OpenPyXL中的列和行维度始终为None

时间:2015-09-30 00:00:43

标签: python python-2.7 openpyxl

为什么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中查看时,它们显然具有尺寸。

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

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

=============== SOLUTION =================

感谢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]

2 个答案:

答案 0 :(得分:16)

仅当要覆盖默认值时,才存在

RowDimensionColumnDimension个对象。因此,ws.row_dimensions[1].height将始终为None,直到为其指定值。

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

答案 1 :(得分:0)

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