使用Python xlutils 保存中文内容:
样例脚本:
import xlutils.copy
file_name = "test.xls"
#读取文件
read_file = xlrd.open_workbook(file_name)
#参数注释:
#file_path:文件路径,包含文件的全名称
#formatting_info=True:保留Excel的原格式
#将文件复制到内存
write_data = xlutils.copy.copy(read_file)
#读取复制后文件的sheet1
write_save = write_data.get_sheet(0)
#写入数据
write_save.write(1,1,"测试2")
#参数注释:
#x,y:写入目标格的位置坐标
#value:写入数据
#保存写入数据后的文件到原文件路径
write_data.save(file_name)
出现如下错误:
Traceback (most recent call last):
File "G:\eclipse\eclipse-workspace\Demo\reTest.py", line 70, in <module>
write_data.save(file_name)
File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 710, in save
doc.save(filename_or_stream, self.get_biff_data())
File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 674, in get_biff_data
shared_str_table = self.__sst_rec()
File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 636, in __sst_rec
return self.__sst.get_biff_record()
File "C:\Python27\lib\site-packages\xlwt\BIFFRecords.py", line 77, in get_biff_record
self._add_to_sst(s)
File "C:\Python27\lib\site-packages\xlwt\BIFFRecords.py", line 92, in _add_to_sst
u_str = upack2(s, self.encoding)
File "C:\Python27\lib\site-packages\xlwt\UnicodeUtils.py", line 50, in upack2
us = unicode(s, encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
在网上查找到的方法是:
注释如下代码
if isinstance(s, unicode_type):
us = s
else:
us = unicode(s, encoding)
修改成下图中的代码样式
def upack2(s, encoding='ascii'):
# If not unicode, make it so.
'''
if isinstance(s, unicode_type):
us = s
else:
us = unicode(s, encoding)
'''
if isinstance(s, unicode):
us = s
elif s is not None:
us = unicode(s, encoding)
else:
us = unicode('', encoding)
# Limit is based on number of content characters
# (not on number of bytes in packed result)
修改后还是报错。
最终排查发现是在写入数据时因为数据的编码格式造成的问题:
#修改前
#报错的
write_save.write(1,1,"测试2")
#修改后
#正常的
write_save.write(1,1,u"测试2")