转换HTML表格到Excel [英] Convert Html Table to Excel

查看:140
本文介绍了转换HTML表格到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要导出HTML表格MVC中创先争优。
我有以下的code在我的控制器:

i want to export an HTML table to excel in MVC. I have the following code in my controller:

  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中的follwing功能:

and the follwing function in jQuery:

 function btnConvertToExcelClick() {

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


                         }


        });
        return false;
    }

我猜我尝试问的是如何将整个HTML表格传递给JsonResult功能的作为控制。救命啊!

推荐答案

JSON是不是就是用Excel支持的格式,所以你使用了错误的ActionResult。

Json is not a format that is supported by Excel, so you're using the wrong ActionResult.

相反,尝试创建您的Excel文件作为HTML表格或CSV文件。我建议导出CSV文件,因为它可能是最简单的构建。

Instead try creating your excel file as an HTML table or a CSV file. I recommend exporting a CSV file as it's probably the easiest to construct.

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

Further, you can use an excel library to construct an Excel file. Here are a couple. http://e-infotainment.com/applications/csharp-excel-library/ http://code.google.com/p/excellibrary/

您已经构建了您的CSV后,您可以返回CSV作为与ContentResult类型(而不是JSON)。

After you've constructed your CSV you can return the CSV as with a ContentResult (instead of json.)

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

或者你,如果你做一个excel的库文件,你可以用FileResult(而不是JSON)

Or you if you made an excel file with the library you can return it with a FileResult (instead of json)

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

在这两种情况下,你不会需要一个Ajax调用加载的内容,只是链接到它,并在新窗口中打开它。

In either case, you won't need an ajax call to load the content, just link to it and open it in a new window.

<a href="/Controller/MakeExcelFile" target="ExcelFile"> Your Text </a>

这篇关于转换HTML表格到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆