簡體   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