利用pandas结合openpyxl批量处理生成excel表格
1.应用场景:
现有两张表:学生姓名excel表、excel问卷模板表
需求:1.想尽快将 学生姓名excel表 的姓名信息在 excel问卷模板表 中的某一位置填写,且每个学生都是单独的一个excel问卷模板表,这时就需要在某一文件夹下批量生成excel表格;
2.以及将每个生成的 excel文件 的文件名以相应的学生姓名结尾
3.生成的excel表格的样式与问卷模板表保持一致
2.话不多说,直接上代码:
主要处理方法
import copy
import openpyxl
from import get_column_letter
def copyExcelFunc(path, save_path, name):
wb = openpyxl.load_workbook(path)
wb2 = ()
sheetnames =
for sheetname in sheetnames:
print(sheetname)
sheet = wb[sheetname]
sheet2 = wb2.create_sheet(sheetname)
# tab颜色
sheet2.sheet_properties.tabColor = sheet.sheet_properties.tabColor
# 开始处理合并单元格形式为“(<CellRange A1:A4>,),替换掉(<CellRange 和 >,)' 找到合并单元格
wm = list(sheet.merged_cells)
if len(wm) > 0:
for i in range(0, len(wm)):
cell2 = str(wm[i]).replace('(<CellRange ', '').replace('>,)', '')
sheet2.merge_cells(cell2)
for i, row in enumerate(sheet.iter_rows()):
sheet2.row_dimensions[i+1].height = sheet.row_dimensions[i+1].height
for j, cell in enumerate(row):
sheet2.column_dimensions[get_column_letter(j+1)].width = sheet.column_dimensions[get_column_letter(j+1)].width
# print(":",str().endswith("填报人:"))
if (str().endswith("填报人:")):
= str() + name
print("new_cell.value:", ) #处理完填报人信息后,进行保存
(row=i + 1, column=j + 1, value=)
# 设置单元格格式
source_cell = (i+1, j+1)
target_cell = (i+1, j+1)
target_cell.fill = (source_cell.fill)
if source_cell.has_style:
target_cell._style = (source_cell._style)
target_cell.font = (source_cell.font)
target_cell.border = (source_cell.border)
target_cell.fill = (source_cell.fill)
target_cell.number_format = (source_cell.number_format)
target_cell.protection = (source_cell.protection)
target_cell.alignment = (source_cell.alignment)
if 'Sheet' in :
del wb2['Sheet']
#进行excel文件重命名后保存
(save_path.replace(save_path.split("_")[1], name+".xlsx"))
()
()
print('Done.')
启动文件,调用上面的方法批量生成excel
# -*- coding: utf-8 -*-
"""
1.首先利用pandas.read_excel读取 学生姓名excel 进行遍历
2.遍历过程中读取问卷模板信息,且过滤每行excel数据,找到需要填写姓名的位置进行填写;以及对文件名进行重命名
3.指定输出文件夹路径进行excel文件批量保存输出
"""
import pandas as pd
import copyExcel
readNameExcelPath = r'学生姓名文件的绝对路径.xlsx'
getModelExcelPath = r'问卷模板的绝对路径.xlsx'
targetSavePath = r'目标文件夹\问卷模板_XXX.xlsx' #XXX 为学生姓名
def handle_excel(readNameExcelPath, getModelExcelPath, targetSavePath):
all_name = pd.read_excel(readNameExcelPath, sheet_name='Sheet1')['name']
print("读取到所有学生姓名", all_name)
for name in all_name:
(getModelExcelPath, targetSavePath, name)
handle_excel(readNameExcelPath, getModelExcelPath, targetSavePath)
以上就是本篇博客的全部内容,拿去把你!
好久没写博客了,哈哈!有点手生 ^_^