java导出Excel(使用阿里巴巴的easyexcel)


1. 第一步导入maven依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.6</version>
</dependency>

2. 第二部创建数据模型(实体类)

@Data
@AllArgsConstructor
public class ExcelEntity {
    @ExcelProperty("姓名 (字符串)")
    private String name;
    @ExcelProperty("生日(时间)")
    private Date birthday;
    @ExcelProperty("年龄(数字)")
    private Integer age;
}

3. 第三步写Controller

@GetMapping("/getExcel")
public void getExcel(HttpServletResponse response) throws IOException {
    List<ExcelEntity> list =  new ArrayList<>(5);
    for (int i=1;i<=10; i++){
        list.add(new ExcelEntity("张"+i,new Date(),i));
    }
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    String fileName = URLEncoder.encode("导出表格", "UTF-8");
    response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream(), ExcelEntity.class).sheet("模板").doWrite(list);
}

4. 第四步测试

访问地址:http://localhost:8080/excel/getExcel

成功结果

有问题质询QQ:248048521,欢迎技术交流

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM