Using EPPlus to create an excel file

91 views Asked by At

I have an ASP.NET Framework web application and I am using an .asmx webservice to create an excel file.

I make an AJAX call to the .asmx file and it should create an .xls or .xlsx to download from the browser via the EPPlus package and a correctly instantiated DataTable object.

When I run the code the file is downloaded, but when I try to open it it says: the file is corrupted.

This is my code

.asmx code:

[WebMethod]
public void ExportToExcel()
{
    HttpContext context = HttpContext.Current;
    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

    // Creazione del file Excel in memoria
    using (ExcelPackage excelPackage = new ExcelPackage())
    {
        ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
        worksheet.Cells["A1"].LoadFromDataTable(dt, true);

        // Converte il pacchetto Excel in array di byte
        byte[] excelBytes = excelPackage.GetAsByteArray();

        // Invia il file Excel come risposta HTTP al client
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        context.Response.AddHeader("content-disposition", "attachment; filename=\"" + HttpUtility.UrlEncode("output.xlsx") + "\"");
        context.Response.BinaryWrite(excelBytes);
        context.Response.Flush();
        context.Response.End();
    }
}

.js code:

$(`#${tableId}BtnDownloadExcelTest`).on("click", function () {
    const bindExcelDownloadDataTable = $.ajax({
        type: "POST",
        url: "/WebServiceDataTable.asmx/ExportToExcel",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            // Ricevuto con successo la risposta dal servizio Web
            // response contiene il file Excel generato
            // Creare un URL oggetto Blob per il file Excel
            var blob = new Blob([response], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
            var url = window.URL.createObjectURL(blob);

            // Creare un link per il download del file Excel
            var a = document.createElement("a");
            a.href = url;
            a.download = "output.xlsx";
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        },
        error: function (xhr, textStatus, errorThrown) {
            // Gestisci l'errore della chiamata AJAX
            console.log("Errore nella chiamata AJAX:", errorThrown);
        }
    });
});
0

There are 0 answers