Excel POI设置自适应宽度

复制代码
/**
 *  自适应列宽
 * @param sheet
 * @param columnLength 列数
 */
private static void setSizeColumn(HSSFSheet sheet, int columnLength) {
    for (int columnNum = 0; columnNum <= columnLength; columnNum++) {
         int columnWidth = sheet.getColumnWidth(columnNum) / 256;
         for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
             HSSFRow currentRow; // 当前行未被使用过
             if (sheet.getRow(rowNum) == null) {
                 currentRow = sheet.createRow(rowNum);
             } else {
                 currentRow = sheet.getRow(rowNum);
             }
             if (currentRow.getCell(columnNum) != null) {
                 HSSFCell currentCell = currentRow.getCell(columnNum);
                 if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                     int length = currentCell.getStringCellValue().getBytes().length;
                     if (columnWidth < length) {
                         columnWidth = length;
                     }
                 }
             }
         }
         sheet.setColumnWidth(columnNum, columnWidth * 256);
    }
}
复制代码

注:HSSFCell.CELL_TYPE_STRING若过期,则使用CellType.STRING
参考链接:https://blog.csdn.net/taisuiyu6397/article/details/107490858

posted @   一隅桥畔  阅读(702)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示