如何在.net core 2.0中通过Ajax下载excel(.xlsx)

时间:2018-06-21 19:21:28

标签: javascript c# excel epplus

我正在尝试下载具有大数据集的Excel文件。在服务器端,我使用EPPlus库生成Excel。然后,我将流obj传递给客户端。客户端代码使用该流obj下载excel文件。
打开下载的文件时,出现错误文件错误消息。我要去哪里错了?

  

服务器端代码(C#)

public async Task<IActionResult> DownloadExcel(Model postData)
{
    string apiUrl = "Api/URL/Get";
    apiUrl += "?Status=" + postData.Status +
              "&Gender=" + postData.Gender +
              "&CurrentAge=" + postData.CurrentAge;

    var result = await CallAPI.GetListFromApiAsync<ResultModel>(apiUrl);

    var stream = new MemoryStream();
    using (ExcelPackage excel = new ExcelPackage(stream))
    {
        var workSheet = excel.Workbook.Worksheets.Add("Sheet1");

        //  Column
        workSheet.Cells[1, 1].Value = "Column 1";
        workSheet.Cells[1, 2].Value = "Column 2";
        .
        .
        .
        workSheet.Cells[1, 19].Value = "Column 19";

        // Row
        int recordIndex = 2;
        foreach (var d in result)
        {
            workSheet.Cells[recordIndex, 1].Value = d.data1;
            workSheet.Cells[recordIndex, 2].Value = d.data2;
            .
            .
            .
            workSheet.Cells[recordIndex, 19].Value = d.data4;
            recordIndex++;
        }
        for (int i = 1; i < 20; i++)
        {
            workSheet.Column(i).AutoFit();
        }

        string fileName = @"download.xlsx";
        string fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        stream.Position = 0;
        return File(stream, fileType, fileName);
    }
}
  

客户端Ajax调用

$.ajax({
    url: "/SomeURL/DownloadExcel",
    type: "POST",
    data: form.serialize(),
    success: function (result) {
        var binaryData = [];
        binaryData.push(result);
        var blob = new Blob([binaryData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'download.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
});

0 个答案:

没有答案