• 周四. 4月 25th, 2024

Python 中操作 Microsoft Word 文档

城主

12月 22, 2022 ,

在 Python 中操作 Microsoft Word 文档,可以使用 python-docx 库。它可以帮助你读取、修改和写入 Word 文档。

下面是使用 python-docx 库读取 Word 文档的一个简单示例:





from docx import Document

# Open the Word document
document = Document('input.docx')

# Print the document properties
print(f'Author: {document.core_properties.author}')
print(f'Title: {document.core_properties.title}')

# Iterate through all the paragraphs
for paragraph in document.paragraphs:
    # Print the paragraph text
    print(paragraph.text)

# Iterate through all the tables
for table in document.tables:
    # Iterate through all the rows
    for row in table.rows:
        # Iterate through all the cells
        for cell in row.cells:
            # Print the cell text
            print(cell.text)

上面的代码会打开名为 input.docx 的 Word 文档,然后打印出文档的属性,并遍历所有段落和表格,打印出每一个单元格的文本。

如果你想要修改 Word 文档,可以使用 python-docx 库修改文档中的数据。下面是一个简单的例子:





from docx import Document

# Open the Word document
document = Document('input.docx')

# Modify the document properties
document.core_properties.author = "John Doe"
document.core_properties.title = "Modified Document"

# Modify the paragraph text
document.paragraphs[0].text = "This is a modified paragraph."

# Modify the cell text
table = document.tables[0]
table.rows[0].cells[0].text = "Modified cell text."

# Save the document to a new file
document.save('output.docx')

上面Python 中操作 Microsoft Word 文档的代码会打开名为 input.docx 的 Word 文档,修改其属性和段落文本,并将修改后的文档保存到一个新的文件 output.docx 中。

阅读  Python 网络编程的详细用法