我在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;
}
}
始终选择表格的标题,因为它是第一行,其中填充了所有列。 有些列仍然比标题行长,所以这似乎不是问题
答案 0 :(得分:0)
当我使用公式时,它发生在我身上。尝试使用
HSSFFormulaEvaluator.evaluateAllFormulaCells(yourWorkbook);