Python操作Word文档
Python可以使用python-docx库来操作Word文档。该库支持创建、修改和读取Word文件。以下是一个基本示例:
from docx import Document
from docx.shared import Pt
# 创建新文档
document = Document()
# 添加标题
document.add_heading('Python生成Word文档', 0)
# 添加段落
p = document.add_paragraph('这是一个使用python-docx库创建的Word文档。')
p.add_run('这段文字是加粗的。').bold = True
# 添加带格式的段落
document.add_paragraph('项目列表:', style='List Bullet')
document.add_paragraph('第一项', style='List Bullet')
document.add_paragraph('第二项', style='List Bullet')
# 添加表格
table = document.add_table(rows=2, cols=2)
cell = table.cell(0, 1)
cell.text = '第一行第二列'
# 设置字体
font = document.styles['Normal'].font
font.name = 'Arial'
font.size = Pt(12)
# 保存文档
document.save('demo.docx')
读取Word文档内容
python-docx也可以读取现有Word文档:
from docx import Document
document = Document('demo.docx')
for para in document.paragraphs:
print(para.text)
for table in document.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
高级Word操作
对于更复杂的Word操作,可以设置页眉页脚、添加图片等:
from docx import Document
from docx.shared import Inches
document = Document()
# 添加图片
document.add_picture('image.png', width=Inches(1.25))
# 添加分页符
document.add_page_break()
# 添加页眉
section = document.sections[0]
header = section.header
header_para = header.paragraphs[0]
header_para.text = "这是页眉内容"
document.save('advanced.docx')
Python操作PowerPoint
对于PowerPoint操作,可以使用`python-pp
573

被折叠的 条评论
为什么被折叠?



