【问题标题】:Column and row dimensions in OpenPyXL are always NoneOpenPyXL 中的列和行维度始终为 None
【发布时间】:2015-09-30 00:00:43
【问题描述】:

为什么 openpyxl 将每一行和每一列的维度都读取为无?无论表格是通过 openpyxl 还是在 Microsoft Excel 中创建的,情况都是如此。

import openpyxl
wb = openpyxl.load_workbook(r'C:\data\MyTable.xlsx')
ws = wb.active
print ws.row_dimensions[1].height
print ws.column_dimensions['A'].width

打印无和无。这些不是隐藏的列/行。在 Excel 中查看时,它们显然具有尺寸。

我知道用迭代器加载工作簿会阻止创建维度字典,但这会导致关键错误,我在这里没有使用迭代器。

是否有其他方法来确定单元格/行/列的宽度/高度?

===============解决方案=================

感谢 Charlie,我意识到以下是获取所有行高列表的最佳方法:

import openpyxl
wb = openpyxl.load_workbook(r'C:\Data\Test.xlsx')
ws = wb.active
rowHeights = [ws.row_dimensions[i+1].height for i in range(ws.max_row)]
rowHeights = [15 if rh is None else rh for rh in rowHeights]

【问题讨论】:

    标签: python python-2.7 openpyxl


    【解决方案1】:

    RowDimensionColumnDimension 对象仅在要覆盖默认值时才存在。所以ws.row_dimensions[1].height 将永远是None,直到它被赋值。

    默认值为:{'defaultRowHeight': '15', 'baseColWidth': '10'}

    【讨论】:

    • 谢谢你,查理。您是否知道 openpyxl 文档中的某处已明确说明了这一点,还是仅通过解释源代码本身?
    • 你想明确表达什么?维度查找故意返回一个对象而不是引发KeyError
    • 如果文档明确说明您在回答中所说的内容,这将对我有所帮助:存在默认值,但除非尺寸已更改,否则返回 None 而不是默认值。
    【解决方案2】:

    openpyxl: 3.0.4

    源代码:from openpyxl.worksheet.dimensions import SheetFormatProperties

    它显示{'defaultRowHeight': 15, 'baseColWidth': 8}

    # dimensions.py
    
    class SheetFormatProperties(Serialisable):
    
        ...
    
        def __init__(self,
                     baseColWidth=8,  # <-----------------
                     defaultColWidth=None,
                     defaultRowHeight=15,  # <------------
                     customHeight=None,
                     zeroHeight=None,
                     thickTop=None,
                     thickBottom=None,
                     outlineLevelRow=None,
                     outlineLevelCol=None,
                    ):
            self.baseColWidth = baseColWidth
            self.defaultColWidth = defaultColWidth
            self.defaultRowHeight = defaultRowHeight
            self.customHeight = customHeight
            self.zeroHeight = zeroHeight
            ...
    

    一个例子

    from openpyxl import load_workbook
    from openpyxl.worksheet.dimensions import SheetFormatProperties
    from openpyxl.worksheet.worksheet import Worksheet
    
    wb = load_workbook('xxx.xlsx')
    for sheet in [wb[sheet_name] for sheet_name in wb.sheetnames]:
        sheet: Worksheet
        sheet_prop: SheetFormatProperties = sheet.sheet_format
        default_width = sheet_prop.baseColWidth
        default_height = sheet_prop.defaultRowHeight
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多