[英]How to add table heading drop-down with Apache Poi
I'm generating Excel tables with Apache POI, but my generated tables lack the drop-down menu on each header that appear when I "format as table" in Excel itself. 我正在使用Apache POI生成Excel表格,但是我生成的表格缺少每个标题上的下拉菜单,当我在Excel中“格式化为表格”时出现。
I'd like to generate this: 我想生成这个:
But instead I get this: 但相反,我得到了这个:
I'm following this blog post , and my code looks like this: 我正在关注这篇博文 ,我的代码如下:
XSSFTable table = sheet.createTable();
table.setDisplayName("Data");
CTTable ctTable = table.getCTTable();
ctTable.setDisplayName("Data");
ctTable.setId(1L);
ctTable.setName("DATA");
CTTableStyleInfo table_style = ctTable.addNewTableStyleInfo();
table_style.setName("TableStyleMedium9");
table_style.setShowColumnStripes(false);
table_style.setShowRowStripes(true);
Each column is then created like this: 然后按如下方式创建每列:
CTTableColumn column = ctColumns.addNewTableColumn();
column.setName(headers.get(i));
column.setId(i + 1);
What am I missing? 我错过了什么?
Thanks to Alan Hay for the clue - the solution is to add an auto-filter, but this needs to be added as a CTAutoFilter
for each individual column of the CTTable
. 感谢Alan Hay提供的线索 - 解决方案是添加一个自动过滤器,但需要将其添加为CTAutoFilter
的每个列的CTTable
。 The working solution looks like this: 工作解决方案如下所示:
CTTableColumns ctColumns = ctTable.addNewTableColumns();
CTAutoFilter autofilter = ctTable.addNewAutoFilter();
ctColumns.setCount(table_headers.size());
for(int i = 0; i < table_headers.size(); i++) {
CTTableColumn column = ctColumns.addNewTableColumn();
column.setName(table_headers.get(i));
column.setId(i + 1);
CTFilterColumn filter = autofilter.addNewFilterColumn();
filter.setColId(i + 1);
filter.setShowButton(true);
}
When auto-sizing columns, it's also necessary to add extra width for the drop down menu: 在自动调整列大小时,还需要为下拉菜单添加额外的宽度:
for(int i = 0; i < table_headers.size(); i++) {
sheet.autoSizeColumn(i);
// Include width of drop down button
sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 1000);
}
It is not exactly clear from the example you quoted whether applying the Table styling should create the filter dropdowns for you or not. 从您引用的示例中可以清楚地看出,应用表样式是否应该为您创建过滤器下拉列表。
However you can explicitly call setAutoFilter() as below to have the filter dropdowns set. 但是,您可以显式调用setAutoFilter(),如下所示,以设置过滤器下拉列表。
eg 例如
CellReference start = table.getStartCellReference();
CellReference end= table.getEndCellReference();
sheet.setAutoFilter(new CellRangeAddress(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.