pythonexcelopenpyxlhttpresponseazure-http-trigger

Python and http trigger not returning a workbook after converting to base64 or saving to temp folder


We are trying to return a workbook of openpyxl using func.httpResponse of an azure http trigger. Before that we need to convert it into Bytes or byteArray.

the file is of type openpyxl.workbook.workbook.Workbook().

The best way is using tempfile.NamedTemporaryFile. While looking into documentations, we've done the following:

tempFilePath = tempfile.gettempdir()
fp = tempfile.NamedTemporaryFile()
customizedFile.save(fp)
filesDirListInTemp = listdir(tempFilePath)

Where our workbook is customizedFile.

We weren't able to retrieve the file and its path in order to use the path to upload into a blob storage.

We tried this:

with NamedTemporaryFile(mode='w') as tmp:
    customizedFile.save(tmp.name)
    output = io.BytesIO(tmp)
    return func.HttpResponse(output, status_code=200)

However, we got the following error:

expected str, bytes or os.PathLike object, not Workbook

we tried several option like converting to base64 but it didn't work as the error was that the script expecting bytes or byteArray not workbook:

file_stream = io.BytesIO()
file =open(customizedFile, 'rb')
file.save(file_stream)
file_stream.seek(0)
base64_data = base64.b64encode(file_stream.getvalue()).decode('utf-8')

the error:

expected str, bytes or os.PathLike object, not Workbook

how to upload the workbook into temporary folder within the directory of the trigger to convert it into bytes and return it with the http response?


Solution

  • I found out the solution as follows:

    wb = workbook.Workbook()
    wb = customizedFile
    virtual_workbook = io.BytesIO()
    wb.save(virtual_workbook)
    logging.warn('Workbook saved to virtual_workbook.')
    return func.HttpResponse (
        virtual_workbook.getvalue(),
        mimetype='application/octet-stream',
        headers={
        'Content-Disposition': 'attachment;filename=' + customizedFileName}
    )