1

I have csv files having encoding-'utf-8'. I need to convert the csv to excel workbook with same encoding but unable to do so. Tried many things but not able to fix. Here is the code snippet. NOte: Using xlsxwriter package

def csv_to_excel(input_file_path, output_file_path):
    file_path = input_file_path
    excel_file_path = output_file_path
    wb = Workbook(excel_file_path.encode('utf-8', 'ignore'), {'encoding': 'utf-8'})
    sheet1 = wb.add_worksheet(("anyname1").encode('utf-8','ignore'))
    sheet2 = wb.add_worksheet(("anyname2").encode('utf-8','ignore'))

    for filename in glob.glob(file_path):
        (f_path, f_name) = os.path.split(filename)
         w_tab = str(f_name.split('_')[2]).split('.')[0] 
         if (w_tab=="anyname1"):
             w_sheet = sheet1
         elif (w_tab=="anyname2"):
             w_sheet = sheet2

         spamReader = csv.reader(open(filename, "rb"), delimiter=',',quotechar='"')
         row_count = 0
         for row in spamReader:
             for col in range(len(row)):
                  w_sheet.write(row_count,col,row[col])
             row_count +=1     
    try:
         os.remove(excel_file_path)
    except:
         pass
    wb.close()
    print "Converted CSVs to Excel File"

Errors: Case1: When I am trying to open the utf-8 encoded csv file as follows:

spamReader = csv.reader(io.open(filename, "r", encoding = 'utf-8'), delimiter=',',quotechar='"')

Then getting error while iterating over the spamReader object as UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 92: ordinal not in range(128)

Case2: When I am trying to open the same csv file as binary as mentioned in above code snippet, then I am not able to save it as utf-8 encoded excel, so while calling wb.close(), getting error as UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 12: ordinal not in range(128)

I have just started learning python so maybe this is not that big issue but Please help me on this.

jmcnamara
  • 38,196
  • 6
  • 90
  • 108

0 Answers0