在使用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
若本文侵犯了以上的利益,請留言聯系
