我正在尝试使用 xlsx4j 将 JTable 导出到 XLSX 文件,但无法设置列宽。我已成功设置所有列的默认宽度,但我想设置列的宽度以自动适应数据长度:
public void exportToXLS() throws Exception
{
//Create the spreadsheet
SpreadsheetMLPackage pkg = SpreadsheetMLPackage.createPackage();
WorksheetPart sheet = pkg.createWorksheetPart(new PartName("/xl/worksheets/sheet1.xml"), "Sheet1", 1);
//Set default format for rows and columns
CTSheetFormatPr format = Context.getsmlObjectFactory().createCTSheetFormatPr();
format.setDefaultColWidth(20.0);
format.setDefaultRowHeight(16.8);
format.setCustomHeight(Boolean.TRUE);
sheet.getJaxbElement().setSheetFormatPr(format);
//Get a few JTable properties
int iSelectedTab = tabPane.getSelectedIndex();
int[] rowsSelected = table[iSelectedTab].getSelectedRows();
int iColumns = table[0].getColumnCount();
int iCurrentRow;
//Retrieve SheetData from sheet object
SheetData sheetData = sheet.getJaxbElement().getSheetData();
Row row;
Cell cell;
//Copy data from JTable to spreadsheet
for(int iRow=0; iRow < rowsSelected.length; iRow++)
{
iCurrentRow = rowsSelected[iRow];
row = Context.getsmlObjectFactory().createRow();
List<Cell>rowl = row.getC();
for(int iCol = 0; iCol < iColumns; iCol++)
{
cell = Context.getsmlObjectFactory().createCell();
CTRst ctrst = new CTRst();
ctrst.setT(table[iSelectedTab].getValueAt(iCurrentRow, iCol).toString());
cell.setT(STCellType.INLINE_STR);
cell.setIs(ctrst);
rowl.add(cell);
}
sheetData.getRow().add(row);
}
//Set the columns widths
List<Cols> lstCols = sheet.getJaxbElement().getCols();
System.out.println("lstCols.size() is " + lstCols.size());
for(int i = 0; i< lstCols.size(); i++)
{
List<Col> lstCol = lstCols.get(i).getCol();
System.out.println("lstCol.size() is " + lstCol.size());
for(int j=0; j<lstCol.size(); j++)
{
lstCol.get(j).setBestFit(Boolean.TRUE);
lstCol.get(j).setWidth(30.0);
System.out.println("Column " + i + " : " + j);
}
}
//Save the spreadsheet to file
pkg.save(new File("Export.xlsx"));
}
上面的代码在控制台中显示:lstCols.size() 为 0,所以看起来在向 SheetData 添加行和单元格后,没有列定义。
另一方面,如果我以这种方式手动创建列:
Cols cols = Context.smlObjectFactory.createCols();
Col col = Context.smlObjectFactory.createCol();
col.setBestFit(Boolean.TRUE);
cols.getCol().add(col);
sheet.getJaxbElement().getCols().add(cols);
我在 XLSX 文件中遇到灾难性错误。