SpringBoot导出EXCEL表格
程序员文章站
2024-03-20 15:56:04
...
1.导入依赖
<!-- easyexcel相关依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
2.创建实体类
- 创建的实体类不能是数据库中的表,会多出一个字段。
- 继承BaseRowModel类。
- 字段上面的注解是显示在excel表格中的列名。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseBudget extends BaseRowModel {
@ExcelProperty(value = "姓名", index = 0)
public String name;
@ExcelProperty(value = "费用", index = 1)
public Integer cost;
}
3.导出Excel表格
//这里传入的参数为id,可以根据需要换成自己的参数
public void excelExport(HttpServletResponse response,Long id) throws IOException {
List<BaseBudget> list = toAccount(id);
//表格的名称
String fileName = "用户账单";
//下面几行都是默认配置,不用管
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xls");
ServletOutputStream out = response.getOutputStream();
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLS,true);
//创建一个sheet , 最后一个参数必须是继承了 BaseRowModel 的类
Sheet sheet = new Sheet(1,0,BaseBudget.class);
//设置自适应宽度
sheet.setAutoWidth(Boolean.TRUE);
sheet1.setAutoWidth(Boolean.TRUE);
sheet.setSheetName("用户账单");
//将list数组写入 sheet 中
writer.write(list,sheet);
writer.finish();
out.flush();
response.getOutputStream().close();
out.close();
}
上一篇: 自学python笔记(一)