1、表格插入
方法一:直接创建表添加
from docx import Document
document = Document()
table = document.add_table(rows=5, cols=7)
table.cell(1,2).text='中国'
table.rows[2].cells[3].text='人民'
row_cells = table.add_row().cells
row_cells[1].text = '加油'
document.save('D:/demo.docx')
方法二:以dataframe形式添加
dataframe = pd.DataFrame({
"企业": [round(random.random(), 2) for _ in range(3)],
"数量": [round(random.random(), 2) for _ in range(3)],
"金额": [round(random.random(), 2) for _ in range(3)]
})
document = Document()
table = convert_df_to_table(document, dataframe, column_list=dataframe.columns.tolist())
table = set_table_singleBoard(table)
base_paragraphs = document.add_paragraph("下面插入表格:")
base_paragraphs._p.addnext(table._tbl)
2、将表格插入到文档指定段落后面
doc = docx.Document("模板docx路径")
dataframe = pd.DataFrame({
"企业": [round(random.random(), 2) for _ in range(3)],
"数量": [round(random.random(), 2) for _ in range(3)],
"金额": [round(random.random(), 2) for _ in range(3)]
})
doc1 = docx.Document()
table = convert_df_to_table(doc1, dataframe, column_list=dataframe.columns.tolist())
table = set_table_singleBoard(table)
base_paragraphs = doc.paragraphs[6]
base_paragraphs._p.addnext(table._tbl)
doc.save(r'.\test1.docx')