Convert Html Table to Excel

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.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);
            return Json(1);

and the follwing function in jQuery:

 function btnConvertToExcelClick() {

        var inputParamtrs={ ????????? }
                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!


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.

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>

Need Your Help

Vertical swipe simulated mouse events sent to wrong control in Windows Forms app on Windows 10 tablet

c# winforms scroll touch windows-10

I'm trying to run a Windows Forms app on a Windows 10 tablet (Dell Venue 8 Pro). In general, Windows translates touch events into the obvious mouse event counterparts. However, it's doing something