2015-02-09 76 views
4

我使用Apache POI生成Excel表格,但是生成的表格在Excel自身“格式化为表格”时缺少每个标题上的下拉菜单。如何使用Apache Poi添加表格标题下拉菜单

我想生成此:

Table with menu button

而是我得到这个:

Table without menu button

我下面this blog post,我的代码如下所示:

 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); 

然后每列都是这样创建的:

  CTTableColumn column = ctColumns.addNewTableColumn(); 
      column.setName(headers.get(i)); 
      column.setId(i + 1); 

我在想什么?

+0

你检查http://stackoverflow.com/问题/ 27630507 /这是一个最大数量的项目,而生成下拉列表中的Excel使用apach – emin 2015-02-09 22:18:54

+0

我看到在搜索,但我不知道的排序菜单在与DataValidation相关的表上 - 它们是否被链接? – 2015-02-09 22:47:10

+0

选中此:http://tiku.io/questions/421420/excel-drop-down-list-using-apache-poi – emin 2015-02-09 23:09:17

回答

4

由于艾伦干草用于线索 - 该解决方案是增加自动过滤器,但是这需要添加作为CTAutoFilterCTTable的每个单独的列中。工作解决方案是这样的:

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); 
    } 

当自动调整大小列,这还需要添加额外的宽度下拉菜单:

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); 
    } 
1

从引用的示例中可以看出,是否应用表格样式应该为您创建滤镜下拉列表。

但是,您可以像下面那样显式调用setAutoFilter()来设置过滤器下拉列表。

例如

CellReference start = table.getStartCellReference(); 
CellReference end= table.getEndCellReference(); 
sheet.setAutoFilter(new CellRangeAddress(...); 
+0

这真的很接近工作 - 它会生成正确的菜单,但Excel会将输出文件报告为已损坏:“已删除的功能:来自/xl/tables/table1.xml部分(表格)的表格” – 2015-02-10 11:42:08

+0

看起来像我剩下的问题在描述由这个未解决的问题:http://stackoverflow.com/questions/25570731/resultset-to-excel-xlsx-table-using-apache-poi – 2015-02-10 11:49:26