Java apache poi excel 大自动列宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20190317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:52:50  来源:igfitidea点击:

apache poi excel big auto column width

javaapache-poiout-of-memorybig-o

提问by Ram Sharan Mittal

I am try to create a big excel 2010 with 30 columns and 1 million records with Apache poi latest. I am creating as describe in this link http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java. but I want column width to be same as column header text size. but when I am doing this after creating excel with following code

我正在尝试使用最新的 Apache poi 创建一个包含 30 列和 100 万条记录的大型 excel 2010。我正在按照此链接http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java 中的描述创建 。但我希望列宽与列标题文本大小相同。但是当我在使用以下代码创建 excel 后执行此操作时

for (int x = 0; x < sheet.getRow(0).getPhysicalNumberOfCells(); x++) {
            sheet.setColumnWidth(x, 20*256);
        }

it is taking a huge time and even with 5gb heap size I am getting out of memory.

它花费了大量时间,即使堆大小为 5GB,我的内存也不足。

thanks

谢谢

ram

内存

采纳答案by Sankumarsingh

First Select the first row or header because only Header can give you the max number of cells in a row.

首先选择第一行或标题,因为只有标题才能为您提供一行中的最大单元格数。

HSSFRow row = wb.getSheetAt(0).getRow(0);

Then use autoSizeColumnon each column of that row

然后autoSizeColumn在该行的每一列上使用

for(int colNum = 0; colNum<row.getLastCellNum();colNum++)   
    wb.getSheetAt(0).autoSizeColumn(colNum);

This will set the column width same as that of its Header width.

这将设置列宽度与其标题宽度相同。

回答by Adi Kish

I would also suggest you look at using sxssf. It uses an xml format to load it into Excel. This is much faster and a better way to create large reports or grids. The autosizing function in xssf takes too long by default.

我还建议您考虑使用 sxssf。它使用 xml 格式将其加载到 Excel 中。这是创建大型报表或网格的更快和更好的方法。默认情况下,xssf 中的自动调整大小功能花费的时间太长。

回答by Nilesh

sheet.autoSizeColumn(columnNumber) works. this will resize the column to the largest cell length.

sheet.autoSizeColumn(columnNumber) 有效。这会将列的大小调整为最大的单元格长度。