踩坑记-利用Apche-POI.XSSFWorkbook.write,处理excel文件,通过response.outputstram下载文件,预览乱码。
问题概要
利用Apche-POI.XSSFWorkbook.write,处理excel文件,通过response.outputstram导出文件,预览乱码。
解决办法
1.检查设置response,代码如下:
response.setContentType("application/msdownload");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment; filename="
+ URLEncoder.encode(filename, "UTF-8"));
--- 如果步骤一,导出excel依旧乱码;按步骤二继续;
2.利用XSSFWorkbook.write,将excel写到本地,通过字节流导出文件,代码如下:
XSSFWorkbook xssfWorkbook = new ;
xssfWorkbook= new XSSFWorkbook(InputSteam);
// 利用request,获取服务器绝对路径
File dest = new File(request.getSession().getServletContext().getRealPath("/") + "cache\\" );
// 判断文件目录是否存在
if(!dest.exists()){
dest.mkdir();
}
Date date = new Date();
// 获取datetime,避免文件名重复
String dateTime = "" + date.getTime();
File file = new File(dateTime + "test.xlsx");
OutputStream out = new FileOutputStream(file);
xssfWorkbook.write(out);
InputStream is = new FileInputStream(file);
int len = 0;
byte buffer[] = new byte[1024];
while ((len = is.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
// 删除缓存文件
file.delete();
// 关闭流,try-catch-finally
out.close();
is.close();
outputStream.flush();
outputStream.close();