导出excel,多个sheet页

863 阅读1分钟

excel多个sheet导出,通过easyexcel实现

image.png

1、导入依赖

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

2、工具类

public class ExcelUtils {

    public static void export(HttpServletResponse response, String fileName, List<Student> list) throws IOException {

        // 表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 设置表头剧中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        // 内容样式
        WriteCellStyle contentWriteCellStyl = new WriteCellStyle();
        // 设置内容靠左
        contentWriteCellStyl.setHorizontalAlignment(HorizontalAlignment.LEFT);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置中文乱码
        fileName = URLEncoder.encode(fileName, "utf-8");
        response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

        // sheet1,可以根据需求添加多个sheet页
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet名称").head(Student.class).build();
        excelWriter.write(list, writeSheet);
        // sheet2
        WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "sheet2名称").head(Student.class).build();
        excelWriter.write(list, writeSheet2);

        excelWriter.finish();

    }
}

3、controller调用

/**
 * @param response
 * @throws IOException
 */
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
    List<Student> list =  warehouseService.getStudentByCondition();
    ExcelUtils.export(response, "导出", list);
}

4、实体类编写(如果属性不想让导出,可添加@ExcelIgnore注解)

@Data
@Builder
public class Student {

    @ExcelProperty(value = "编号", index = 0)
    private String id;
    @ExcelProperty(value = "名称", index = 1)
    private String name;
    @ExcelProperty(value = "年龄", index = 2)
    private Integer age;
}

结果展示

image.png 第一次写不会说啥,勿喷