EasyExcel excel 模板文件下载
时间: 2023-08-16 17:03:35 浏览: 191
您可以使用EasyExcel来实现excel模板文件下载功能。下面是一个示例代码,供您参考:
```java
// 导出excel模板文件
@RequestMapping("/exportTemplate")
public void exportTemplate(HttpServletResponse response) throws IOException {
// 1. 创建excel对应的实体类
List<ExcelTemplate> list = new ArrayList<>();
ExcelTemplate excelTemplate = new ExcelTemplate();
excelTemplate.setName("张三");
excelTemplate.setAge(20);
excelTemplate.setGender("男");
list.add(excelTemplate);
// 2. 设置excel文件名
String fileName = "excel_template.xlsx";
// 3. 设置sheet名
String sheetName = "sheet1";
// 4. 创建ExcelWriter对象
ExcelWriter writer = new ExcelWriterBuilder()
.file(response.getOutputStream())
.excelType(ExcelTypeEnum.XLSX)
.build();
// 5. 创建表格样式
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 12);
headWriteFont.setBold(true);
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
headWriteCellStyle.setBorderRight(BorderStyle.THIN);
headWriteCellStyle.setBorderTop(BorderStyle.THIN);
// 6. 创建表头
List<List<String>> head = new ArrayList<>();
head.add(Arrays.asList("姓名", "年龄", "性别"));
// 7. 写入excel文件
Sheet sheet = new Sheet(1, 0, ExcelTemplate.class);
sheet.setSheetName(sheetName);
Table table = new Table(1);
table.setHead(head);
table.setTableStyle(new TableStyle());
writer.write(list, sheet, table);
// 8. 设置表格样式
sheet.setTableStyle(new TableStyle());
sheet.getTableStyle().setTableContentBackGroundColor(IndexedColors.WHITE.getIndex());
sheet.getTableStyle().setHeadBackGroundColor(IndexedColors.WHITE.getIndex());
sheet.getTableStyle().setTableContentFont(new WriteFont());
sheet.getTableStyle().setTableHeadBackGroundColor(IndexedColors.WHITE.getIndex());
sheet.getTableStyle().setTableHeadFont(headWriteFont);
sheet.getTableStyle().setTableHeadBorderStyle(headWriteCellStyle);
// 9. 设置响应头
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
// 10. 关闭流
writer.finish();
}
```
在上述代码中,我们使用EasyExcel创建了一个ExcelWriter对象,然后根据我们的实体类ExcelTemplate创建了一个Sheet,并设置了表头和表格样式,最后将数据写入表格中,设置响应头并关闭流,即可实现excel模板文件下载功能。
阅读全文