【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);
            }
		}
	}
}
相关推荐
大厂码农老A1 分钟前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
艾菜籽18 分钟前
Spring MVC入门补充2
java·spring·mvc
爆更小哇28 分钟前
统一功能处理
java·spring boot
程序员鱼皮29 分钟前
我造了个程序员练兵场,专治技术焦虑症!
java·计算机·程序员·编程·自学
n8n1 小时前
SpringAI 完全指南:为Java应用注入生成式AI能力
java·后端
不爱编程的小九九1 小时前
小九源码-springboot082-java旅游攻略平台
java·开发语言·旅游
只是懒得想了1 小时前
用C++实现一个高效可扩展的行为树(Behavior Tree)框架
java·开发语言·c++·design-patterns
码农阿树1 小时前
Java 离线视频目标检测性能优化:从 Graphics2D 到 OpenCV 原生绘图的 20 倍性能提升实战
java·yolo·目标检测·音视频
夫唯不争,故无尤也1 小时前
Maven创建Java项目实战全流程
java·数据仓库·hive·hadoop·maven
weixin_404551241 小时前
openrewrite Maven plugin configuration
java·maven·configuration·openrewrite