【问题标题】:openpyxl - TypeError: a bytes-like object is required, not '_io.BytesIO'openpyxl - TypeError:需要一个类似字节的对象,而不是'_io.BytesIO'
【发布时间】:2020-06-06 23:45:58
【问题描述】:

使用openpyxl我在一个二元对象中编写和excel文件但是当我尝试通过“write”方法保存它时,我得到了这个异常:

Traceback(最近一次调用最后一次):文件“stack.py”,第 13 行,在 file.write(output) TypeError: a bytes-like object is required, not '_io.BytesIO'

我该如何解决这个问题?下面是一个简单的例子:

import openpyxl
from io import BytesIO

wb = openpyxl.Workbook()
ws = wb.active
ws.title = "TEST"
output = BytesIO() 

wb.save(output)


file = open("ciao.xlsx", "wb")
file.write(output) # <--- this instruction doesn't work..

file.close()

注意:我已经知道可以直接用openpyxl保存excel文件,但是在我的真实代码中,我需要将它保存在二进制文件中。

【问题讨论】:

    标签: python openpyxl


    【解决方案1】:

    您可以使用 getvalue 函数从 BytesIO 输出中获取类似字节的对象。

    file.write(output.getvalue())

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多