easyExcel实现简单的excel导出/下载功能

1.定义实体类

@Data
public class ExcelEntity {

    @ExcelIgnore
    private Long id;

    //上传的话 可以不加这个注解@ExcelProperty, index从0开始
    @ExcelProperty(value = "姓名",index = 0)
    private String name;

    @ExcelProperty(value = "年龄",index = 1)
    private Integer age;

    @ColumnWidth(20)
    @ExcelProperty(value = "生日",index = 2)
    private String birthday;

}

2.测试代码

/**
     * 下载/导出 excel
     * @param response
     * @throws IOException
     */
    @RequestMapping("/write")
    public void write(HttpServletResponse response) throws IOException {
        //这里模拟要导出的excel里的数据
        ListdataList = new ArrayList<>();
        ExcelEntity excelEntity1 = new ExcelEntity();
        excelEntity1.setAge(20);
        excelEntity1.setName("李明");
        excelEntity1.setBirthday("2021-01-18 13:45:00");
        ExcelEntity excelEntity2 = new ExcelEntity();
        excelEntity2.setName("王刚");
        excelEntity2.setAge(11);
        excelEntity2.setBirthday("2020-11-09 13:45:00");
        dataList.add(excelEntity1);
        dataList.add(excelEntity2);
        //文件名必须经过encode,否则名称不对
        String fileName = URLEncoder.encode("导出的excel.xlsx", "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-disposition", "attachment;fileName="+fileName);
        //内容样式
        WriteCellStyle cellStyle = new WriteCellStyle();
        //居中
        cellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        //参数:表头样式对象,列样式对象
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, cellStyle);


        //获取响应的输出流
        ServletOutputStream outputStream = null;
        try{
            outputStream = response.getOutputStream();
            EasyExcel.write(outputStream,ExcelEntity.class)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .sheet("sheet1")
                    .doWrite(dataList);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (null != outputStream){
                outputStream.flush();
                outputStream.close();
            }
        }
    }

你可能感兴趣的:(excel,java,easyExcel)