1

语境

我使用OfficeOpenXml创建了一个 Excel 文件,但浏览器没有返回任何内容。

知道为什么吗?

代码

[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 }
        });
    }
});
4

1 回答 1

1

好的,我解决了我的问题。

根据这篇文章,我将我的替换return为:

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

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

根据这篇文章,我用 html 表单方法替换了我的 ajax 方法:

[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]];
}
于 2012-12-05T10:33:20.830 回答