简体   繁体   English

Python - Win32com - 打开工作簿并为每个选项卡创建一个新的 Excel 文件

[英]Python - Win32com - Open Workbook & Create a New Excel File for Each Tab

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.我有一个 MS Excel 工作簿,我想打开它,然后循环浏览选项卡并为原始工作簿中的每个选项卡创建和保存一个工作簿。 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.所以我打开文件 A,有选项卡 1、2、3,然后创建并保存文件 B、C、D,每个文件都有一个唯一的选项卡。 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.我有 VBA 的代码,它创建了一个工作表的单个副本,但是当我尝试在 Python 中执行此操作时,我最终得到了每个工作簿中的所有选项卡。 The following is the VBA that works:以下是有效的 VBA:


 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:以下是不起作用的 Python 代码:


 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.提前致谢。

You can save individual sheets via the SaveAs method:您可以通过 SaveAs 方法保存单个工作表:

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.注意我将 'r' 前缀放在字符串中,否则反斜杠会被 Python 解释为特殊字符,除非加倍混淆了字符串。

Thanks for Schollii, I was able to get on the right track.感谢 Schollii,我得以走上正轨。 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.特别是 Schollii 让我走上正轨。 Also Thanks TankorSmash for the answer, too.也感谢 TankorSmash 的回答。

for newer version of excel the codes changes from对于较新版本的 excel,代码从

xlApp.WorkbookAdd() xlApp.WorkbookAdd()

to

xlApp.Workbooks.Add() xlApp.Workbooks.Add()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM