需求:

Python  向 Excel 工作表中批量插入指定的工作表

 vab 程序  https://www.cnblogs.com/shanger/p/12993804.html

vba 的 sub 过程交互性不很好,泛化性也不是很好。

Python 使用 pandas 和 openpyxl 简单明了,泛化性更好。

 

1、加载包

import pandas  as pd
import openpyxl

2、读取表格

wb_file = 'E:\\excel_vba\\test.xlsx'
df = pd.read_excel( wb_file)
df

Python  向 Excel 工作表中批量插入指定的工作表

 

 

 3、去重生成指定的表名

new_sheet_names = df['班级'].drop_duplicates()
new_sheet_names

4、插入指定名称的工作表,保存

wb = openpyxl.load_workbook(wb_file)  # 加载工作表
for name in new_sheet_names:
    wb.create_sheet(title=name)  # 插入工作表,指定名称,index 参数默认为 -1

new_wb_file = os.path.join(os.path.dirname(wb_file), 'test_1.xlsx')
wb.save(new_wb_file)

结果:

Python  向 Excel 工作表中批量插入指定的工作表

 

 

 Python  向 Excel 工作表中批量插入指定的工作表

 

 

 

完整代码:

import os
import pandas  as pd
import openpyxl

wb_file = 'E:\\excel_vba\\test.xlsx'
df = pd.read_excel( wb_file)
wb = openpyxl.load_workbook(wb_file)  # 加载工作表
for name in df['班级'].drop_duplicates():
    wb.create_sheet(title=name)  # 插入工作表,指定名称,index 参数默认为 -1

new_wb_file = os.path.join(os.path.dirname(wb_file), 'test_1.xlsx')
wb.save(new_wb_file)

 

相关文章:

  • 2021-11-17
  • 2021-07-06
  • 2021-05-25
  • 2021-08-10
  • 2021-07-03
  • 2022-12-23
  • 2021-12-04
  • 2021-12-05
猜你喜欢
  • 2022-12-23
  • 2021-09-10
  • 2022-02-21
  • 2021-11-30
  • 2021-11-23
  • 2022-01-13
  • 2021-12-04
相关资源
相似解决方案