【问题标题】:question about python-docx, settings are applied to some cells, but not all cells关于 python-docx 的问题,设置应用于某些单元格,但不是所有单元格
【发布时间】:2022-01-02 13:45:36
【问题描述】:

我不知道为什么这段代码会更改某些单元格的设置,但不会更改某些单元格的设置。特别是,某些单元格上没有应用“돋움”字体

可能是什么原因?

这是更改单元格设置的代码部分(?)。 i代表行,3代表列

cell(0, 3) 和 cell(4, 3) 不变,但 cell(1~3, 3) 变化。

for i, j in enumerate([0,1,1,2,5]):
    ~~~
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    des.tables[table_number].cell(i, 3).paragraphs[0].runs[0].font.size = Pt(8)
    des.tables[table_number].cell(i, 3).paragraphs[0].runs[0].font.name = "돋움"
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.space_before = 0
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.line_spacing = 0.75
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.space_after = 0

【问题讨论】:

    标签: python word python-docx word-table


    【解决方案1】:

    一个单元格可以有多个段落,一个段落可以有多个运行。如果您希望它们都具有这些属性设置,则需要将设置应用于所有段落和所有运行:

    def set_paragraph_attributes(paragraph):
        paragraph_format = paragraph.paragraph_format
        paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
        paragraph_format.space_before = 0
        paragraph_format.line_spacing = 0.75
        paragraph_format.space_after = 0
    
    def set_run_attributes(run):
        font = run.font
        font.size = Pt(8)
        font.name = "돋움"
    
    for i, j in enumerate([0,1,1,2,5]):
        cell = des.tables[table_number].cell(i, 3)
        for paragraph in cell.paragraphs:
            set_paragraph_attributes(paragraph)
            for run in paragraph.runs:
                set_run_attributes(run)
    

    您的enumerate() 呼叫看起来不太正确。您使用的是i,但不是jij 将采用以下值:

    [(0, 0), (1, 1), (2, 1), (3, 2), (4, 5)]
    

    但您用于选择单元格的是:

    [(0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]
    

    基本上就是第四列前五行的所有单元格。

    您的意思是 des.tables[table_number].cell(i, j)? If not, why do you compute j` 并且不使用它吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多