Python 2:在Excel文件中编写时出现ASCII问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 2:在Excel文件中编写时出现ASCII问题相关的知识,希望对你有一定的参考价值。
问题草图:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)
我正在尝试编写一个简单的python程序,它可以自动完成空白单元,数据出现在上面的同一列中。
由于文件中有中文字符,我已经想到了ASCII的问题,所以我试着把它改成UTF-8。
代码如下:
#!/usr/bin/python
# -*- coding:utf-8 -*-
from xlrd import open_workbook
from xlwt import Workbook
from xlutils.copy import copy
rb = open_workbook('data.xls', 'utf-8')
wb = copy(rb)
sh = wb.get_sheet(0)
s = rb.sheet_by_index(0)
cols = s.ncols
rows = s.nrows
temp = 0
for cx in range(cols):
for rx in range(rows):
if s.cell_value(rowx = rx, colx = cx).encode('utf-8') != "":
temp = s.cell_value(rowx = rx, colx = cx).encode('utf-8')
print(temp) #to verify
else:
sh.write(rx, cx, temp)
wb.save('data.xls')
但是,问题仍然存在。结果在终端:
ZishengdeMacBook-Pro:Downloads zisheng$ python form.py
(printed result ignored, and it looked good)
Traceback (most recent call last):
File "form.py", line 41, in <module>
wb.save('data.xls')
File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/Workbook.py", line 710, in save
doc.save(filename_or_stream, self.get_biff_data())
File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/Workbook.py", line 674, in get_biff_data
shared_str_table = self.__sst_rec()
File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/Workbook.py", line 636, in __sst_rec
return self.__sst.get_biff_record()
File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/BIFFRecords.py", line 77, in get_biff_record
self._add_to_sst(s)
File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/BIFFRecords.py", line 92, in _add_to_sst
u_str = upack2(s, self.encoding)
File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/UnicodeUtils.py", line 50, in upack2
us = unicode(s, encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)
有人可以帮忙吗?提前致谢!
我已经明白了!
要解决这个问题,我们可以在编写过程中添加UTF-8表示法:
sh.write(rx, cx, unicode(temp, 'utf-8'))
它已经完成了。
答案
问题解决了。
要解决这个问题,我们可以在编写过程中添加UTF-8表示法:
sh.write(rx, cx, unicode(temp, 'utf-8'))
以上是关于Python 2:在Excel文件中编写时出现ASCII问题的主要内容,如果未能解决你的问题,请参考以下文章
将 Excel 工作表导出到 PDF 文件时出现奇怪的 Powershell 行为
从Dynamics 365打开下载的Excel文件时出现Excel错误 - 客户服务