Java Hutool 包工具类推荐 ExcelUtil详解
作者:莫傷曉 时间:2023-01-22 23:47:12
Java Hutool 包工具类推荐 ExcelUtil
包引入
hutool包版本号可根据实际情况更换
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.4.M1</version>
</dependency>
除hutool包之外,还需要引入操作Excel必要包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-full</artifactId>
<version>5.0.0</version>
</dependency>
一般简单表头Excel封装工具类
直接上代码
package io.supers.common.utils;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.style.StyleUtil;
import io.supers.framework.em.BaseErrorEnum;
import io.supers.framework.exception.RRException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Excel 工具类
*
* @author guoc
* @date 2022年05月31日 下午 17:21
*/
public class ExcelUtils {
/**
* 下载 Excel 模板 (只有表头的 Excel)
*
* @param response response
* @param headers 表头
* @param fileName 文件名
*/
public static void exportHeaders(HttpServletResponse response, List<String> headers, String fileName) {
export(response, null, headers, fileName);
}
/**
* 导出或下载 Excel 公用方法
*
* @param response 当前请求的 HttpServletResponse
* @param rows 需要写入的数据 List
* @param fileName 最终文件名
*/
public static void export(HttpServletResponse response, List<Map<String, Object>> rows, List<String> headers, String fileName) {
// 获取 Writer
ExcelWriter writer = ExcelUtil.getWriter(true);
// 写入表头
writer = writer.writeHeadRow(headers);
// 若是有数据 则写入数据
if (CollectionUtils.isNotEmpty(rows)) {
writer.write(rows);
}
Workbook workbook = writer.getWorkbook();
CellStyle defaultCellStyle = StyleUtil.createDefaultCellStyle(workbook);
DataFormat format = writer.getWorkbook().createDataFormat();
// 默认为 文本格式
defaultCellStyle.setDataFormat(format.getFormat("@"));
// 默认为 居中
defaultCellStyle.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < headers.size(); i++) {
String h = headers.get(i);
h = h == null ? " " : h;
writer.setColumnStyle(i, defaultCellStyle);
// 默认宽度为 3 * 表头字符数
writer.setColumnWidth(i, 3 * h.length());
}
try {
// 弹出下载对话框的文件名,不能为中文,中文请自行编码
fileName = URLUtil.encode(fileName);
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
response.setContentType(ExcelUtil.XLSX_CONTENT_TYPE);
// 输出
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
// 关闭writer,释放内存
writer.close();
//此处记得关闭输出Servlet流
IoUtil.close(out);
} catch (IOException e) {
e.printStackTrace();
throw new RRException(BaseErrorEnum.COMMON_ERROR, "下载文件失败!\n" + e.getMessage());
}
}
/**
* 读取上传到后台的excel
*
* @param file MultipartFile 上传的文件
* @return 数据列表
* @throws IOException e
*/
public static List<Map<String, Object>> readExcelRows(MultipartFile file) throws IOException {
return ExcelUtil.getReader(file.getInputStream()).readAll();
}
}
工具类封装了三个方法, 只写入表头方法, 写入表头和数据方法 和 读取表格数据列表方法。
三个方法的操作简单,看代码就能明白,不多赘述了。
复杂表头或表格内合并单元格写入
合并单元格核心方法
// cn.hutool.poi.excel.ExcelWriter#merge(int, int, int, int, java.lang.Object, boolean)
/**
* 合并某行的单元格,并写入对象到单元格<br>
* 如果写到单元格中的内容非null,行号自动+1,否则当前行号不变<br>
* 样式为默认标题样式,可使用{@link #getHeadCellStyle()}方法调用后自定义默认样式
*
* @param firstRow 起始行,0开始
* @param lastRow 结束行,0开始
* @param firstColumn 起始列,0开始
* @param lastColumn 结束列,0开始
* @param content 合并单元格后的内容
* @param isSetHeaderStyle 是否为合并后的单元格设置默认标题样式,只提取边框样式
* @return this
* @since 4.0.10
*/
public ExcelWriter merge(int firstRow, int lastRow, int firstColumn, int lastColumn, Object content, boolean isSetHeaderStyle) {
Assert.isFalse(this.isClosed, "ExcelWriter has been closed!");
CellStyle style = null;
if (null != this.styleSet) {
style = styleSet.getStyleByValueType(content, isSetHeaderStyle);
}
return merge(firstRow, lastRow, firstColumn, lastColumn, content, style);
}
看完一般表头写入的代码,可以得知,此工具类写入表头时只需传入表头的字符串列表,即 List<String>,若是遇到动态表头时,则可以通过遍历的操作,先生成出导出数据中所有需要的表头信息,即可为下一步的写入数据的数据列表List<Map<String,Object>> 做准备了。
若是遇到某列或某些列中有合并单元格的,一般都有规律的,可以遍历数据时根据合并的数据项内容通过合并单元格方法进行合并单元格操作。
来源:https://www.cnblogs.com/mlxs/archive/2022/09/30/16745344.html
标签:Java,Hutool,包工具类,ExcelUtil
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#实现计算器窗体程序
2023-04-09 01:25:42
![](https://img.aspxhome.com/file/2023/2/100222_0s.jpg)
Java中的ThreadLocal详解
2023-01-02 16:02:21
![](https://img.aspxhome.com/file/2023/5/71645_0s.png)
C#实现类型的比较示例详解
2022-02-18 18:17:44
![](https://img.aspxhome.com/file/2023/1/126111_0s.png)
Springboot 整合 RabbitMQ 消息队列 详情
2021-07-17 18:49:42
![](https://img.aspxhome.com/file/2023/7/113497_0s.png)
java byte数组与int,long,short,byte的转换实现方法
2023-09-08 12:26:43
C#生成随机数实例
2023-09-17 23:28:28
浅谈Java中ThreadLocal内存泄露的原因及处理方式
2021-06-12 21:08:37
![](https://img.aspxhome.com/file/2023/1/108211_0s.png)
Android实现图像灰度化、线性灰度变化和二值化处理方法
2021-10-17 15:49:10
Android自定义View模仿即刻点赞数字切换效果实例
2023-08-26 12:45:39
![](https://img.aspxhome.com/file/2023/6/110706_0s.gif)
Android提高之SQLite分页读取实现方法
2022-11-28 22:44:04
![](https://img.aspxhome.com/file/2023/4/138894_0s.gif)
C#中使用CAS实现无锁算法的示例详解
2023-07-01 20:57:44
java使用listIterator逆序arraylist示例分享
2022-06-16 05:33:10
![](https://img.aspxhome.com/file/2023/4/104004_0s.jpg)
老生常谈 Java中的继承(必看)
2023-06-21 11:59:51
![](https://img.aspxhome.com/file/2023/2/80982_0s.jpg)
详解Java类库的概念以及import的使用方法
2022-04-18 06:56:54
![](https://img.aspxhome.com/file/2023/4/62774_0s.png)
C#使用第三方组件生成二维码汇总
2023-10-03 22:15:21
![](https://img.aspxhome.com/file/2023/9/100089_0s.png)
C#使用webbrowser的常见用法实例
2023-06-14 13:57:45
java8 stream 如何打印数据元素
2022-08-20 18:40:02
C语言编程中统计输入的行数以及单词个数的方法
2021-06-08 10:49:31
字符串阵列String[]转换为整型阵列Int[]的实例
2021-07-22 08:19:17
![](https://img.aspxhome.com/file/2023/1/116531_0s.jpg)
Android 如何获取设备唯一标识
2022-09-03 10:47:48