前言
在开发过程中如有此业务需求,那么本文或许能给你派上用场。
工具类
/* 导出txt文件
* @author
* @param response
* @param text 导出的字符串
* @return
*/
public void exportTxt(HttpServletResponse response,String text){
response.setCharacterEncoding("utf-8");
// 设置响应的内容类型
response.setContentType("text/plain");
// 设置文件的名称和格式
response.addHeader("Content-Disposition", "attachment;filename="+genAttachmentFileName("文件名称", "JSON_FOR_UCC_")+".txt");//设置名称格式,没有这个中文名称无法显示
BufferedOutputStream buff = null;
ServletOutputStream outStr = null;
try {
outStr = response.getOutputStream();
buff = new BufferedOutputStream(outStr);
buff.write(text.getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
System.out.println("导出文件文件出错");
}finally {
try {
buff.close();
outStr.close();
} catch (Exception e) {
System.out.println("关闭流对象出错");
}
}
}
/**
* 防止中文文件名显示出错
*
* @param cnName
* @param defaultName
* @return
*/
public String genAttachmentFileName(String cnName, String defaultName){
try {
cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
} catch (Exception e) {
cnName = defaultName;
}
return cnName;
}
使用
/*
* 将查询的结果作为导出结果
* @author
* @param
* @return
*/
@RequestMapping("exportLog.do")
public void exportLog(HttpServletResponse response,MchRebateListForm fom){
//获取日志
fom.setPageNumber(0);
fom.setPageSize(30000);//最大数量
List<MchHelpReturnCommission> list = mchRebateService.list_MchHelpRebate(fom);
//拼接字符串
StringBuffer text = new StringBuffer();
for(MchHelpReturnCommission log:list){
text.append(log.getMydata());
text.append("\r\n");//换行字符
}
exportTxt(response,text.toString());
}