Apache POI, calling autosize after auto filter

只愿长相守 提交于 2019-12-05 08:33:20

I'm the one that wrote the original thread you referred. At the end I achieved a solution, not the one I was looking for but at least it is working for me. I just forgot to update my question with the solution I found.

I created a new method that iterates over the columns of the sheet I want to autosize and do two things. First I autosize the column so we will have the width we don't want because it doesn't take into account the arrow's width. Then I set the width of the column manually including the width of the arrow. I had to play a little bit to find the width of the arrow (which for me is 1300). I guess this width can work for you but you're free to set it as you want.

As you can imagine, you should first get and autofilter the data. After that you call a method to autosize the columns, like the one I used:

private static final int WIDTH_ARROW_BUTTON = 1300;

private void autosizeColumnsFromSheet(final Sheet excelSheet, final int fromColumn, final int toColumn) {
        for (int i = fromColumn; i <= toColumn; i++) {
            excelSheet.autoSizeColumn(new Short(String.valueOf(i)));
            try {
                excelSheet.setColumnWidth(i, excelSheet.getColumnWidth(i) + WIDTH_ARROW_BUTTON);
            } catch (final Exception e) {
                // don't do anything - just let autosize handle it
            }
        }
    }

As per my understanding, your selected text of the filter dropdown is hiding because of arrow. If I am right, why not you just give some padding after autosize! I mean first autosize the col by:

testSheet.autoSizeColumn(ColIndex);

then calculate the column width and add some desired padding in the width

testSheet.setColumnWidth(ColIndex ,testSheet.getColumnWidth(ColIndex)+PaddingWidth);

this will give sufficient padding for arrow icon right to the dropdown and the text will comlpletely appear.

            int WIDTH_ARROW_BUTTON = 2 * 255;
        for (int i = 0; i < row.getLastCellNum(); i++) {
            sheet.autoSizeColumn(i);
            // For filter additional arrow width
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) + WIDTH_ARROW_BUTTON);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!