在运行python代码将信息写入excel表格的时候报错:
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xb8 in position 59: ordinal not in range(128)
部分源码如下:
import xlwt
writeBook = xlwt.Workbook()
sheet = writeBook.add_sheet("test")
sheet_line = 0
(略)
for k,v in self.context_dict.items():
if flag == True:
sheet.write(sheet_line, 0, k)
sheet.write(sheet_line, 1, v)
sheet_line += 1
writeBook.save("answer.xls")
程序在最后一行writeBook.save(“answer.xls”)处报错。试了网上多种方法,包括重新设置编码方式为“utf-8”:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
以及将写入信息编码为’utf-8’方式:
sheet.write(sheet_line, 0, k.encode('utf-8'))
sheet.write(sheet_line, 1, v.encode('utf-8'))
仍旧报错。
后发现写入的内容“k”中包含中文,将其中的中文删除后遂运行成功。