Search code examples
python-2.7unicodepycharmxlwt

How can I write characters like äöü in a Excel file without getting a UnicodeDecodeError


I want to use the xlwt to create an Excel file. However, some of the strings contain letters like ä, ü and ö. Therefore, I get the UnicodeDecodeError. Can this be fixed?

I transfered my code from 3.5 (IDLE) to 2.7 (Pycharm). It worked in 3.5, probably because I didn't need to put

# coding=utf-8  
# -*- coding: iso-8859-1 -*-  

at the beginning of the code in 3.5...

# coding=utf-8
# -*- coding: iso-8859-1 -*-
import xlwt

name_of_new_file = "Test.xls"
workbook_new = xlwt.Workbook()
worksheet = workbook_new.add_sheet("Testing")
worksheet.write(0, 0, "ä")  # it works if I write an "a" instead
workbook_new.save("C:\\...\\Test123.xls")

I'm pretty sure the reason for the problem is about the first two lines. The Error message says: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)


Solution

  • in python 2, the encoding is a thouble

    worksheet.write(0, 0, u"ä")