1.导出代码实现
public class EasypoiExport{
public void export(String templatePath, String outputPath, Map<String, String> params){
// 获取数据列表
List<Map<String, Object>> data = Mapper.searchData(params);
// 获取模板
TemplateExportParams templateExportParams =new TemplateExportParams(templatePath+"/模板.xlsx");
// 塞入数据
Map<String,Object> map = new HashMap<>();
map.put("list",JcxqData);
String fileName = "结果.xlsx";
// 生成excel文件
Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, map);
try (FileOutputStream fileOut = new FileOutputStream(outputPath+"/"+fileName)) {
workbook.write(fileOut);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.将文件返回给浏览器
public class Export {
public void exportToBrowser(Map<String, String> params,String templatePath, String outputPath, HttpServletResponse httpServletResponse) throws Exception{
EasypoiExport.export(TemplatePath,OutPath,params);
String outFileName = "结果.xlsx";
//返回给浏览器
File file = new File(OutPath+"/"+outFileName);
String encodedFileName = URLEncoder.encode(file.getName(), "UTF-8");
// Set headers for file download
httpServletResponse.setContentType("application/octet-stream");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+ encodedFileName);
httpServletResponse.setCharacterEncoding("UTF-8");
// Obtain the output stream
OutputStream outputStream = httpServletResponse.getOutputStream();
// Read the file from the file system
FileInputStream fileInputStream = new FileInputStream(file);
// Write the file contents to the response output stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// Close the input stream and flush/close the output stream
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
}
3.模板设置
注: easypoi依赖于poi,且需要与poi版本进行对应