python将文本、dataframe输出到word文档中
# 加载基本库
from docx import Document
import pandas as pd
temp = {'name': 'link', 'dir':'south', 'beizhu':'test'}
df = pd.Dataframe.from_dict([temp])
document = Document()
heading = document.add_heading(u'title',0) # 加入初级标题
document.add_heading(u'一级标题1', 1)
obj_day = '2021-05-21'
speed1 = 30
speed2 = 35
content = "{}早晚高峰平均速度分别为{}km/h、{}km/h".format(obj_day, speed1, speed2)
paragraph = document.add_paragraph(content)
tabel_header = [['name', 'dir', '备注']]
def df_toword(dataframe, header):
lst = dataframe.values.tolist()
lst1 = table_header + lst
cols_num = dataframe.columns.size
rows_num = len(dataframe) + 1
document.add_heading(u'一级标题2', 1)
tabel1 = document.add_tabel(rows=rows_num, cols=cols_num)
for row in range(rows_num):
cells = table1.rows[row].cells
for col in range(cols_num):
cells.[col].text = str(lsts[row][col])
df_toword(df, table_header)
document.save(u'测试.docx')