Question

I am trying to copy all the data in csv to excel "xlsx" file using python. I am using following code to do this:

from openpyxl import load_workbook
import csv
#Open an xlsx for reading
wb = load_workbook(filename = "empty_book.xlsx")
#Get the current Active Sheet
ws = wb.get_active_sheet()
#You can also select a particular sheet
#based on sheet name
#ws = wb.get_sheet_by_name("Sheet1")
#Open the csv file
with open("Pricing_Updated.csv",'rb') as fin:
    #read the csv
    reader = csv.reader(fin)
    #get the row index for the xlsx
    #enumerate the rows, so that you can
    for index,row in enumerate(reader):

        i=0
        for row[i] in row:
            ws.cell(row=index,column=i).value = row[i]
            i = i+1
#save the excel file
wb.save("empty_book.xlsx")

I found this code on SO itself and modified it to make it usable for my case. But this code is throwing UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128) error for ws.cell(row=index,column=i).value = row[i] line.

Please help me in resolving this issue.

Update: I tried using following code also to resolve the issue but came across UnicodeDecode error again for ws.cell(row=rowx,column=colx).value = row[colx] line:

for rowx,row in enumerate(reader):
    for colx, value in enumerate(row):

        ws.cell(row=rowx,column=colx).value = row[colx]

Update 2: I tried using xlwt module also to copy the csv into xls (as it doesn't support xlxs) and again came across UnicodeDecode error, code which I used was:

import glob, csv, xlwt, os
wb = xlwt.Workbook()
for filename in glob.glob("Pricing_Updated.csv"):
    (f_path, f_name) = os.path.split(filename)
    (f_short_name, f_extension) = os.path.splitext(f_name)
    ws = wb.add_sheet(f_short_name)
    spamReader = csv.reader(open(filename, 'rb'))
    for rowx, row in enumerate(spamReader):
        for colx, value in enumerate(row):
            ws.write(rowx, colx, value)
wb.save("exceltest7.xls")
Was it helpful?

Solution

The error indicates that the cell object is trying to convert the value to Unicode, but the value contains non-ASCII characters. What encoding is your csv file in? You must find that out, though on Windows a good guess would be the "mbcs" encoding, which Python defines to be the same as Windows "ANSI" code page. Try this:

for rowx,row in enumerate(reader):
    for colx, value in enumerate(row):
        ws.cell(row=rowx,column=colx).value = unicode(value, "mbcs")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top