問題背景
將excel表中的成績內容制作為成績單,每頁對應一個學員的成績,方便打印
代碼實現
## 導入包
import pandas as pd
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH,WD_LINE_SPACING# 讀取 Excel 內容
df = pd.read_excel('./匯總的內容.xlsx')## 實例化一個
document = Document()## 循環寫入多個表
for i in range(len(df)):# 增加一級標題document.add_heading(f'{df.loc[i,"企業"]}的表', level=1)## 每個表格之間添加一個空行或者添加一句話document.add_paragraph(f'請{df.loc[i,"企業"]}于{df.loc[i,"日期"]}前,盡快完成以下表格填寫。')## 新建一個表,設置單元格樣式:https://blog.csdn.net/ibiao/article/details/78595295table = document.add_table(3, 4, style="Table Grid")## 第一行heading_cells = table.rows[0].cells# 每一列heading_cells[0].text = f'{df.loc[i,"序號"]}'heading_cells[1].text = f'{df.loc[i,"日期"]}'heading_cells[2].text = f'{df.loc[i,"企業"]}'heading_cells[3].text = f'{df.loc[i,"文號"]}'## 第二行heading_cells = table.rows[1].cells# 每一列heading_cells[1].text = f'{df.loc[i,"主題"]}'# (1)水平對齊table.cell(1,1).paragraphs[0].paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER## 第三行heading_cells = table.rows[2].cells# 每一列heading_cells[1].text = '簽收'## 合并單元格table.cell(0,0).merge(table.cell(2,0))table.cell(1,1).merge(table.cell(1,3))table.cell(2,1).merge(table.cell(2,3))## 添加分頁符,一頁一張表document.add_page_break()# 保存文件
document.save("./成績單打印.docx")