Excel File Corrupted When Downloaded from Django Backend via Axios in Vue.js

I'm trying to download an Excel file from my Django backend to the frontend using Axios and FileSaver.js (also tried without this). The file is generated successfully on the backend, but when I download it through the frontend, the file becomes corrupted and cannot be opened by Excel.

I am using pandas to create the Excel file in-memory and then return it as a response.

Backend code -

buffer = BytesIO()
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
    for item in data_list:
        attributes = item['attributes']
        attributes['ID'] = item['id']
        df = pd.DataFrame([attributes])
        
        sheet_name = f"Sheet_{item['id']}"
        df.to_excel(writer, sheet_name=sheet_name, index=False)

buffer.seek(0)

response = HttpResponse(buffer, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="data_export.xlsx"'

return response

Frontend code -

async function downloadFile() {
  try {
    const response = await axios.get('/api/export-excel', {
      responseType: 'blob',
    });

    saveAs(new Blob([response.data]), 'data_export.xlsx');
  } catch (error) {
    console.error('Error downloading file:', error);
  }
}

I know there are similar questions already asked and I have already tried those things (using arraybuffer, type - ms-excel, also tried using openpyxl) but none seems to work.

What could be causing the file corruption during download via the frontend? How can I ensure that the file downloads correctly and opens in Excel without corruption?

Any advice or suggestions would be greatly appreciated!

Вернуться на верх