Python docx row.cells return 一个 "merged" 单元格多次

Python docx row.cells return a "merged" cell multiple times

我正在使用 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 的问题。

谢谢。

如果你想得到每个合并的单元格恰好一次,你可以添加以下代码:

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)

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

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