Save Excel Workbook to AWS S3 With Python

Tip: AWS uses /tmp as the storage!


Published on: April 19, 2020

Save File to S3 Using Python

For my work project, one of the requirements is to generate an Excel workbook after posting JSON data with openpyxl. The file would be downloadable but first it needed to be saved to an S3 bucket. Here is how I resolved that.

# necessary imports
import boto3
from openpyxl import Workbook
from tempfile import NamedTemporaryFile

# Using an Excel workbook file extension
wb = Workbook()

... Build out workbook with openpyxl
s3_resource = boto3.resource('s3')
dest_filename = "my-file.xslx"

with NamedTemporaryFile() as tmp:
    filename = '/tmp/{}'.format(dest_filename)
    wb.save(filename)
    s3_resource.Bucket(bucket_name).upload_file(Filename=filename, Key=dest_filename)
    # create downloadable URL (see other tutorial)
    # https://danh-was-here.netlify.app/download-aws-s3-files
    url = create_presigned_url(bucket_name, dest_filename)
    return {
        'downloadurl': url
    }

Source