简体   繁体   中英

How to merge excel files to one in Pandas?

I have 9 excel files named "1_mock" to "10_mock" (It needs to skip "5_mock"). These files just have a single sheet.

Then, I want to combine those 9 files into 9 single sheets, but not to concat them into one sheet. I've found this online merger https://products.aspose.app/cells/merger . Though it's convenient to use, I need to stop processing the code and turn to this link every time. Not very efficient at all! Thus, I hope there are ways to write this process into a code.

Thanks!

You just have to read all the files first and then write them to the same output file using the to_excel function but have a different sheet_name parameter every time. You can try something like this:

import pandas as pd
files_list = ["1_mock.xlsx", "2_mock.xlsx", "3_mock.xlsx", .....]
df_list = [pd.read_excel(file_name) for file_name in files_list]
with pd.ExcelWriter('output.xlsx') as writer:
     for i in range(len(files_list)):
          df_list[i].to_excel(writer, sheet_name=files_list[i].replace(".xlsx",""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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