Skip to content

其实对于Excel读取部分一般都是不复杂的,让客户根据指定行进行读取即可。但是写入可能就会涉及到许多自定义导出部分,例如导出指定列。

忽略某些列,使其不导出

java
@GetMapping("download/exclude")
public void downloadExcludeColumn(HttpServletResponse response) throws IOException {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    String fileName = URLEncoder.encode("测试", StandardCharsets.UTF_8).replaceAll("\\+", "%20");

    // 根据用户传入字段,假设我们要忽略 date
    Set<String> excludeColumnFiledNames = new HashSet<>();
    excludeColumnFiledNames.add("date");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream(), DemoData.class).excludeColumnFieldNames(excludeColumnFiledNames).sheet("模板").doWrite(getList());
}

只导出选中列

java
@GetMapping("download/include")
public void downloadExcludeColumn(HttpServletResponse response) throws IOException {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    String fileName = URLEncoder.encode("测试", StandardCharsets.UTF_8).replaceAll("\\+", "%20");

    // 根据用户传入字段,例如只导出data和title列
    Set<String> includeColumnFiledNames = new HashSet<>();
    includeColumnFiledNames.add("date");
    includeColumnFiledNames.add("title");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream(), DemoData.class).includeColumnFieldNames(includeColumnFiledNames).sheet("模板").doWrite(getList());
}