繁体   English   中英

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

[英]How to get the default column width of an Excel sheet with Apache-POI?

要求

我需要从XSSFSheet获取默认列宽

方法

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

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

问题

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

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

原因

我用 Excel 本身检查了到底发生了什么:

  1. 我更改了 Excel 中的默认列宽并保存了工作表。
  2. 然后我在相应的 xml 文件中查找 Excel 所做的更改:
    • 属性defaultColWidth更改。
    • 属性baseColWidth保持不变。

因此,“真实”和正确的默认列宽存储在defaultColWidth属性中。 因此,该方法应该返回该属性,而是返回基本列宽(如您在上面的实现中所见)。

解决方案

在我看来,上面的方法应该返回pr.getDefaultColWidth()而不是pr.getBaseColWidth()

我认为要么该方法被错误地实现,要么我太愚蠢而无法找到返回正确值的正确方法。

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

问候温克勒

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。

即使在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"/>

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

暂无
暂无

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

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