How to add table dropdown with Apache Poi

I create Excel tables with Apache POIs, but my generated tables do not have a drop-down menu for each header that appears when I "format as a table" in Excel itself.

I would like to generate this:

Table with menu button

But instead, I get the following:

Table without menu button

I am following this blog post and my code is as follows:

        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 created as follows:

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

What am I missing?

+4
source share
2 answers

- , , CTAutoFilter CTTable. :

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

, , .

setAutoFilter(), , .

.

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

All Articles