首页 文章

autoSizeColumns的问题 - 某些单元格仍然太小

提问于
浏览
0

我在Excel工作表之间写数据 . 有些纸张是从原始的Excel中取出的,有些纸张是新的 . 我在将列拟合到正确的大小时遇到问题,因此所有数据都是可见的 .

我的代码

public void autoSizeColumns(Workbook workbook) {
    int numberOfSheets = workbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (sheet.getPhysicalNumberOfRows() > 0) {

            //Find a row that has entries for all columns 
            // because resizing on empty cell doesn't work correctly
            Iterator<Row> rowIterator = sheet.rowIterator();
            int maxCells = 0;
            Row rowWithMaxCells = null;
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if(row.getPhysicalNumberOfCells() > maxCells || rowWithMaxCells == null ){
                    maxCells = row.getPhysicalNumberOfCells();
                    rowWithMaxCells = row;
                }
            }

            // calculate column width
            Iterator<Cell> cellIterator = rowWithMaxCells.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                int columnIndex = cell.getColumnIndex();
                sheet.autoSizeColumn(columnIndex);
            }
            }
        }
    }

我在将工作簿写入输出流之前调用该函数

我知道在SO上有类似的问题,但没有找到对我有用的答案 .

编辑:因为对类似问题的一些回答提到了使用的字体的问题:大多数表使用Arial

编辑:我注意到这部分代码

//Find a row that has entries for all columns 
        // because resizing on empty cell doesn't work correctly
        Iterator<Row> rowIterator = sheet.rowIterator();
        int maxCells = 0;
        Row rowWithMaxCells = null;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if(row.getPhysicalNumberOfCells() > maxCells || rowWithMaxCells == null ){
                maxCells = row.getPhysicalNumberOfCells();
                rowWithMaxCells = row;
            }
        }

总是选择表的 Headers ,因为它是第一行,它填充了所有列 . 有些列仍然比 Headers 行长,所以这似乎不是问题

1 回答

  • 0

    当我使用公式时,它发生在我身上 . 尝试使用

    HSSFFormulaEvaluator.evaluateAllFormulaCells(yourWorkbook);
    

相关问题