# 为matplotlib中文无法显示设置字体
plt.rcParams['font.sans-serif'] = 'SimHei' # 黑体
# -*- coding: UTF-8 -*-
from docx import Document
from docx.shared import Pt, Cm
from docx.oxml.ns import qn
from docx.shared import Inches
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
# 为matplotlib中文无法显示设置字体
plt.rcParams['font.sans-serif'] = 'SimHei' # 黑体
# 设置文件根目录
BASE_DIR = Path(__file__).resolve().parent
# docx保存的文件夹path
TARGET_DIR = BASE_DIR / 'docxs'
IMAGE_DIR = BASE_DIR / 'imgs'
if not Path(IMAGE_DIR).exists():
# 新建一个文件夹存放保存的img
Path.mkdir(IMAGE_DIR)
if not Path(TARGET_DIR).exists():
# 新建一个文件夹存放保存的docx
Path.mkdir(TARGET_DIR)
# 打开文档
document = Document()
# 添加标题
document.add_heading('数据V1.0', 0)
#加入不同的标题
reader = pd.ExcelFile(BASE_DIR / '数据V1.0.xlsx')
# 获取所有sheet的name
sheet_names = reader.sheet_names[:3]
for sheet_name in range(len(sheet_names)):
df1 = reader.parse(sheet_name=sheet_names[sheet_name])
head = list(df1.loc[0, :])
body = df1.loc[1:, :].copy() # 获取主体信息
body.columns = head # 设置头部信息
# 添加二级标题
document.add_heading(sheet_names[sheet_name], 1)
rows, cols = body.shape
# 添加表格
table = document.add_table(rows=rows, cols=cols)
# 设置head信息
# hdr_cells = table.rows[0].cells
print(body)
# for col in range(0, len(head)):
# table.rows[0].cells[col].text = str(body.loc[1, head[col]])
try:
for row in range(0, rows):
hdr_cells = table.rows[row].cells
if row == 0:
for col in range(0, len(head)):
hdr_cells[col].text = str(head[col])
hdr_cells[col].paragraphs[0].runs[0].font.bold = True
else:
for col in range(0, len(head)):
if str(body.loc[row, head[col]]) == 'nan':
hdr_cells[col].text = ''
else:
hdr_cells[col].text = str(body.loc[row, head[col]])
if sheet_name == 0:
fig = plt.figure() # 创建空图
x = [i for i in body.loc[:, head[1]]]
y1 = [i for i in body.loc[:, head[2]]]
y2 = [i for i in body.loc[:, head[3]]]
y3 = [i for i in body.loc[:, head[4]]]
y4 = [i for i in body.loc[:, head[5]]]
print(x)
fig, ax = plt.subplots()
ax.plot(x, y1, label=head[2])
ax.plot(x, y2, label=head[3])
ax.plot(x, y3, label=head[4])
ax.plot(x, y4, label=head[5])
ax.legend()
plt.xlabel('机构')
plt.ylabel('数据')
plt.legend() # 显示图例
# 保存图片 展示show
plt.savefig(IMAGE_DIR / f'{sheet_names[0]}.png', dpi=200)
plt.show()
# 增加图片(此处使用相对位置)
picture_obj = document.add_picture(f'imgs/{sheet_names[0]}.png', width=Inches(1.25))
picture_obj.height = Cm(10) # 设置图片高度为4cm
picture_obj.width = Cm(15) # 设置图片宽度为4cm
except:
print('出错了')
document.save(TARGET_DIR / '数据V1.0.docx')