1
python生成Word文档
pydoc是python自带的一个文档生成工具,pydoc可以直接生成html、md的说明文档,也可以启动本地服务,在web上查看文档。
2
使用python生成图表、文字、段落的功能
class Export():
def __init__(self):
self.doc = Document()
def add_center_picture(self, image_path_or_stream, width=None, height=None):
# run = self.doc.add_paragraph().add_run()
tab = self.doc.add_table(rows=1, cols=3) # 添加一个1行3列的空表
cell = tab.cell(0, 1) # 获取某单元格对象(从0开始索引)
ph =cell.paragraphs[0]
run = ph.add_run()
# run.add_break()
if not width:
run.add_picture(image_path_or_stream, width=Inches(5.2))
else:
run.add_picture(image_path_or_stream, width=width, height=height)
def align_center(self):
last_paragraph = self.doc.paragraphs[-1]
last_paragraph.alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.CENTER
def exportReport(self):
# pip install python-docx
self.doc.add_heading('self.doc Title', 0)
p = self.doc.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
self.doc.add_heading('Heading, level 1', level=1)
self.doc.add_paragraph('Intense quote', style='Intense Quote')
self.doc.add_paragraph(
'first item in unordered list', style='List Bullet'
)
self.doc.add_paragraph(
'first item in ordered list', style='List Number'
)
# self.add_center_picture('output.png')
self.doc.add_picture('output.png', width=Inches(5.2))
self.align_center()
self.doc.add_paragraph(
'Second item in ordered list', style='List Number'
)
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
table = self.doc.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
self.doc.add_page_break()
self.doc.save('reports.docx')
效果如下: