亲宝软件园·资讯

展开

python利用openpyxl拆分多个工作表的工作簿的方法

人气:0

实现按目录拆分工作簿,源数据如下图

按目录拆分成N个文件。

上代码,没有找是否有整个sheet 复制的,先逐个cell复制解决问题。:

# encoding: utf-8
"""
@author: 陈年椰子
@contact: hndm@qq.com
@version: 1.0
@file: Split_Xls.py
@time: 2019/9/24 0028 15:04
说明
"""
def Split_Xls(xls_file):
  from openpyxl import load_workbook
  from openpyxl import Workbook
 
  wb = load_workbook(xls_file)
  sheet_list = wb.sheetnames
  print(sheet_list)
  a_sheet = wb['目录']
  for i in range(3,6):
    sheet_name = a_sheet['B{}'.format(i)].value
    if sheet_name is None:
      break
    if sheet_name == '':
      break
    sr_sheet = wb[sheet_name]
    new_file_name = "{}.xlsx".format(sheet_name)
    print(sheet_name)
    wb_tg = Workbook()
    ws = wb_tg.active
    ws.title = sheet_name
 
    # 两个for循环遍历整个excel的单元格内容
    for i, row in enumerate(sr_sheet.iter_rows()):
      for j, cell in enumerate(row):
        # print(i,j,cell.value)
        ws.cell(row=i + 1, column=j + 1, value=cell.value)
    wb_tg.save(new_file_name)
    wb_tg.close()
  wb.close()
 
 
 
def Split_Xls2(xls_file):
  # 这个是通过删除其他的工作表,只留下要保存的工作表,这样就可以整个表复制,包括样式,过程曲折,但能达到效果。
  from openpyxl import load_workbook
  wb = load_workbook(xls_file)
  sheet_list = wb.sheetnames
  print(sheet_list)
  work_list = []
  a_sheet = wb['目录']
  for i in range(3,6):
    sheet_name = a_sheet['B{}'.format(i)].value
    if sheet_name is None:
      break
    if sheet_name == '':
      break
    work_list.append(sheet_name)
  wb.close()
 
  for sheet_name in work_list:
    new_file_name = "{}.xlsx".format(sheet_name)
    print('处理工作表', sheet_name, '\t保存文件', new_file_name)
    wb = load_workbook(xls_file)
    # print(wb.sheetnames)
    for del_sheet in sheet_list:
      if del_sheet != sheet_name:
        # print('del',del_sheet)
        wb.remove(wb[del_sheet])
    wb.save(new_file_name)
    wb.close()
 
 
Split_Xls2('test.xlsx')
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论