Python docx row.cells多次返回“合并”单元格

问题描述 投票:2回答:1

我正在使用python docx库,需要从文档中的表中读取数据。

虽然我可以使用以下代码读取数据,

document = Document(path_to_your_docx)
tables = document.tables
for table in tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                print(paragraph.text)

我得到多个重复值,其中单元格中的内容跨越其合并的单元格,对于合并到其中的每个单元格一次。我不能简单地删除重复值,因为可能有多个具有相同值的未合并单元格。我该怎么办呢?

作为参考,我被指示从this github issue这里提问。

谢谢。

python python-docx
1个回答
2
投票

如果您想要将每个合并的单元格恰好一次,则可以添加以下代码:

def iter_unique_cells(row):
    """Generate cells in *row* skipping empty grid cells."""
    prior_tc = None
    for cell in row.cells:
        this_tc = cell._tc
        if this_tc is prior_tc:
            continue
        prior_tc = this_tc
        yield cell


document = Document(path_to_your_docx)
for table in document.tables:
    for row in table.rows:
        for cell in iter_unique_cells(row):
            for paragraph in cell.paragraphs:
                print(paragraph.text)

对于它占据的每个“网格”单元出现一次的表中相同单元格的行为是预期的行为。如果行单元格在行之间不均匀,则会在其他地方引起问题。如果3 x 3表中的每一行不一定包含3个单元格。例如,如果该行中存在合并的单元格,则访问三列表中的row.cell [2]会引发异常。

同时,有一个备用访问器可能是有用的,也许Row.iter_unique_cells()不保证跨行的一致性。这可能是值得请求的功能。

© www.soinside.com 2019 - 2024. All rights reserved.