使用python模块xlutils保存xls文件问题解决

在使用python下编辑excel文件的模块保存xls文件的修改时,报出如下错误

(其实吧我把问题解决了才想起了写个记录的,实际的报错内容没copy下来,这段是网上别人一样的错误)

File "/usr/local/lib/python2.7/dist-packages/xlwt/Workbook.py", line 662, in save
doc.save(filename,self.get_biff_data())
File "/usr/local/lib/python2.7/dist-packages/xlwt/Workbook.py", line 630, in get_biff_data
before += self.all_fonts_num_formats_xf_styles_rec()
File "/usr/local/lib/python2.7/dist-packages/xlwt/Workbook.py", line 533, in __all_fonts_num_formats_xf_styles_rec
return self.__styles.get_biff_data()
File "/usr/local/lib/python2.7/dist-packages/xlwt/Style.py", line 183, in get_biff_data
result += self._all_num_formats()
File "/usr/local/lib/python2.7/dist-packages/xlwt/Style.py", line 208, in _all_num_formats
result += NumberFormatRecord(fmtidx, fmtstr).get()
File "/usr/local/lib/python2.7/dist-packages/xlwt/BIFFRecords.py", line 789, in __init
ufmtstr = upack2(fmtstr)
File "/usr/local/lib/python2.7/dist-packages/xlwt/UnicodeUtils.py", line 50, in upack2
us = unicode(s, encoding)
TypeError: coercing to Unicode: need string or buffer, NoneType found

在经历多番的查找解决方法和尝试中终于找到了靠谱的解决方法

在上面贴出的报错的内容中,标记部分就是问题所在的根源,这个文件的部分内容如下

1 def upack2(s, encoding='ascii'):
2     # If not unicode, make it so.
3     if isinstance(s, unicode_type):
4         us = s
5     else:
6         us = unicode(s, encoding)
7     # Limit is based on number of content characters
8     # (not on number of bytes in packed result)

红色部分没有涵盖当“s”为None时的情况(没想到官方的模块也有问题啊)

于是我们对这部分进行补充修改,结果如下

 1 def upack2(s, encoding='ascii'):
 2     # If not unicode, make it so.
 3     '''
 4     if isinstance(s, unicode_type):
 5         us = s
 6     else:
 7         us = unicode(s, encoding)
 8     '''
 9     if isinstance(s, unicode):
10         us = s
11     elif s is not None:
12         us = unicode(s, encoding)
13     else:
14         us = unicode('', encoding)
15     # Limit is based on number of content characters
16     # (not on number of bytes in packed result)

为了方便日后出现问题需要回退,建议将原内容注释

修改后保存,再次执行代码就OK了

 

解决办法源自http://blog.sina.com.cn/s/blog_7407815a0101o7oa.html所引用的https://github.com/python-excel/xlwt/issues/22

若本文侵犯了以上的利益,请留言联系

posted @ 2017-03-03 11:14  怀念你的温柔  阅读(3766)  评论(0编辑  收藏  举报