Reputation: 19
I am working for a company that is looking to automate reports with python, these reports are built using excel.
I'm currently using an HTTP Azure Function to host the api, and the main function looks like this.
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
response = req.get_json()
statement = #sql statement using payload data from post request
df = rpt.sql_table_to_df(statement)
frame = df.to_csv()
filebytes= bytes(frame, 'utf-8')
headers = {
"Content-Disposition": "attachment; filename='report.csv'"
}
return func.HttpResponse(body=filebytes, status_code=200, headers=headers,
mimetype='application/octet-stream')
The data that is sent to the api is JSON.
How can I think about returning an excel file from a post request?
Upvotes: 0
Views: 1126
Reputation: 43
Looks like you already have the csv string. In that case you can use pandas to export it as a excel file.
import pandas as pd
def main(req: func.HttpRequest) -> func.HttpResponse:
csvString = "a,b,c,d,e,f,g\na,b,c,d,e,f,g"
# read csv string into a file like object
csvStringIO = io.StringIO(csvString)
# read csv into pandas dataframe
df = pd.read_csv(csvStringIO, sep=",", header=None)
# write to excel bytes
output = io.BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
output.seek(0)
headers = {
"Content-Disposition": "attachment; filename='myfile.xlsx'"
}
return func.HttpResponse(body=output.read(), status_code=200, headers=headers,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
Upvotes: 1