错误"请求的JSON解析失败"在下载excel文件

时间:2017-10-20 07:22:42

标签: c# json ajax excel

我有一个action方法,它返回一个excel文件。我正在使用ajax调用该action方法。我得到了Requested JSON parse failed

 $.ajax({
            url: importUrl,
            data: {
                X: "12",
                Y: "12",
                Z: "12"
            },
            success: function (data) {
                alert("S: "+data);
            },
            error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }
                console.log(msg);
            }
        });



public ActionResult ExportReportToExcel(string X, string Y, string Z)
        {
            if (HttpContext.Request.UrlReferrer == null)
                TempData["PDFPrevUrl"] = Url.RouteUrl("PageNotFound");
            else if (TempData["PDFPrevUrl"] == null)
                TempData["PDFPrevUrl"] = HttpContext.Request.UrlReferrer.PathAndQuery;

            var customer = _authenticationService.CurrentCustomer;
            if (customer == null)
                return new LmsHttpUnauthorizedResult();

            string filename = "Report";
            try
            {
                XLWorkbook wb = new XLWorkbook(Server.MapPath(@"~/Content/CumulativePerformanceReportTemplate.xlsx"));
                XElement userprogress = XElement.Load(Server.MapPath(@"~/Content/Export.xml")).Element("cumulativeperformancereport");
                int datarow = int.Parse(userprogress.Element("T").Attribute("row").Value.Trim());
                int datacol = int.Parse(userprogress.Element("T").Attribute("col").Value.Trim());
                IXLWorksheet WS = wb.Worksheet(1);
                WS.Cell(datarow, datacol).Value = customer.Name;
                datarow = int.Parse(userprogress.Element("X").Attribute("row").Value.Trim());
                datacol = int.Parse(userprogress.Element("X").Attribute("col").Value.Trim());
                WS.Cell(datarow, datacol).Value = X;
                datarow = int.Parse(userprogress.Element("Y").Attribute("row").Value.Trim());
                datacol = int.Parse(userprogress.Element("Y").Attribute("col").Value.Trim());
                WS.Cell(datarow, datacol).Value = Y;
                datarow = int.Parse(userprogress.Element("Z").Attribute("row").Value.Trim());
                datacol = int.Parse(userprogress.Element("Z").Attribute("col").Value.Trim());
                WS.Cell(datarow, datacol).Value = Z;
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=" + filename + "_Summary.xlsx");
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();

                }
                return null;
            }

            catch (Exception ex)
            {
                return Redirect(TempData["PDFPrevUrl"].ToString());
            }

        }

为什么我收到此错误?

3 个答案:

答案 0 :(得分:0)

为什么要使用Backend来创建excel文件&然后下载....它的矫枉过正&下载部分是难以理解的

在客户端使用像Javascript一样轻量级的东西...它将从XML和&amp ;;创建excel将使用download下载它  属性...

    var data_type = 'data:application/vnd.ms-excel';
    var table_div = document.getElementById('table_wrapper');
    var table_html = table_div.outerHTML.replace(/ /g, '%20');

Here is Solution

答案 1 :(得分:0)

发送文件时可能是服务器端错误。 您是否尝试将响应内容类型更改为 application / vnd.ms-excel

我向您展示了一个最小的工作示例

// Server side
public ActionResult GimmeFile()
{
    var bytes = System.IO.File.ReadAllBytes(@"path_to_your_file.xlsx");
    return File(bytes, "application/vnd.ms-excel", "Myfile.xls");
}

客户端使用Ajax调用

$.ajax({
    method: 'POST',
    url: '/Home/GimmeFile',
    success: function (data) {
        alert("S: " + data)
    },
    error: function (jqXHR, ex) {
        console.log(ex)
    }
})

无论如何,在ajax调用之后,我不知道你需要对excel文件做什么, 但如果您需要将其保存到本地,那么您应该使用HTML5 < a download>而不是

答案 2 :(得分:0)

&#34; 请求的JSON解析失败&#34;指示AJAX调用期望将JSON数据作为返回值获取,但控制器操作方法返回除JSON对象之外的其他数据类型。

通过查看控制器流程并省略一些不相关的代码,您将得到:

public ActionResult ExportReportToExcel(string X, string Y, string Z)
{
    // other stuff

    var customer = _authenticationService.CurrentCustomer;
    if (customer == null)
        return new LmsHttpUnauthorizedResult();

    try
    {   
        // other stuff

        return null; // this returns null value instead of expected JSON
    }

    catch (Exception ex)
    {
        return Redirect(TempData["PDFPrevUrl"].ToString());
    }

} 

默认情况下,jQuery会根据响应的MIME类型(xml,json,script或html,最近的默认值为JSON)来推断dataType参数。因此,您需要return a JSON object通过以下方法:

// ContentResult
return Content("message_text", "application/json");

// JsonResult
return Json("message_text", JsonRequestBehavior.AllowGet);

如果您想通过AJAX返回文件进行下载,可以使用window.locationwindow.location.href重定向:

$.ajax({
        url: importUrl, // this should be refer to JsonResult action
        data: {
            X: "12",
            Y: "12",
            Z: "12"
        },
        success: function (data) {
            // deal with data response here
            window.location = downloadUrl; // redirect to FileResult action
        },
        error: function (jqXHR, exception) {
            // other stuff
        }
}

// example controller to return Excel binary file
public FileResult DownloadFile(string fileName)
{
    // other stuff
    byte[] content = TempData["something"] as byte[];

    return File(content, "application/vnd.ms-excel", fileName);
}

注意:上面的解释大部分是微不足道的,您当前的实现可能与给定的示例不同。

类似问题:

Download Excel file via AJAX MVC

jQuery returning "parsererror" for ajax request