Skip to main content
 首页 » 编程设计

Python docx row.cells 多次返回 "merged"单元格

2024年09月07日6EasonJim

我正在使用 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) 

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

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