可以使用Python中的docx库进行操作。 ```python from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.oxml.ns import nsdecls from docx.oxml import etree # 创建一个新的Word文档 doc = Document() # 设置页眉页脚的样式 section = doc.sections[0] header = section.header footer = section.footer header.paragraphs[0].text = "页眉内容" footer.paragraphs[0].text = "页脚内容" # 添加标题 title = doc.add_paragraph("文档标题") title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 添加目录 doc.add_paragraph().add_run("目录").bold = True toc = doc.add_paragraph() toc_run = toc.add_run() toc_run.text = "" toc_run.add_field("TOC \\o \"1-3\" \\h \\z \\u", "") # 添加正文内容 doc.add_page_break() # 添加分页符 doc.add_heading("章节标题 1", level=1) doc.add_paragraph("正文内容 1") doc.add_page_break() doc.add_heading("章节标题 2", level=1) doc.add_paragraph("正文内容 2") # 保存文档 doc.save("generated_doc.docx") ```
pojie202 发表于 2023-9-28 23:08 提示啥呢 安装python-docx库。 pip install python-docx AttributeError: 'Run' object has no attribute 'add_field'