2015-02-09 69 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

相關問題