1.导入依赖
< 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表格
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 sheet = new Sheet ( 1 , 0 , BaseBudget . class ) ;
sheet. setAutoWidth ( Boolean . TRUE) ;
sheet1. setAutoWidth ( Boolean . TRUE) ;
sheet. setSheetName ( "用户账单" ) ;
writer. write ( list, sheet) ;
writer. finish ( ) ;
out. flush ( ) ;
response. getOutputStream ( ) . close ( ) ;
out. close ( ) ;
}