Convert Html Table to Excel

2019-09-05 10:09发布

问题:

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

and the follwing function in jQuery:

 function btnConvertToExcelClick() {

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


                         }


        });
        return false;
    }

I guess what im trying to ask is how to pass the whole HTML table to the JsonResult function as a Control. Help!

回答1:

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

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.

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/

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");
    }

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");
    }

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>