Productivity
文档处理(DOCX)
通过编程方式创建和操作 Microsoft Word 文档。当用户需要生成、编辑或转换 Word 文档时使用。
使用 Python 通过编程方式创建和操作 Microsoft Word 文档。
pip install python-docx
from docx import Document
# 创建文档
doc = Document()
# 添加内容
doc.add_heading('Document Title', 0)
doc.add_paragraph('Hello, World!')
# 保存
doc.save('document.docx')
# 主标题
doc.add_heading('Main Title', 0)
# 章节标题
doc.add_heading('Section 1', level=1)
doc.add_heading('Subsection 1.1', level=2)
# 段落
doc.add_paragraph('This is a paragraph.')
# 无序列表
doc.add_paragraph('Item 1', style='List Bullet')
doc.add_paragraph('Item 2', style='List Bullet')
# 有序列表
doc.add_paragraph('First item', style='List Number')
doc.add_paragraph('Second item', style='List Number')
# 创建表格
table = doc.add_table(rows=3, cols=3)
# 填充数据
for i, row in enumerate(table.rows):
for j, cell in enumerate(row.cells):
cell.text = f'Row {i}, Col {j}'
# 设置表格样式
table.style = 'Table Grid'
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
# 段落格式
paragraph = doc.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 文本格式
run = paragraph.add_run('Bold text')
run.bold = True
run = paragraph.add_run('Italic text')
run.italic = True
run = paragraph.add_run('Large text')
run.font.size = Pt(14)
doc.add_picture('image.png', width=Inches(4))
# 添加带对齐的图片
from docx.enum.text import WD_ALIGN_PARAGRAPH
paragraph = doc.add_paragraph()
run = paragraph.add_run()
run.add_picture('image.png', width=Inches(4))
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
section = doc.sections[0]
header = section.header
header_para = header.paragraphs[0]
header_para.text = 'Document Header'
footer = section.footer
footer_para = footer.paragraphs[0]
footer_para.text = 'Page number: '
from docx import Document
# 加载模板
doc = Document('template.docx')
# 替换占位符
for paragraph in doc.paragraphs:
if '{{NAME}}' in paragraph.text:
paragraph.text = paragraph.text.replace('{{NAME}}', 'John Doe')
if '{{DATE}}' in paragraph.text:
paragraph.text = paragraph.text.replace('{{DATE}}', '2024-01-15')
# 保存为新文件
doc.save('output.docx')
def create_report(data):
doc = Document()
doc.add_heading(f'Report: {data["title"]}', 0)
# 添加摘要
doc.add_heading('Summary', level=1)
doc.add_paragraph(data['summary'])
# 添加数据表格
doc.add_heading('Data', level=1)
table = doc.add_table(rows=len(data['items']) + 1, cols=2)
table.style = 'Table Grid'
# 表头行
table.rows[0].cells[0].text = 'Item'
table.rows[0].cells[1].text = 'Value'
# 数据行
for i, item in enumerate(data['items']):
table.rows[i + 1].cells[0].text = item['name']
table.rows[i + 1].cells[1].text = str(item['value'])
return doc