首页 > 编程语言 > 详细

java poi 导出excel自适应列宽

时间:2020-11-03 15:05:34      阅读:227      评论:0      收藏:0      [点我收藏+]
public static void setAutoColumnWidth(HSSFSheet sheet,int maxColumnNum) {
        try{
            //获取当前列的宽度,然后对比本列的长度,取最大值
            for (int columnNum = 0; columnNum <= maxColumnNum; 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);
                        int length = currentCell.toString().getBytes("GBK").length;
                        if (columnWidth < length + 1)
                        {
                            columnWidth = length + 1;
                        }
                    }
                }
                sheet.setColumnWidth(columnNum, columnWidth * 300);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

 

java poi 导出excel自适应列宽

原文:https://www.cnblogs.com/xiaopengL/p/13919504.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!