【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);
            }
		}
	}
}
相关推荐
东阳马生架构6 小时前
商品中心—6.商品考核系统的技术文档
java
晴空月明7 小时前
Java 内存模型与 Happens-Before 关系深度解析
java
皮皮林55110 小时前
SpringBoot 加载外部 Jar,实现功能按需扩展!
java·spring boot
rocksun11 小时前
认识Embabel:一个使用Java构建AI Agent的框架
java·人工智能
Java中文社群12 小时前
AI实战:一键生成数字人视频!
java·人工智能·后端
王中阳Go12 小时前
从超市收银到航空调度:贪心算法如何破解生活中的最优决策谜题?
java·后端·算法
shepherd11112 小时前
谈谈TransmittableThreadLocal实现原理和在日志收集记录系统上下文实战应用
java·后端·开源
维基框架12 小时前
Spring Boot 项目整合Spring Security 进行身份验证
java·架构
日月星辰Ace13 小时前
Java JVM 垃圾回收器(四):现代垃圾回收器 之 Shenandoah GC
java·jvm
天天摸鱼的java工程师14 小时前
商品详情页 QPS 达 10 万,如何设计缓存架构降低数据库压力?
java·后端·面试