问题
I have an MS Excel Workbook that I would like to open and then loop through the tabs and create and save a workbook for each tab in the original workbook. So I open file A and there are tabs 1, 2, 3 and create and save a file B, C, D each with one a unique tab in it. I have the code for the VBA which creates a single copy of a worksheet but when I attempt to do this in Python I end up with all the tabs in each workbook. The following is the VBA that works:
Sub ConvertTabsToFiles()
Dim currPath As String
currPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=currPath & "\" & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
The following is the Python Code that does not work:
xlApp = win32.com.client.Dispatch("Excel.Application")
xlwb = xlApp.Workbooks.Open("C:\Inputfile.xlsx")
for sheet in xlwb.Worksheets:
sheet.Copy
xlApp.ActiveWorkbook.SaveAs("C:\Users\user\AppData\Local\Temp\\"+ sheet.Name+".xlsx")
Your help is really appreciated, I am stumped. Thanks ahead of time.
回答1:
Thanks for Schollii, I was able to get on the right track. The following is what worked for me, I hope it helps you:
for sheet in xlwb.Worksheets:
xlApp = win32com.client.Dispatch("Excel.Application")
nwb = xlApp.WorkbookAdd()
sheet.Copy(Before=nwb.Sheet(1))
nwb.SaveAs("C:\Users\user\AppData\Local\Temp\\" +sheet.Name+ ".xlsx")
nwb.Close(True)
Thank you everyone. Especially Schollii for getting me on the right track. Also Thanks TankorSmash for the answer, too.
回答2:
You can save individual sheets via the SaveAs method:
for sheet in xlwb.Worksheets:
filename = r"C:\Users\user\AppData\Local\Temp\" + sheet.Name + ".xlsx"
sheet.SaveAs(filename)
print('Saved sheet to', filename)
Note I put the 'r' prefix to the string otherwise the backslashes get interpreted by Python as special characters unless doubled which obfuscates the string.
来源:https://stackoverflow.com/questions/27712824/python-win32com-open-workbook-create-a-new-excel-file-for-each-tab