英文:
Is there a way to combine Excel workbooks into one Master workbook within python?
问题
我想知道是否可以在不将所有的Excel工作簿合并到一个主工作簿的单个工作表中的情况下实现这一点。
(更确切地说)
一个主工作簿,包含所有从属工作簿的工作表。
也许有一种方法可以在Python中使用VBA脚本来实现这一点?
英文:
I would like to know if this is possible without merging all Excel workbooks into a single Worksheet within a Master workbook
(rather)
A Master workbook, containing the sheets of all the slave workbooks
This picture shows what I'd like to do
Perhaps is there a way to use VBA script within python to do this?
答案1
得分: 2
是的,可以使用Python和Pandas来实现这个目标。您可以按表格打开多个文件,然后将它们简单地写入单个输出文档。更多信息,请参阅此处的文档。
您需要根据您的用例更改变量名称,但这是一个通用的想法:
mon_sheet = pd.read_excel('file_1_path.xlsx', sheetname='Mon')
tue_sheet = pd.read_excel('file_1_path.xlsx', sheetname='Tue')
wed_sheet = pd.read_excel('file_1_path.xlsx', sheetname='Wed')
thu_sheet = pd.read_excel('file_2_path.xlsx', sheetname='Thu')
fri_sheet = pd.read_excel('file_2_path.xlsx', sheetname='Fri')
sat_sheet = pd.read_excel('file_3_path.xlsx', sheetname='Sat')
sun_sheet = pd.read_excel('file_3_path.xlsx', sheetname='Sun')
with pd.ExcelWriter('output.xlsx') as writer:
mon_sheet.to_excel(writer, sheet_name='Mon')
tue_sheet.to_excel(writer, sheet_name='Tue')
wed_sheet.to_excel(writer, sheet_name='Wed')
thu_sheet.to_excel(writer, sheet_name='Thu')
fri_sheet.to_excel(writer, sheet_name='Fri')
sat_sheet.to_excel(writer, sheet_name='Sat')
sun_sheet.to_excel(writer, sheet_name='Sun')
希望这有所帮助!
英文:
Yes, this is achievable using python and pandas. You can open multiple files by sheet and simply write them to a single output document. See the documentation here for more information.
You'll need to change the variable names to fit your use case, but here is a generic idea:
mon_sheet = pd.read_excel('file_1_path.xlsx', sheetname = 'Mon')
tue_sheet = pd.read_excel('file_1_path.xlsx', sheetname = 'Tue')
wed_sheet = pd.read_excel('file_1_path.xlsx', sheetname = 'Wed')
thu_sheet = pd.read_excel('file_2_path.xlsx', sheetname = 'Thu')
fri_sheet = pd.read_excel('file_2_path.xlsx', sheetname = 'Fri')
sat_sheet = pd.read_excel('file_3_path.xlsx', sheetname = 'Sat')
sun_sheet = pd.read_excel('file_3_path.xlsx', sheetname = 'Sun')
with pd.ExcelWriter('output.xlsx') as writer:
mon_sheet.to_excel(writer, sheet_name = 'Mon')
tue_sheet.to_excel(writer, sheet_name = 'Tue')
wed_sheet.to_excel(writer, sheet_name = 'Wed')
thu_sheet.to_excel(writer, sheet_name = 'Thu')
fri_sheet.to_excel(writer, sheet_name = 'Fri')
sat_sheet.to_excel(writer, sheet_name = 'Sat')
sun_sheet.to_excel(writer, sheet_name = 'Sun')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论