上代码
@RequestMapping(value = "/test", method = RequestMethod.GET)
public Result test(HttpServletRequest request, HttpServletResponse response){
try (OutputStream outputStream = response.getOutputStream()){
response.setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode("哒哒", "UTF-8") +".xls");
HSSFWorkbook wb = ExcelUtils.export(Arrays.asList("zm"));
wb.write(outputStream);
outputStream.flush();
}catch (IOException e){
LOGGER.error("exportOrderBill error. ", e);
return Result.error("导出失败." + e.getMessage());
}catch (Exception e){
LOGGER.error("exportOrderBill error. ", e);
return Result.error("导出失败." + e.getMessage());
}
return Result.error("导出失败.");
}
public static HSSFWorkbook export(Object data){
HSSFWorkbook hwb = new HSSFWorkbook();
//新增sheet
HSSFSheet sheet = hwb.createSheet();
int rowIndex = 0;
Row headerRow = sheet.createRow(rowIndex++);
String [] headers = {"姓名"};
//设置表头
for (int hIndex = 0; hIndex < headers.length ; hIndex++){
headerRow.createCell(hIndex).setCellValue(headers[hIndex]);
}
//设置内容
for (String str: list) {
//新增行
HSSFRow row = sheet.createRow(rowIndex++);
int cellIndex = 0;
//新增单元格
row.createCell(cellIndex++).setCellValue(str);
}
return hwb;
}
遇到的问题
文件名乱码
尝试如下设置,没有用
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream;utf-8");
response.setHeader("Content-Disposition","attachment; filename="哒哒.xls");
效果如下:
![](https://img.haomeiwen.com/i4155655/d80fb3e8be289017.png)
再试:
response.setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode("哒哒", "UTF-8") +".xls");
![](https://img.haomeiwen.com/i4155655/11e28b3b8f243bf1.png)
网友评论