0

我想将 HTML 表导出到 MVC 中的 excel 中。我的控制器中有以下代码:

  public JsonResult ExportToExcel(Control ctl)
        {

            Response.Clear();
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("content-disposition", "attachment;filename=ExcelCopy.xls");
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            ctl.RenderControl(hw);
            Response.Write(sw.ToString());
            Response.End();
            return Json(1);
        }

以及 jQuery 中的以下函数:

 function btnConvertToExcelClick() {

        var inputParamtrs={ ????????? }
         $.ajax({
                type: "POST",
                url: "/Expenses/ExportToExcel",
                data: inputParamtrs,
                success: function (json) {


                         }


        });
        return false;
    }

我想我想问的是如何将整个 HTML 表作为 Control传递给 JsonResult 函数。帮助!

4

1 回答 1

0

Json 不是 Excel 支持的格式,因此您使用了错误的 ActionResult。

而是尝试将您的 excel 文件创建为 HTML 表格或 CSV 文件。我建议导出 CSV 文件,因为它可能是最容易构建的。

此外,您可以使用 excel 库来构建 Excel 文件。这里有一对。 http://e-infotainment.com/applications/csharp-excel-library/ http://code.google.com/p/excellibrary/

构建 CSV 后,您可以将 CSV 与 ContentResult(而不是 json)一起返回。

    public ActionResult MakeExcelCSV()
    {
        string excelCSV = null;
        // consruct your CSV
        return Content(excelCSV, "application/ms-excel");
    }

或者,如果您使用库制作了一个 excel 文件,您可以使用 FileResult(而不是 json)返回它

    public ActionResult MakeExcelFile()
    {
        Stream excelStream = null;
        // consruct your excel file
        return File(excelStream, "application/ms-excel", "myexcel.xlsx");
    }

无论哪种情况,您都不需要 ajax 调用来加载内容,只需链接到它并在新窗口中打开它。

<a href="/Controller/MakeExcelFile" target="ExcelFile"> Your Text </a>
于 2012-06-15T13:44:36.143 回答