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