简体   繁体   中英

New Excel file with OfficeOpenXml in ASP.Net MVC : nothing is returned

Context

I create an Excel file with OfficeOpenXml , but nothing is returned to browser.

Any idea why ?

Code

[C#] :

public ActionResult ExportToExcel(string[] mails)
{
    using (var ep = new ExcelPackage())
    {
        var ws = ep.Workbook.Worksheets.Add("Contacts");

        for (var i = 0; i < mails.Length; i++)
        {
            ws.Cells[i + 1, 1].Value = mails[i];
        }

        Byte[] bytes = ep.GetAsByteArray();

        return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "Contacts.xls" };
    }
}

[JavaScript] :

$('#contacts-excel-btn').click(function () {
    var mails = [],
        uniqueMails = [];

    $('.email-td').each(function () {
        var txt = $(this).text();
        if (txt) {
            mails.push(txt);
        }
    });

    $.each(mails, function (i, el) {
        if ($.inArray(el, uniqueMails) === -1) {
            uniqueMails.push(el);
        }
    });

    if (uniqueMails[0]) {
        $.ajax({
            type: 'POST',
            url: '/Contact/ExportToExcel',
            dataType: 'json',
            traditional: true,
            data: { mails: uniqueMails }
        });
    }
});

Ok I solved my issue.

According to this article , I replaced my return with:

var butes = ep.GetAsByteArray();
var fileName = "Contacts.xlsx";

return base.File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);

And according to this article , I replaced my ajax approach by a html form approach:

[JS] :

$.each(uniqueMails, function (i, el) {
    $('#contacts-excel-form').append('<input type="hidden" name="mails[' + i + ']" value="' + el + '" />');
});

$('#contacts-excel-form').submit();

[C#] :

var mails = Request.Form.AllKeys;

for (var i = 0; i < mails.Length; i++)
{
    ws.Cells[i + 1, 1].Value = Request.Form[mails[i]];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM