我正在使用Apache POI API
生成excel spreadsheet
来输出一些数据。
我面临的问题是,当创建和打开电子表格时,列没有展开,因此一些长文本,如日期格式的文本,不会第一眼就显示出来。
我可以在excel中双击列边框来展开或拖动边框来调整列宽,但可能有20+列,我不可能每次打开电子表格时都手动执行此操作:(
我发现(尽管可能是错误的方法) groupRow()
和setColumnGroupCollapsed()
也许能够做到这一点,但运气不佳。也许我用错了方法。
示例代码片段
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
//create sheet
Sheet sheet = wb.createSheet("masatoSheet");
//not really working yet.... :(
//set group for expand/collapse
//sheet.groupRow(0, 10); //just random fromRow toRow argument values...
//sheet.setColumnGroupCollapsed(0, true);
//create row
Row row = sheet.createRow((short)0);
//put a cell in the row and store long text data
row.createCell(0).setCellValue("Loooooooong text not to show up first");
当创建此电子表格时,"Looooooong text to not show up first“字符串在单元格中,但由于该列未展开,因此仅显示"Loooooooo”。
如何对其进行配置,使其在打开电子表格时,列已经展开?
发布于 2011-01-06 14:05:29
在将所有数据添加到工作表后,可以在工作表上调用autoSizeColumn(int column)
来自动调整列的大小
这里有一个API的链接。
有关更多参考Problem in fitting the excel cell size to the size of the content when using apache poi,请参阅此帖子
发布于 2012-03-13 15:06:19
提示:要使自动调整大小起作用,应在将数据填充到excel后调用。
在填充数据之前调用该方法将不起作用。
发布于 2016-02-11 03:56:34
如果要自动调整工作簿中所有列的大小,这里有一个可能有用的方法:
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) {
Row row = sheet.getRow(sheet.getFirstRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int columnIndex = cell.getColumnIndex();
sheet.autoSizeColumn(columnIndex);
}
}
}
}
https://stackoverflow.com/questions/4611018
复制相似问题