Search code examples
azureazure-functionsazureportalazure-http-trigger

Excel file generated through azure function seems corrupted


Iam able to generate an excel using python pandas using:

    df = pd.DataFrame(columns =["test"])
    writer = pd.ExcelWriter(f'{basepath}/Summary.xlsx', engine='xlsxwriter')
    df.to_excel(writer,engine='openpyxl',sheet_name= 'Sample')
    writer.save()

But when i try to trigger it using an azure function with HTTP trigger the downloaded excel says: enter image description here

Below is the code I have been using:

    df = pd.DataFrame(columns =["test"])
    writer = pd.ExcelWriter(f'{basepath}/Summary.xlsx', engine='xlsxwriter')
    df.to_excel(writer,engine='openpyxl',sheet_name= 'Sample')
    writer.save()
    response = func.HttpResponse(body=None,headers={'Content-Disposition':'attachment; filename='f'{basepath}/Summary.xlsx'}, mimetype='application/vnd.ms-excel')
    return response

Solution

  • Please try to use the following code:

        df = pd.DataFrame(columns =["test"])
        writer = pd.ExcelWriter(f'{basepath}/Summary.xlsx', engine='xlsxwriter')
        df.to_excel(writer,engine='openpyxl',sheet_name= 'Sample')
        writer.save()
    
        with open(f'{basepath}/Summary.xlsx', "rb") as file:
            return func.HttpResponse(body=file.read(),headers={'Content-Disposition':'attachment; filename='f'{basepath}/Summary.xlsx'}, mimetype='application/vnd.ms-excel')