【Java】ExcelWriter自适应宽度工具类(支持中文)

工具类

java 复制代码
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * Excel工具类
 *
 * @author xiaoming
 * @date 2023/11/17 10:40
 */
public class ExcelUtils {

	/**
     * 自适应宽度(支持中文)
     *
     * @param sheet 表单
     * @param size  因为for循环从0开始,size值为 列数-1
     */
    public static void setSizeColumn(Sheet sheet, int size) {
        for (int columnNum = 0; columnNum <= size; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row currentRow;
                // 当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }

                if (currentRow.getCell(columnNum) != null) {
                    Cell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == CellType.STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }
}

工具类使用方法

java 复制代码
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.xxx.utils.ExcelUtils;
import com.xxx.entity.Entity;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.bind.annotation.*;

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

/**
 * 文件接口
 *
 * @author xiaoming
 * @date 2023/11/17 10:50
 */
@RestController
@RequestMapping("/file")
public class FileController {

	@PostMapping("exportExcel")
	public void exportExcel(HttpServletResponse response) {
		// 假设这里有个List是要导出用的
		List<Entity> list = ...;

		ExcelWriter writer = ExcelUtil.getWriter(true);
		writer.addHeaderAlias("field1", "fieldValue1")
				.addHeaderAlias("field2", "fieldValue2")
				.addHeaderAlias("field3", "fieldValue3");
		
		if (CollUtil.isNotEmpty(list)) {
			writer.write(list, true);

			// 就只有下面两步操作,根据上面addHeaderAlias的个数减一就行,上面是三个,所以填二
			Sheet sheet = writer.getSheet();
			ExcelUtils.setSizeColumn(sheet, 2);

			ServletOutputStream out = null
			try {
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
				response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("xxx.xlsx", "UTF-8"));
				out = response.getOutputStream();
				writer.flush(out, true);
			} catch (IOException e) {
                e.printStackTrace();
            } finally {
                writer.close();
                IoUtil.close(out);
            }
		}
	}
}
相关推荐
李游Leo15 分钟前
Redis 持久化与高可用实践(RDB / AOF / Sentinel / Cluster 全解析)
java·spring·bootstrap
mask哥35 分钟前
详解mcp以及agen架构设计与实现
java·微服务·flink·大模型·ai agent·springai·mcp
Propeller1 小时前
【Android】View 交互的事件处理机制
android·java
杨杨杨大侠1 小时前
Atlas Mapper 教程系列 (5/10):集合映射与嵌套对象处理
java·开源·github
ERP老兵_冷溪虎山1 小时前
Python/JS/Go/Java同步学习(第十三篇)四语言“字符串转码解码“对照表: 财务“小南“纸式转码术处理凭证乱码崩溃(附源码/截图/参数表/避坑指南)
java·后端·python
是2的10次方啊1 小时前
如何设计10万QPS秒杀系统?缓存+消息队列+分布式锁架构实战
java
心灵宝贝1 小时前
Tomcat Connectors 1.2.37 源码编译安装教程(mod_jk 详细步骤)
java·tomcat
杨杨杨大侠1 小时前
Atlas Mapper 教程系列 (6/10):Spring Boot 集成与自动配置
java·开源·github
傻傻虎虎1 小时前
【Docker】容器端口暴露+镜像生成实战
java·docker·容器
练习时长一年1 小时前
搭建langchain4j+SpringBoot的Ai项目
java·spring boot·后端