Skip to content

Instantly share code, notes, and snippets.

@billydh
Created January 19, 2020 06:33
Show Gist options
  • Select an option

  • Save billydh/770482defcc8426babc0723b0cd32445 to your computer and use it in GitHub Desktop.

Select an option

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])
@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