Skip to content

Instantly share code, notes, and snippets.

@billydh
Created January 19, 2020 06:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save billydh/770482defcc8426babc0723b0cd32445 to your computer and use it in GitHub Desktop.
Save billydh/770482defcc8426babc0723b0cd32445 to your computer and use it in GitHub Desktop.
'''This python script is to extract each sheet in an Excel workbook as a new csv file'''
import csv
import xlrd
import sys
def ExceltoCSV(excel_file, csv_file_base_path):
workbook = xlrd.open_workbook(excel_file)
for sheet_name in workbook.sheet_names():
print 'processing - ' + sheet_name
worksheet = workbook.sheet_by_name(sheet_name)
csv_file_full_path = csv_file_base_path + sheet_name.lower().replace(" - ", "_").replace(" ","_") + '.csv'
csvfile = open(csv_file_full_path, 'wb')
writetocsv = csv.writer(csvfile, quoting = csv.QUOTE_ALL)
for rownum in xrange(worksheet.nrows):
writetocsv.writerow(
list(x.encode('utf-8') if type(x) == type(u'') else x for x in worksheet.row_values(rownum)
)
)
csvfile.close()
print sheet_name + ' has been saved at - ' + csv_file_full_path
if __name__ == '__main__':
ExceltoCSV(excel_file = sys.argv[1], csv_file_base_path = sys.argv[2])
@sosinovitch
Copy link

sosinovitch commented Jan 26, 2020

I just wrote code you can execute in your terminal which will grab all the worksheets in your active workbook and quickly save them in the same folder. It works super fast.

`'''This python script is to extract each sheet in an Excel workbook as a new csv file'''

import pandas as pd
import xlwings as xw
import os

workbook = xw.books.active
print("Current File Name : ",os.path.realpath(workbook.name))

workbook_path = os.path.realpath(workbook.name)
workbook = pd.read_excel(workbook_path,sheet_name=None)

for name, sheet in workbook.items():
print('processing - ' + name)
cwd = os.getcwd() + '/'
name_file = cwd + name + '.csv'
sheet.to_csv(name_file, sep="\t", index=False)

@abslearn-code
Copy link

abslearn-code commented Aug 31, 2020

Line 10: SyntaxError: Missing parentheses in call to 'print'. Did you mean print('processing - ' + sheet_name)?
Line 21: SyntaxError: Missing parentheses in call to 'print'. Did you mean print(sheet_name + ' has been saved at - ' + csv_file_full_path)?

Thanks!

@billydh
Copy link
Author

billydh commented Aug 31, 2020

Hi @abslearn-code, this was written in Python 2.x, that's why the print syntax works. For Python 3.x, you need parentheses as you mentioned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment