新手:我有一个Excel文件,它有100多个不同的表格。每张表都包含几个表格和图表。
我希望将每张工作表保存为新的Excel文件。
我尝试了很多python代码,但没有一个工作。
请帮忙。谢谢!
编辑1:在回复评论时,这就是我的尝试:
import pandas as pd
import xlrd
inputFile = 'D:\Excel\Complete_data.xlsx'
#getting sheet names
xls = xlrd.open_workbook(inputFile, on_demand=True)
sheet_names = xls.sheet_names()
path = "D:/Excel/All Files/"
#create a new excel file for every sheet
for name in sheet_names:
parsing = pd.ExcelFile(inputFile).parse(sheetname = name)
#writing data to the new excel file
parsing.to_excel(path+str(name)+".xlsx", index=False)
准确地说,问题在于复制表格和图表。
答案 0 :(得分:4)
我刚刚解决了这个问题所以会发布我的解决方案,我不知道它会如何影响图表等。
import os
import xlrd
from xlutils.copy import copy
import xlwt
path = #place path where files to split up are
targetdir = (path + "New_Files/") #where you want your new files
if not os.path.exists(targetdir): #makes your new directory
os.makedirs(targetdir)
for root,dir,files in os.walk(path, topdown=False): #all the files you want to split
xlsfiles=[f for f in files] #can add selection condition here
for f in xlsfiles:
wb = xlrd.open_workbook(os.path.join(root, f), on_demand=True)
for sheet in wb.sheets(): #cycles through each sheet in each workbook
newwb = copy(wb) #makes a temp copy of that book
newwb._Workbook__worksheets = [ worksheet for worksheet in newwb._Workbook__worksheets if worksheet.name == sheet.name ]
#brute force, but strips away all other sheets apart from the sheet being looked at
newwb.save(targetdir + f.strip(".xls") + sheet.name + ".xls")
#saves each sheet as the original file name plus the sheet name
不是特别优雅但对我来说效果很好并且功能简单。希望对某人有用。