当前位置: 首页 > article >正文

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

工具类

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);
        }
    }
}

工具类使用方法

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);
            }
		}
	}
}

http://www.kler.cn/news/134187.html

相关文章:

  • 5 redis的GEO操作
  • 2023/11/19总结
  • 【Flink 问题集】The generic type parameters of ‘Collector‘ are missing
  • linux gdb调试
  • 【数据结构】图的简介(图的逻辑结构)
  • 【ATTCK】MITRE Caldera-emu插件
  • Windows网络「SSL错误问题」及解决方案
  • Python中的迭代器、生成器和装饰器
  • 蓝桥杯单片机综合练习——工厂灯光控制
  • 2311rust到31版本更新
  • 莹莹API管理系统源码附带两套模板
  • 二元分类模型评估方法
  • 6 Redis的慢查询配置原理
  • whisper large-v3 模型文件下载链接
  • 计算机视觉与机器学习D1
  • 软件测试面试-如何定位线上出现bug
  • python使用selenium webDriver时 报错
  • MongoDB随记
  • PHP 数组在底层的实现原理
  • 网页视频下载工具 iTubeGo mac中文版软件特色
  • Apache POI 使用
  • 【自然语言处理】【大模型】赋予大模型使用工具的能力:Toolformer与ART
  • 虹科案例 | AR内窥镜手术应用为手术节约45分钟?
  • 原理Redis-IntSet
  • 9、传统计算机视觉 —— 边缘检测
  • [Linux] PXE批量装机
  • Canal+Kafka实现MySQL与Redis数据同步(二)
  • 《洛谷深入浅出进阶篇》P1995 程序自动分析——并查集,离散化
  • 全新酷盒9.0源码:多功能工具箱软件的最新iapp解决方案
  • 【计算思维】蓝桥杯STEMA 科技素养考试真题及解析 4