数据分析–word文档自动化2
表格操作
def table_merge_text(a, b, t):
"""
合并单元格 并写入文字
Args:
a: cell a
b: cell b
t: 文字
Returns:
cell obj
"""
m = a.merge(b)
m.text = t
for pgh in m.paragraphs:
pgh.alignment = WD_TABLE_ALIGNMENT.CENTER
return m
def table_write_rows(cells, txt_list):
"""
批量写入
Args:
cells: 单元格列表
txt_list: 文字列表
Returns:
"""
for c, t in zip(cells, txt_list):
c.text = str(t)
for pgh in c.paragraphs:
pgh.alignment = WD_TABLE_ALIGNMENT.CENTER
实战
doc_title = 'Title'
title_size = 1
table_title = 'table title'
table_content = ['a1', 'a2', 'a3', 'a4']
pngs_path = ['发.png', '2022.05.02.png']
doc_save = 'mytest.docx'
doc = new_document()
add_head(doc, doc_title, title_size)
tb = add_table(doc, 3, 4)
table_merge_text(tb.rows[0].cells[0], tb.rows[0].cells[-1], table_title)
table_write_rows(tb.rows[1].cells, table_content)
tw = int(tb.columns[0].width * 1.3)
tb.columns[0].width = tw
for cell in tb.column_cells(0):
cell.paragraphs[0].alignment = WD_TABLE_ALIGNMENT.LEFT
cell.width = tw
doc_add_picture(doc, pngs_path)
save_document(doc, doc_save)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1835596570f8824014a58fa009db1cda.png)