html table to excel 然后打印,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.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.

Your Text

来源:https://stackoverflow.com/questions/11050815/convert-html-table-to-excel

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值