[英]xlsx4j - How to set column width in spreadsheet?
我正在嘗試使用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文件中收到災難性錯誤。
從ECMA-376規范(我看過3ed,第18.3.1.17節,p1774):
此示例顯示第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"/>
給出以零寬度開頭的col,因此您應指定@width。
@bestFit似乎並沒有達到您的期望(您想要更多類似autoFit的東西?)。
有關更多信息,請參見custom-column-widths-in-excel-open-xml和Calculation-column-widths-in-excel-open-xml 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.