Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert multiple excel sheets to csv python

Tags:

python

csv

excel

I want to convert all the excel document(.xls) sheets into csv, If excel document has one sheet only then I am converting like as follow-

   wb = open_workbook(path1)
    sh = wb.sheet_by_name('Sheet1')
    csv_file = open(path2, 'w')
    wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)
    for rownum in range(sh.nrows):
        wr.writerow(sh.row_values(rownum))
    csv_file.close()

If my excel(.xls) document have more than one sheet i.e.('Sheet1', 'Sheet2', 'Sheet3', 'Sheet4') than how to convert all sheets into csv.

Any help would be appreciated.

like image 689
Prashant Avatar asked Aug 24 '26 07:08

Prashant


2 Answers

My understanding is that you're trying to get one CSV file for each sheet.

You can obtain that by executing the following:

excel_file = 'data/excel_file.xlsx'
all_sheets = pd.read_excel(excel_file, sheet_name=None)
sheets = all_sheets.keys()

for sheet_name in sheets:
    sheet = pd.read_excel(excel_file, sheet_name=sheet_name)
    sheet.to_csv("data/%s.csv" % sheet_name, index=False)

If you actually want to concatenate all sheets to one CSV, they all need to have the same column names. You can concatenate all your CSV files into one by executing the following:

import glob
import os
all_files = glob.glob(os.path.join("data", "*.csv"))
df_from_each_file = (pd.read_csv(f, sep=',') for f in all_files)
df_merged = pd.concat(df_from_each_file, ignore_index=True)
df_merged.to_csv( "data/merged.csv")

Source for the second snippet

like image 92
Hadrien Avatar answered Aug 25 '26 22:08

Hadrien


I am using python3.x in Anaconda environment and In my case file name is 'INDIA-WMS.xlsx' having 40 different sheets below code will create 40 different csv files named as sheet name of excel file, as 'key.csv'. Hope this will help your issue.

    import pandas as pd
    df = pd.read_excel('INDIA-WMS.xlsx', sheet_name=None)  
    for key in df.keys(): 
        df[key].to_csv('%s.csv' %key)

For example if you have different sheets like 'Sheet1', 'Sheet2', 'Sheet3' etc. then above code will create different csv file as 'Sheet1.csv', 'Sheet2.csv', 'Sheet3.csv'. Here 'key' is the sheet name of your excel workbook. If you want to use data content inside sheets you can use the for loop as for key, value in df.items():

like image 24
Ashu007 Avatar answered Aug 25 '26 21:08

Ashu007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!