简体   繁体   English

使用请求发布通过 openpyxl 修改的 excel 工作簿

[英]Posting an excel workbook modified through openpyxl using request

I have an excel sheet that I wrote on memory and that I want to modify using openpyxl.我有一个写在内存上的 excel 表,我想使用 openpyxl 进行修改。 Due to several circumstances I cannot use temporary files or anything of the sort.由于几种情况,我不能使用临时文件或任何类似的东西。 I am also writing the original sheet not using openpyxl, but xlsxwriter, for reasons that I do not wish to elaborate upon.由于我不想详细说明的原因,我也在编写原始工作表,而不是使用 openpyxl,而是使用 xlsxwriter。 The original sheet is saved in a bytes-like format, however, so I am wondering if I can do the same with the modified excel sheet and then upload it using requests.但是,原始工作表以类似字节的格式保存,所以我想知道是否可以对修改后的 Excel 工作表执行相同操作,然后使用请求上传它。

This is the code I am using:这是我正在使用的代码:

def UploadXLS(name, xlsx):
   wb = opx.load_workbook(io.BytesIO(xlsx))     
   wb.security = WorkbookProtection(workbookPassword = 'super-secret-password', lockStructure = True)
   wb.save(name)

   r = requests.post('my-url-here', 
                      files = wb)
return r.url

And this is the (predictable) error message I am getting:这是我收到的(可预测的)错误消息:

a bytes-like object is required, not 'Workbook'

Any help or advice on the topic would be much appreciated.任何有关该主题的帮助或建议将不胜感激。

The problem here is that you are attempting to pass the openpyxl Workbook object to the post() request.这里的问题是您试图将 openpyxl Workbook对象传递给post()请求。 However, post() does not know how to handle a Workbook .但是, post()不知道如何处理Workbook But it does know how to handle any generic file stream.但它确实知道如何处理任何通用文件流。 So the solution is to open the file and pass the stream to the request:所以解决办法是打开文件,将流传递给请求:

file = open(name, 'r')
r = requests.post('url', files=file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM