首先你心里要有一张表的样子,openpyxl才能帮你创建出其余的29张。
import openpyxl
from openpyxl.styles import Alignment, Font
import calendar
from datetime import datework_path = r'XX\YY\ZZ\日报-九月.xlsx'try:workbook = openpyxl.load_workbook(work_path)
except FileNotFoundError:workbook = openpyxl.Workbook()workbook.save(work_path)workbook = openpyxl.load_workbook(work_path)# 创建30张表
for i in range(1, 31):# 新建表格sheet = workbook.create_sheet(title=f'9.{i}')# 设置单元格内容sheet['A1'].value = f'2023.09.{i:02d}({calendar.day_name[date(2023, 9, i).weekday()]})'sheet['A2'].value = '特记'sheet['A3'].value = '类型'sheet['B3'].value = '任务描述'sheet['C3'].value = '完成情况'sheet['D3'].value = '启发'sheet['A4'].value = '工作'sheet['A8'].value = '兴趣'sheet['A9'].value = '交际'sheet['A10'].value = '生活'sheet['A11'].value = '额外'# 设置单元格合并sheet.merge_cells('A1:D1')sheet.merge_cells('B2:D2')sheet.merge_cells('A4:A7')sheet.merge_cells('B11:C11')# 设置B、C、D三列的宽度为常规宽度的4倍sheet.column_dimensions['B'].width = sheet.column_dimensions['C'].width = sheet.column_dimensions['D'].width = 4 * \sheet.column_dimensions['A'].width# 设置单元格对齐方式for row in sheet.iter_rows(min_row=1, max_row=20, min_col=1, max_col=20):for cell in row:cell.alignment = Alignment(horizontal='center', vertical='center')# 设置中文字体样式
font_zh = Font(name='宋体')
for sheet in workbook.sheetnames:for row in workbook[sheet].rows:for cell in row:if isinstance(cell.value, str) and any('\u4e00' <= char <= '\u9fff' for char in cell.value):cell.font = font_zh# 设置英文字体样式
font_en = Font(name='Times New Roman')
for sheet in workbook.sheetnames:for row in workbook[sheet].rows:for cell in row:if isinstance(cell.value, str) and all(not ('\u4e00' <= char <= '\u9fff') for char in cell.value):cell.font = font_en# 保存
workbook.save(work_path)
结果展示