xlsx4j – 如何在电子表格中设置列宽?

我试图使用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添加行和单元格后,看起来没有任何列定义。

另一方面,如果我以这种方式手动创build列:

 Cols cols = Context.smlObjectFactory.createCols(); Col col = Context.smlObjectFactory.createCol(); col.setBestFit(Boolean.TRUE); cols.getCol().add(col); sheet.getJaxbElement().getCols().add(cols); 

我在XLSX文件中遇到了灾难性的错误。

从ECMA-376规范(我看了3ed,第18.3.1.17节,第1774页):

这个例子显示第4列(D)具有“最适合”,也是自定义的宽度。 此外,列5(E)被列为具有在列级应用的自定义宽度和样式(与单元级相对)。

 <cols> <col min="4" max="4" width="12" bestFit="1" customWidth="1"/> <col min="5" max="5" width="9.140625" style="3"/> </cols> 

所以,看起来您只需要通过指定列号(通过min / max属性)来完成col对象定义。

 <col min="2" max="2" bestFit="1"/> 

给出一个以零宽度开始的列,所以你应该指定@width。

@bestFit似乎没有做你所期望的(你想要更类似于autoFit的东西?)。

请参阅custom-column-width-in-excel-open-xml和计算-column-width-in-excel-open-xml以获取更多信息。