文章

Python操作文档

处理 Excel 电子表格

Python 的 openpyxl 模块让我们可以在 Python 程序中读取和修改 Excel 电子表格,由于微软从 Office 2007 开始使用了新的文件格式,这使得 Office Excel 和 LibreOffice Calc、OpenOffice Calc 是完全兼容的,这就意味着 openpyxl 模块也能处理来自这些软件生成的电子表格。

1
2
3
4
5
6
7
8
9
10
11
12
import datetime

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

ws['A1'] = 42
ws.append([1, 2, 3])
ws['A2'] = datetime.datetime.now()

wb.save("sample.xlsx")

处理 Word

利用 python-docx 模块,Python 可以创建和修改 Word 文档,当然这里的 Word 文档不仅仅是指通过微软的 Office 软件创建的扩展名为 docx 的文档,LibreOffice Writer 和 OpenOffice Writer 都是免费的字处理软件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
    'first item in ordered list', style='List Number'
)

document.add_picture('monty-truth.png', width=Inches(1.25))

records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

document.add_page_break()

document.save('demo.docx')
本文由作者按照 CC BY 4.0 进行授权