2021/03/04
python docx 模块常用代码
from docx import Document
from docx.shared import RGBColor
document = Document()
paragraph = document.add_paragraph('hello,world')
document.add_heading('添加标题段落', level=0) # level:标题等级
document.add_heading('添加标题1', level=1)
document.add_page_break() # 添加硬分页符
# 添加表格
example_table = document.add_table(rows = 3, cols = 2)
cell = example_table.cell(0, 1)
cell.text = '这是第一行第二列(0,1)单元格的内容'
row = example_table.rows[1]
row.cells[0].text = '这是第二行第一个单元格(1,0)的内容'
# 可迭代获取表格内容
for row in example_table.rows: # 每行
for cell in row.cells: # 每个单元格
print(cell.text)
# 计数表中的行数或列数
row_count = len(example_table.rows)
col_count = len(example_table.columns)
# 添加行
row = example_table.add_row()
document.add_paragraph('这是一个可变长度表的例子', style = 'List Bullet')
items = ( (1, '字符串', '内容'), (2, '2222', '22222222'), (3, '3333', '33333333'))
items_table = document.add_table(1, 3)
heading_cells = items_table.rows[0].cells # 添加表头
heading_cells[0].text = '列1'
heading_cells[1].text = '列2'
heading_cells[2].text = '列3'
for item in items:
cells = items_table.add_row().cells
cells[0].text = str(item[0])
cells[1].text = item[1]
cells[2].text = item[2]
paragraph = document.add_paragraph('这是一个')
run1 = paragraph.add_run('粗体').bold = True
run2 = paragraph.add_run('斜体').italic = True
run3 = paragraph.add_run('有颜色').font.color.rgb = RGBColor(250, 0, 0)
paragraph.add_run('的例子')
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 这是一个居中的格式 LEFT RIGHT
document.save('example.docx')
网友评论