【问题标题】:Create a table in the header of a *.docx file在 *.docx 文件的标题中创建一个表
【发布时间】:2020-09-10 19:23:59
【问题描述】:

我有以下工作代码 usinf python-docx:

import docx

inp = input('inp: ')


def write_docx_header():
    document = docx.Document('Test.docx')
    section = document.sections[0]
    header = section.header
    paragraph = header.paragraphs[0]
    paragraph.text = inp + "\t" + inp + "\t" + inp
    paragraph.style = document.styles["Header"]
    document.save('Test.docx')


write_docx_header()

现在我想要一个表头中包含三列而不是三个选项卡的表格,但我不知道从哪里开始以及如何做。

非常感谢

【问题讨论】:

    标签: python document docx


    【解决方案1】:
        records = (
            (3, 'Spam', 'Meow'),
            (7, 'Eggs', 'Meow'),
            (4, 'Spam, spam, eggs, and spam', 'Meow')
        )    
        table = document.add_table(rows=1, cols=3)
        table.style = 'TableGrid'  # apply styling
        header_cells = table.rows[0].cells
        header_cells[0].text = 'ID'
        header_cells[1].text = 'Name'
        header_cells[2].text = 'Cat'
        for id, desc, meow in records:
            row_cells = table.add_row().cells
            row_cells[0].text = str(id)
            row_cells[1].text = desc
            row_cells[2].text = meow
        document.save('Test.docx')
    

    References.

    Table styles.

    【讨论】:

    • 看起来不错,但它没有在我的 *.docx 文档中创建表格,我不知道为什么
    • @0x01_PH 你的意思是它不画边框?
    • 我真是个白痴。错误地删除了def末尾的document.save()。对不起对不起对不起。现在它工作正常。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多