程序员scholar 程序员scholar
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
npm

(进入注册为作者充电)

  • 快速入门

  • 克隆

  • 类型转换

  • 日期时间

  • IO流相关

  • 工具类

  • 语言特性

  • JavaBean

  • 集合类

  • Map

  • Codec编码

  • 文本操作

  • 注解

  • 比较器

  • 异常

  • 数学

  • 线程和并发

  • 图片

  • 网络

  • 源码编译

  • 配置文件

  • 日志

  • 缓存

  • JSON

  • 加密解密

  • DFA查找

  • HTTP客户端

  • 定时任务

  • 扩展

  • 切面

  • 脚本

  • Office文档操作

    • Excel工具 - `ExcelUtil`
    • Excel 生成工具 - `ExcelWriter`
      • 1. 将行列对象写出到 Excel
      • 2. 写出 Map 数据
      • 3. 写出 Bean 数据
      • 4. 自定义 Bean 的 key 别名(排序标题)
      • 5. 写出到流(用于 Web 文件下载)
      • 6. 自定义 Excel 样式
        • 6.1 设置单元格背景色
        • 6.2 自定义字体样式
        • 6.3 写出多个 Sheet
    • Excel大数据生成工具 - `BigExcelWriter`
    • Excel读取工具 - `ExcelReader`
    • Word生成工具 - `Word07Writer`
    • 流方式读取Excel 2003 - `Excel03SaxReader`
    • 流方式读取 Excel 2007 - `Excel07SaxReader`
  • 系统调用

  • 图形验证码

  • 网络Socket

  • JWT

  • Hutoll
  • Office文档操作
scholar
2024-08-20
目录

Excel 生成工具 - ExcelWriter

好的,以下是更为完整和详细的 ExcelWriter 工具总结,包括写出到客户端下载、自定义 Excel 相关的示例代码。每个示例都是完整的,并附上了详细的注释。


# Excel 生成工具 - ExcelWriter

介绍

ExcelWriter 是 Hutool 提供的用于将数据写出到 Excel 文件的工具类,支持多种数据格式的写入,如 List、Map、JavaBean 等,还支持自定义单元格样式、合并单元格、导出多 Sheet、设置字体颜色等功能。ExcelWriter 是对 Apache POI 的进一步封装,使用更为简单方便。

# 1. 将行列对象写出到 Excel

将嵌套的 List<List<String>> 形式的数据写出到 Excel,每个内层 List 代表一行数据。

  • 方法签名:
public ExcelWriter write(List<?> data, boolean isWriteKeyAsHead)
1
  • 参数:

    • data:需要写入的数据。
    • isWriteKeyAsHead:是否将第一行作为标题写入。
  • 返回值:ExcelWriter 对象,链式调用。

  • 使用场景:适用于直接将简单的行列数据写出到 Excel 文件中。

  • 完整示例代码:

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.core.collection.CollUtil;

import java.util.List;

public class ExcelWriterExample {
    public static void main(String[] args) {
        // 构建行列数据,每个 List<String> 代表一行
        List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
        List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1");
        List<String> row3 = CollUtil.newArrayList("aa2", "bb2", "cc2", "dd2");
        List<String> row4 = CollUtil.newArrayList("aa3", "bb3", "cc3", "dd3");
        List<String> row5 = CollUtil.newArrayList("aa4", "bb4", "cc4", "dd4");

        // 将所有行数据放入一个 List 中
        List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5);

        // 通过工具类创建 ExcelWriter,指定输出路径
        ExcelWriter writer = ExcelUtil.getWriter("d:/writeTest.xlsx");

        // 跳过当前行(第一行)
        writer.passCurrentRow();

        // 合并单元格后的标题行,使用默认标题样式
        writer.merge(row1.size() - 1, "测试标题");

        // 一次性写出内容,强制输出标题
        writer.write(rows, true);

        // 关闭 writer,释放内存
        writer.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

效果图:

写出效果图


# 2. 写出 Map 数据

可以将 Map 数据写出到 Excel,其中键值对将作为 Excel 的标题和内容。

  • 方法签名:
public ExcelWriter write(List<? extends Map<?, ?>> data, boolean isWriteKeyAsHead)
1
  • 参数:

    • data:包含 Map 数据的 List。
    • isWriteKeyAsHead:是否将 Map 的键作为标题。
  • 返回值:ExcelWriter 对象,链式调用。

  • 使用场景:适用于将 Map 数据导出为 Excel 文件。

  • 完整示例代码:

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.List;

public class ExcelWriterExample {
    public static void main(String[] args) {
        // 构建 Map 数据,每个 Map 代表一行数据
        Map<String, Object> row1 = new LinkedHashMap<>();
        row1.put("姓名", "张三");
        row1.put("年龄", 23);
        row1.put("成绩", 88.32);
        row1.put("是否合格", true);
        row1.put("考试日期", DateUtil.date());

        Map<String, Object> row2 = new LinkedHashMap<>();
        row2.put("姓名", "李四");
        row2.put("年龄", 33);
        row2.put("成绩", 59.50);
        row2.put("是否合格", false);
        row2.put("考试日期", DateUtil.date());

        // 将所有 Map 数据放入一个 List 中
        List<Map<String, Object>> rows = CollUtil.newArrayList(row1, row2);

        // 创建 ExcelWriter,指定输出路径
        ExcelWriter writer = ExcelUtil.getWriter("d:/writeMapTest.xlsx");

        // 合并单元格后的标题行,使用默认标题样式
        writer.merge(row1.size() - 1, "一班成绩单");

        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(rows, true);

        // 关闭 writer,释放内存
        writer.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

效果图:

写出效果


# 3. 写出 Bean 数据

对于 Java Bean 数据,可以直接将 Bean 列表写出到 Excel 中。

  • 方法签名:
public ExcelWriter write(List<?> data, boolean isWriteKeyAsHead)
1
  • 参数:

    • data:需要写入的 Bean 数据。
    • isWriteKeyAsHead:是否将 Bean 的字段名作为标题。
  • 返回值:ExcelWriter 对象,链式调用。

  • 使用场景:适用于将实体类数据导出为 Excel 文件。

  • 完整示例代码:

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;

import java.util.List;
import java.util.Date;

public class ExcelWriterExample {
    public static void main(String[] args) {
        // 构建 TestBean 数据
        TestBean bean1 = new TestBean("张三", 22, 66.30, true, DateUtil.date());
        TestBean bean2 = new TestBean("李四", 28, 38.50, false, DateUtil.date());

        List<TestBean> rows = CollUtil.newArrayList(bean1, bean2);

        // 创建 ExcelWriter,指定输出路径
        ExcelWriter writer = ExcelUtil.getWriter("d:/writeBeanTest.xlsx");

        // 合并单元格后的标题行,使用默认标题样式
        writer.merge(4, "一班成绩单");

        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(rows, true);

        // 关闭 writer,释放内存
        writer.close();
    }
}

// 定义 TestBean 类
class TestBean {
    private String name;
    private int age;
    private double score;
    private boolean isPass;
    private Date examDate;

    public TestBean(String name, int age, double score, boolean isPass, Date examDate) {
        this.name = name;
        this.age = age;
        this.score = score;
        this.isPass = isPass;
        this.examDate = examDate;
    }

    // Getters 和 Setters 省略
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

效果图:

写出Bean数据


# 4. 自定义 Bean 的 key 别名(排序标题)

在写出 Bean 数据时,可以通过 addHeaderAlias 方法自定义字段的别名,使得标题更加友好。同时,setOnlyAlias(true) 可以控制是否只输出设置了别名的字段。

  • 完整示例代码:
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.core.collection.CollUtil;

import java.util.List;

public class ExcelWriterExample {
    public static void main(String[] args) {
        // 构建 TestBean 数据
        TestBean bean1 = new TestBean("张三", 22, 66.30, true);
        TestBean bean2 = new TestBean("李四", 28, 38.50, false);

        List<TestBean> rows = CollUtil.newArrayList(bean1, bean2);

        // 创建 ExcelWriter,指定输出路径
        ExcelWriter writer = ExcelUtil.getWriter("d:/writeBeanTest.xlsx");

        // 自定义标题别名
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("age", "年龄");


        writer.addHeaderAlias("score", "分数");
        writer.addHeaderAlias("isPass", "是否通过");

        // 只输出设置了别名的字段
        writer.setOnlyAlias(true);

        // 合并单元格后的标题行,使用默认标题样式
        writer.merge(4, "一班成绩单");

        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(rows, true);

        // 关闭 writer,释放内存
        writer.close();
    }
}

// 定义 TestBean 类
class TestBean {
    private String name;
    private int age;
    private double score;
    private boolean isPass;

    public TestBean(String name, int age, double score, boolean isPass) {
        this.name = name;
        this.age = age;
        this.score = score;
        this.isPass = isPass;
    }

    // Getters 和 Setters 省略
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

效果图:

img


# 5. 写出到流(用于 Web 文件下载)

可以将数据写出到输出流,这种方式常用于与 Web 服务器集成,实现文件下载。

  • 完整示例代码:
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ExcelWriterExample {
    public static void main(String[] args) throws Exception {
        // 构建 TestBean 数据
        TestBean bean1 = new TestBean("张三", 22, 66.30, true);
        TestBean bean2 = new TestBean("李四", 28, 38.50, false);

        List<TestBean> rows = CollUtil.newArrayList(bean1, bean2);

        // 创建 ExcelWriter,指定输出路径
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 合并单元格后的标题行,使用默认标题样式
        writer.merge(4, "一班成绩单");

        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(rows, true);

        // 设置响应头信息,实现文件下载
        HttpServletResponse response = // 获取 HttpServletResponse 对象;
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
        ServletOutputStream out = response.getOutputStream();

        // 将数据写出到输出流
        writer.flush(out, true);

        // 关闭 writer,释放内存
        writer.close();

        // 关闭输出流
        IoUtil.close(out);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

# 6. 自定义 Excel 样式

Hutool 提供了丰富的样式自定义功能,如设置单元格背景色、自定义字体、写出多个 Sheet 等。

# 6.1 设置单元格背景色

  • 完整示例代码:
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.IndexedColors;

public class ExcelWriterExample {
    public static void main(String[] args) {
        // 创建 ExcelWriter
        ExcelWriter writer = ExcelUtil.getWriter("d:/writeTest.xlsx");

        // 设置单元格背景色,第二个参数表示是否设置标题背景色
        writer.getStyleSet().setBackgroundColor(IndexedColors.YELLOW, false);

        // 写出数据(数据略)
        // ...

        // 关闭 writer,释放内存
        writer.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 6.2 自定义字体样式

  • 完整示例代码:
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.Font;

public class ExcelWriterExample {
    public static void main(String[] args) {
        // 创建 ExcelWriter
        ExcelWriter writer = ExcelUtil.getWriter("d:/writeTest.xlsx");

        // 自定义字体样式
        Font font = writer.createFont();
        font.setBold(true);
        font.setColor(Font.COLOR_RED);
        font.setItalic(true);

        // 设置内容字体,第二个参数表示是否忽略标题样式
        writer.getStyleSet().setFont(font, true);

        // 写出数据(数据略)
        // ...

        // 关闭 writer,释放内存
        writer.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 6.3 写出多个 Sheet

  • 完整示例代码:
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

public class ExcelWriterExample {
    public static void main(String[] args) {
        // 创建 ExcelWriter,并初始化 Sheet1
        ExcelWriter writer = new ExcelWriter("d:/multiSheet.xlsx", "Sheet1");

        // 写出数据到 Sheet1(数据略)
        // ...

        // 切换到 Sheet2
        writer.setSheet("Sheet2");

        // 写出数据到 Sheet2(数据略)
        // ...

        // 关闭 writer,释放内存
        writer.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

通过以上详细总结和完整的示例代码,你可以更好地理解如何在实际项目中使用 ExcelWriter 来实现各种 Excel 数据写出需求。如果有其他常用但未涉及的功能,也可以帮助你进一步总结补充。

编辑此页 (opens new window)
上次更新: 2024/12/28, 18:32:08
Excel工具 - `ExcelUtil`
Excel大数据生成工具 - `BigExcelWriter`

← Excel工具 - `ExcelUtil` Excel大数据生成工具 - `BigExcelWriter`→

Theme by Vdoing | Copyright © 2019-2025 程序员scholar
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式