I have an excel sheet that I wrote on memory and that I want to modify using 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. 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.
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.
Advertisement
Answer
The problem here is that you are attempting to pass the openpyxl Workbook
object to the post()
request. However, post()
does not know how to handle a 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)