- 单sheet页写出
private static List<DataTemplate> data() {
return data(10);
}
private static List<DataTemplate> data(int size) {
List<DataTemplate> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
DataTemplate data = new DataTemplate();
data.setMoney(i + 0.111);
data.setDate(new Date());
data.setValue(i + 0.111);
data.setUserid("userid " + i);
list.add(data);
}
return list;
}
public static void main(String[] args) {
String fileName = "D:\\Users\\lvhb\\Desktop\\templatewrite.xlsx";
EasyExcel.write(fileName, DataTemplate.class).sheet("模板").doWrite(data());
}
单sheet页导出没什么问题
- 多sheet页导出
@Test
public void test3(){
String fileName = "D:\\Users\\lvhb\\Desktop\\templatewrite.xlsx";
ExcelWriter excelWriter = EasyExcel.write(fileName).head(DataTemplate.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0,"11").build();
excelWriter.write(data(10),writeSheet);
writeSheet = EasyExcel.writerSheet(1,"22").build();
excelWriter.write(data(20),writeSheet);
}
此时可能会遇到文件生成问题
此时需要调一下excelWriter.finish()方法将缓冲区中的数据全部写出。
excelWriter.finish();
- web下载
@ResponseBody
@GetMapping("exportSheet")
public void exportSheet(HttpServletResponse response) throws Exception {
response.setContentType("application/force-download");// 设置强制下载不打开
// response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
String filename = URLEncoder.encode("数据导出", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+filename+".xlsx");//弹出下载窗体
ServletOutputStream os = response.getOutputStream();
ExcelWriter excelWriter = EasyExcel.write(os).head(DataTemplate.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0,"11111").build();
excelWriter.write(data(10),writeSheet);
writeSheet = EasyExcel.writerSheet(1,"2222222").build();
excelWriter.write(data(20),writeSheet);
excelWriter.finish();
os.close();
}