Search code examples
pythonjsonpython-3.xxlsxxlsxwriter

How to generate xls file content without creating a file?


I am working on the Django REST server which does some calculations. I store these calculations as JSON and I want to create an endpoint that will generate a .xlsx file based on these JSON results and upload it to AWS S3 just like this:

s3.meta.client.put_object(
    Bucket = credentials['AWS_BUCKET_NAME'],
    Key=file_path,
    Body=file_content,
)

But there is the problem - every lib I checked for generating .xlsx content is creating a file, which I don't want to. Any solutions?

I understand that I can generate the file (with "xlsxwriter" for example), pull out the content, and delete it, but this way seems not quite the best:D

Any guidance would be greatly appreciated. Thank you


Solution

  • As Tim Roberts said in the comments, i used io.BytesIO object with xlsxwriter library, because it has 'in_memory' option on Workbook object initialization.

    output = BytesIO()
    workbook = xlsxwriter.Workbook(output, {"in_memory":True})
    
    # After all manipulations with workbook
    workbook.close()
    output.seek(0)
    
    # Uploading to AWS S3 using "boto3"
    s3.meta.client.put_object(
        Bucket=bucket_name,
        Key=file_path,
        Body=output,
    )