如何使用Apache-POI获取Excel工作表的默认列宽?

时间:2015-11-17 13:36:00

标签: java excel apache-poi

要求

我需要从XSSFSheet获取默认列宽

方法

XSSFSheet有一个名为getDefaultColumnWidth()的方法:

public int getDefaultColumnWidth() {
    CTSheetFormatPr pr = worksheet.getSheetFormatPr();
    return pr == null ? 8 : (int)pr.getBaseColWidth();
}

问题

即使我在Excel中更改默认列宽,该方法每次返回相同的值。

显然这个方法应该返回默认的列宽,但我认为它实际上并没有返回正确的值。

原因

我用Excel检查了究竟发生了什么:

  1. 我更改了Excel中的默认列宽并保存了工作表。
  2. 然后我查找Excel在相应的xml文件中所做的更改:
    • 属性defaultColWidth已更改。
    • 属性baseColWidth保持不变。
  3. 所以'真实'并且正确的默认列宽存储在defaultColWidth属性中。因此,该方法应该返回该属性,而是返回基本列宽(正如您在上面的实现中所看到的那样)。

    解决方案

    根据我的拙见,上面的方法应该返回pr.getDefaultColWidth()而不是pr.getBaseColWidth()

    我认为该方法是错误实现的,或者我太愚蠢而无法找到返回正确值的正确方法。

    问题

    如何从带有POI Apache的Excel XSSFSheet获取正确的 默认列宽

    关心winklerrr

2 个答案:

答案 0 :(得分:1)

getDefaultColumnWidth

public int getDefaultColumnWidth()

Get the default column width for the sheet (if the columns do not define their own width) in characters.

Note, this value is different from getColumnWidth(int). The latter is always greater and includes 4 pixels of margin padding (two on each side), plus 1 pixel padding for the gridlines.

Specified by:
    getDefaultColumnWidth in interface Sheet
Returns:
    column width, default value is 8

上面明确指出,如果列没有定义自己的默认值,则默认值为8。可能是您使用了错误的API。

答案 1 :(得分:1)

这个问题即使在 apache poi-5.0.0 中也没有解决。

如果您尝试获取 defaultColWidth,它会返回不期望的 baseColWidth

因此,获取 defaultColWidth 的解决方法可能是访问 CTWorksheet 以获取值。

private double getDefaultColumnWidth(XSSFSheet sheet) {
    if (sheet.getCTWorksheet().isSetSheetFormatPr()) {
        CTSheetFormatPr pr = sheet.getCTWorksheet().getSheetFormatPr();
        if (pr.isSetDefaultColWidth())
            // returns the actual default column width if it has been set
            return pr.getDefaultColWidth();
    }
    // tries to return the baseColWidth and in its absence returns 8
    return sheet.getDefaultColumnWidth();
}

MSExcel 设置 defaultColWidth 和 apache poi-5.0.0 处理它的方式。

MSExcel 将默认列宽设置为 defaultColWidth

<sheetFormatPr defaultColWidth="2.5" defaultRowHeight="18.75"/>

XML 片段取自 apache poi-5.0.0 生成的文档。apache poi-5.0.0 将默认列宽设置为 baseColWidth

<sheetFormatPr baseColWidth="2.5" defaultRowHeight="18.75" customHeight="true"/>

我知道距离上次发布这个问题已经快六年了,但我想它可能对其他人有帮助。