用Apache-POI隐藏所有额外的excel列 [英] Hide all extra excel columns with Apache-POI

查看:391
本文介绍了用Apache-POI隐藏所有额外的excel列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的目标:

我正在使用Apache POI生成一个xlsx文件。我想将所有未使用的列隐藏在我正在使用的列的右侧。在Excel中,这是一个比较简单的操作:我可以选择所有的无关列,并将它们全部隐藏在一个动作中。在Apache POI中,我唯一的选择是 sheet.setColumnHidden(index,true) 。如果我尝试为每个无关列执行此操作:

I am generating an xlsx file using Apache POI. I would like to hide all the unused columns to the right of the columns I am using. In Excel, this is a relatively simple operation: I can select all the extraneous columns and tell them all to hide in one action. In Apache POI, the only option I seem to have is sheet.setColumnHidden(index, true). If I try to do this for every extraneous column:

for (int i = myLastColumn+1; i < 16384; ++i) {
    sheet.setColumnHidden(i, true);
}

然后,库试图创建超过16,000列以隐藏它们,这是不切实际的:它变得越来越慢,永远不会完成。似乎没有一个 setColumnRangeHidden 或任何类似的东西。

then the library tries to create over 16 thousand columns in order to hide them, which is impractical: it gets slower and slower as it goes, and never finishes. There doesn't seem to be a setColumnRangeHidden or anything like that.

有没有办法隐藏几乎所有Apache POI中的列?

Is there a way to hide nearly all the columns in Apache POI?

推荐答案

最后,查看 XSSFSheet ColumnHelper 工作,我设法找到我缺少的功能。

Eventually, looking through how XSSFSheet and ColumnHelper work, I managed to find the bit of functionality I was missing.

当您尝试隐藏单列, ColumnHelper 为您请求的索引(如果不存在)创建一个新列,然后将其设置为隐藏。但是,列对象实际上是一个 CTCol ,其中 min max 字段设置为相同的索引。如果您使用不同的 min max 创建一个 CTCol 字段,您可以在一个操作中设置所有匹配列的状态。

When you try and hide a single column, the ColumnHelper makes a new column for the index you requested (if it didn't exist), and then sets it to be hidden. However, the column object is actually a CTCol with min and max fields set to the same index. If you create a CTCol object with different min and max fields, you can set the state of all matching columns in one action.

因此:

CTCol col = sheet.getCTWorksheet().getColsArray(0).addNewCol();
col.setMin(myLastColumn+2);
col.setMax(16384); // the last column (1-indexed)
col.setHidden(true);

这篇关于用Apache-POI隐藏所有额外的excel列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆