Search code examples
pythonexcelcsvworksheet

Exclude worksheet when converting from Excel to CSV in python


I have an excel spreadsheet which has multiple worksheets in it. My python code converts the worksheets to separate CSV's. I am trying to exclude worksheets if there is any empty worksheets.

Here is my code:

def csv_from_excel(excel_file):

    workbook = xlrd.open_workbook(excel_file)
    all_worksheets = workbook.sheet_names()
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        with open('{}.csv'.format(worksheet_name), 'wb') as your_csv_file:
            wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
            for rownum in xrange(worksheet.nrows):
                wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])
    print('CSV files has been generated from Excel')

I expect the empty worksheets should be skipped.

I tried if worksheet.nrows > 0: before for loop , but it's including the empty worksheets as well.


Solution

  • I made a tiny Excel file with 3 sheets (sheet number 2 is empty) and tried the following:

    import xlrd
    
    workbook = xlrd.open_workbook("TestMap.xlsx")
    all_worksheets = workbook.sheet_names()
    
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        if worksheet.nrows > 0:
            print(worksheet_name)
    

    The output is as i wanted:

    >>> sheet1
    sheet3
    

    Are you sure your sheets are really empty?