【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);
            }
		}
	}
}
相关推荐
独自破碎E4 分钟前
IDEA2023中新建Spring Boot2.X版本的工程的方法
java·spring boot·后端
醇氧8 分钟前
【idea】使用Live Templates
java·ide·intellij-idea
talenteddriver14 分钟前
Java Web:http请求在springboot项目中的传递层级(自用笔记)
java·前端·spring boot·http
咘噜biu19 分钟前
Java后端和前端的接口数据加密方案(椭圆曲线集成加密方案)
java·前端·安全·aes·密钥协商ecdh·椭圆曲线集成加密方案
零雲24 分钟前
java面试:@Resource和@Autowired的区别
java·开发语言·面试
007php00728 分钟前
Git 操作偏门指南:常用和隐藏命令与问题解决
java·git·面试·职场和发展·golang·jenkins·php
li.wz32 分钟前
溯源数据清洗:一次由“可控”到“失控”的复盘
java·后端·doris
仅此,35 分钟前
Java请求进入Python FastAPI 后,请求体为空,参数不合法
java·spring boot·python·组合模式·fastapi
毕设源码-郭学长38 分钟前
【开题答辩全过程】以 基于springboot的健身房信息管理为例,包含答辩的问题和答案
java·spring boot·后端
爱编码的傅同学1 小时前
【单例模式】深入理解懒汉与饿汉模式
java·javascript·单例模式