how to concatenate multiple excel sheets from the same file?

前端 未结 4 1398
鱼传尺愫
鱼传尺愫 2020-12-17 03:59

I have a big excel file that contains many different sheets. All the sheets have the same structure like:

Name
col1  col2  col3  col4
1     1     2     4
4           


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 04:42

    file_save_location='myfolder'                                
    file_name='filename'
    
    location = ''myfolder1'
    os.chdir(location)
    files_xls = glob.glob("*.xls*")
    excel_names=[f for f in files_xls]
    sheets = pd.ExcelFile(files_xls[0]).sheet_names
    def combine_excel_to_dfs(excel_names, sheet_name):
        sheet_frames = [pd.read_excel(x, sheet_name=sheet_name) for x in excel_names]
        combined_df = pd.concat(sheet_frames).reset_index(drop=True)
        return combined_df
    
    i = 0
    
    while i < len(sheets):
        process = sheets[i]
        consolidated_file= combine_excel_to_dfs(excel_names, process)
        consolidated_file.to_csv(file_save_location+file_name+'.csv')
        i = i+1
    else:
        "we done on consolidation part"
    

提交回复
热议问题