javascriptvue.js

Corrupted Excel File on download Excel file feature in vue js


I'm currently developing a feature that enables users to download an Excel file through an endpoint. However, when I implemented it, the downloaded Excel file appears corrupted. Interestingly, when I used the same cURL command in Postman, the file downloaded perfectly and rendered without any issues.

I've included my code below:

async downloadExcel() {
    try {
        const response = await InteractionService.getDiscussionExport({key: '5', exportType: 'Excel'});

        console.log('response', response);

        // Create Blob from Excel file data
        const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });

        // Create URL and trigger download
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'csr-discussion.xlsx');
        document.body.appendChild(link);
        link.click();

        // Clean up
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
    } catch (error) {
        console.error('Error downloading Excel file:', error);
    }
}
    public static async getDiscussionExport({
key,
afterId,
hideCsrData = true,
exportType = 'Word',
}: {
key: string,

afterId?: number,

hidexyzData?: boolean,

exportType?: 'Word' | 'Excel',
}): Promise<any> {
        const result = await __request({
            method: 'GET',
            path: `xxxx`,
            query: {
                'afterId': afterId,
                'hidexyzData': hidexyzData,
                'exportType': exportType,
            },
            errors: {
                403: `Error: Forbidden`,
                422: `Error: Unprocessable Entity`,
            }

        });
        return result.body;
    }

I've created a method to generate the Blob file, which is used to download the XLSX file. The expectation is that the downloaded file should open properly in Excel, just as it did when downloaded via Postman using the same cURL command and response


Solution

  • Diagnosed the forked package of typescript-Codegen and found that there was no code to handle ArrayBuffer responses, which was causing the issue