2017-06-21 319 views
2

我正在Python 3.6中編寫一個小程序,該程序讀取一個excel文件,然後修改單元格的格式。我想在同一小區內的多種格式,所以我使用xlwtwrite_rich_textPython 3 - xlwt保存工作簿錯誤

import xlrd 
import xlwt 
from xlutils.copy import copy 

col = 0 
row = 0 

rb = xlrd.open_workbook('test.xls', formatting_info=True) 

r_sheet = rb.sheet_by_index(0) 
text_cell = r_sheet.cell_value(row, col) 

book = copy(rb) 
first_sheet = book.get_sheet(0) 

font1 = xlwt.easyfont('struck_out true, color_index red') 
font2 = xlwt.easyfont('color_index green') 

seg1 = (text_cell[0:10], font1) 
seg2 = (text_cell[10:], font2) 


first_sheet.write_rich_text(row, col, [seg1, seg2]) 

book.save('test.xls') 

一切正常了編寫到excel文件的點,但然後保存工作簿時,我得到了錯誤TypeError: must be str, not bytes

完整的錯誤:

File "test.py", line 91, in <module> 
book.save('test.xls') 

File "C:\Users\...\AppData\Local\Continuum\Anaconda2\envs\py36\lib\site-packages\xlwt\Workbook.py", line 710, in save 
doc.save(filename_or_stream, self.get_biff_data()) 

File "C:\Users\...\AppData\Local\Continuum\Anaconda2\envs\py36\lib\site-packages\xlwt\Workbook.py", line 674, in get_biff_data 
shared_str_table = self.__sst_rec() 

File "C:\Users\...\AppData\Local\Continuum\Anaconda2\envs\py36\lib\site-packages\xlwt\Workbook.py", line 636, in __sst_rec 
return self.__sst.get_biff_record() 

File "C:\Users\...\AppData\Local\Continuum\Anaconda2\envs\py36\lib\site-packages\xlwt\BIFFRecords.py", line 79, in get_biff_record 
self._add_rt_to_sst(s) 

File "C:\Users\...\AppData\Local\Continuum\Anaconda2\envs\py36\lib\site-packages\xlwt\BIFFRecords.py", line 108, in _add_rt_to_sst 
rt_str, rt_fr = upack2rt(rt, self.encoding) 

File "C:\Users\...\AppData\Local\Continuum\Anaconda2\envs\py36\lib\site-packages\xlwt\UnicodeUtils.py", line 86, in upack2rt 
fr += pack('<HH', offset, fontx) 

TypeError: must be str, not bytes 

我一直在尋找一個解決這個問題,但答案似乎不存在對解決我的問題:

xlwt book.save TypeError: must be str, not bytes

Python code, not able to write into xls

然後我發現這個問題可能與Python 3和Python 2中的字符串處理方式有關,並且我可能會b e在某處導致錯誤的字節串。

我看了text_cell的類型,並且是str,我嘗試了在seg1seg2中忽略的字體,但它仍然不起作用。 最後,我在Python 2.7上運行了這個相同的腳本,它工作正常!

壞消息是我需要在Python 3中工作的代碼,因爲只能運行Python 3的服務器不能更改。

任何人都有可能導致問題的線索?

+0

哈維爾,你的「編輯」應該是「答案」,而不是:)你被允許在這裏回答你自己的問題在計算器上! –

+0

我不知道!謝謝 –

+0

不用擔心!您也可以將您的答案標記爲已接受。歡迎來到SO。 –

回答

相關問題