Search code examples
pythonxlrd

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 37: ordinal not in range(128)


Getting this error while executing below code:

def csvFromExcel(path):
    'This is for converting Delights.xlsx sheets into sheetName.csv '
    wb = xlrd.open_workbook(path)
    print wb.nsheets
    sheetNames = []
    sheetNames = wb.sheet_names()
    print sheetNames
    for sheetName in sheetNames:
        sh = wb.sheet_by_name(sheetName)
        csvFile = open("processed/"+sheetName+'.csv', 'wb')
        wr = csv.writer(csvFile, quoting=csv.QUOTE_ALL)

        for rownum in xrange(sh.nrows):
            wr.writerow(sh.row_values(rownum))
        csvFile.close()

if __name__ == "__main__":
    path = 'toBeProcess/Delights.xlsx'
    csvFromExcel(path)

At this point i'm getting error: wr.writerow(sh.row_values(rownum))

Does anyone have any idea how to fix it.


Solution

  • I have solved it by using encode('utf-8')

    def csvFromExcel(path):
        'This is for converting Delights.xlsx sheets into sheetName.csv '
        wb = xlrd.open_workbook(path)
        print wb.nsheets
        sheetNames = []
        sheetNames = wb.sheet_names()
        print sheetNames
        for sheetName in sheetNames:
            sh = wb.sheet_by_index(2)
            csvFile = open("processed/"+sheetName+".csv", 'wb')
            wr = csv.writer(csvFile, quoting=csv.QUOTE_ALL)
    
            for rownum in xrange(sh.nrows):
                wr.writerow(
                     list(x.encode('utf-8') if type(x) == type(u'') else x
                          for x in sh.row_values(rownum)))
            csvFile.close()
    
    if __name__ == "__main__":
        path = 'toBeProcess/Delights.xlsx'
        csvFromExcel(path)