Python 3 - xlwt保存工作簿错误

3

我正在使用Python 3.6编写一个小程序,它可以读取Excel文件并修改单元格的格式。我希望在同一个单元格内有多个格式,因此我使用了xlwtwrite_rich_text

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:必须是str,而不是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 bytesPython code, not able to write into xls。 后来我发现,这个问题可能与 Python 3 和 Python 2 处理字符串的方式有关,而我可能会得到一个导致错误的字节字符串。 我查看了 text_cell 的类型,发现它是 str。我尝试省略 seg1seg2 中的字体,但仍然无法解决问题。最后,我在 Python 2.7 上运行了相同的脚本,并且运行成功。 坏消息是,我需要代码在 Python 3 中工作,因为这台服务器只能运行 Python 3,不能更改。 有人知道可能导致这个问题的原因吗?

Javier,你的“编辑”应该改成“回答” :) 在StackOverflow上,你可以回答自己的问题! - David Zemens
我不知道!谢谢。 - Javier Garcia de Leaniz
没问题!你也可以将你的答案标记为已接受。欢迎来到SO。 - David Zemens
2个回答

2

0
我在一年后遇到了同样的问题,使用faker中的(fake.address().split('\n'))[1].split(',') 作为我的输入时,看起来当您尝试将列表(在我的情况下是两个字符串的列表)输入单个单元格时,也会出现此错误。
尝试将它们分开,在我的情况下,以下内容应该有效:
temp =(fake.address().split('\n'))[1].split(',')
input = temp[0] + temp[1]
sheet.write(0, 0, input)

更加通用的做法是,如果你遇到了这种情况,请尝试将字符串连接起来。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接