简体   繁体   English

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

[英]xlsx4j - How to set column width in spreadsheet?

I'm trying to export JTable to XLSX file using xlsx4j, but have trouble with setting the columns widths. 我正在尝试使用xlsx4j将JTable导出到XLSX文件,但是在设置列宽时遇到了麻烦。 I've succeeded in setting the default width for all the columns, but I would like to set the widths of columns to fit data lenght automatically: 我已经成功设置了所有列的默认宽度,但是我想设置列的宽度以自动适应数据长度:

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"));              
}

The above code shows in console: lstCols.size() is 0 so it looks like after adding rows and cells to the SheetData, there are no columns definitions. 上面的代码在控制台中显示:lstCols.size()为0,因此在将行和单元格添加到SheetData后看起来像没有列定义。

On the other hand if I create the columns manually this way: 另一方面,如果我以这种方式手动创建列:

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

I get the catastrophic error in XLSX file. 我在XLSX文件中收到灾难性错误。

From the ECMA-376 spec (I looked at 3ed, section 18.3.1.17, p1774): 从ECMA-376规范(我看过3ed,第18.3.1.17节,p1774):

This example shows that column 4 (D) has 'best fit' applied to it, which is also a custom width. 此示例显示第4列(D)对其应用了“最佳匹配”,这也是自定义宽度。 Also, column 5 (E) is listed as having a custom width and a style applied at the column level (as opposed to the cell level). 同样,列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>

so, it looks like you just need to complete your col object definition, by specifying the col number (via min/max attributes). 因此,看起来您只需要通过指定列号(通过min / max属性)来完成col对象定义。

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

gives a col which starts with zero width, so you should specify @width. 给出以零宽度开头的col,因此您应指定@width。

@bestFit doesn't seem to do what you'd expect (you want something more like autoFit?). @bestFit似乎并没有达到您的期望(您想要更多类似autoFit的东西?)。

See custom-column-widths-in-excel-open-xml and calculating-column-widths-in-excel-open-xml for more. 有关更多信息,请参见custom-column-widths-in-excel-open-xmlCalculation-column-widths-in-excel-open-xml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM