問題概要
利用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();
