在asp.net MVC2中将html表导出为ex​​cel

您好我正在寻找有关如何在ASP.NET MVC中导出到Excel的最佳方式

现在我从billsternberger.net得到了这个

使用C#从ASP.NET MVC导出到Excel或CSV

//Export to excel public ActionResult Download() { List lookupList = data,GetLookupList(); var grid = new System.Web.UI.WebControls.GridView(); grid.DataSource = lookupList; grid.DataBind(); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=YourFileName.xlsx"); Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); return View(); } 

这是从绑定到datagrid并导出到excel。

现在我需要做的是获取我的html表并将其导出到excel,我在操作表数据时使用jquery数据表,因此它会更轻,因为它是在客户端完成的。

我尝试使用jquery和ajax,我将我的html表传递给我的控制器上的实体

 function Export() { var details = {}; details.LookupName = $("#tblLookup").html(); //Validate details var url_ = generateURL("/Home/Download"); //Call Save Controller and pass details entities $.ajax({ type: "POST", url: url_, data: details, //details will act as the Entities Model traditional: true, success: function(data) { }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("error: " + XMLHttpRequest.responseText); }, dataType: 'json' }); }; 

但它抛出了我A potentially dangerous Request.Form value was detected from the clientA potentially dangerous Request.Form value was detected from the client ,..

它是如何在MVC上完成的? 我已经找了一些类似的话题,但它总是让我看到我的第一个工作样本。

在此致谢谢

最简单的解决方案是将HTML表导出为CSV文件并发送到服务器。 我们来举个例子吧。 假设我们已经定义了一个视图模型:

 public class ExportViewModel { [AllowHtml] public string Csv { get; set; } } 

和一个控制器:

 public class HomeController : Controller { public ActionResult Index() { return View(new ExportViewModel()); } [HttpPost] public ActionResult Export(ExportViewModel model) { var cd = new ContentDisposition { FileName = "YourFileName.csv", Inline = false }; Response.AddHeader("Content-Disposition", cd.ToString()); return Content(model.Csv, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); } } 

现在在相应的视图中我们假设我们已经生成了一些

(这个表的生成方式在这里真的没什么意思):

 @model ExportViewModel 
Id Name
1 Foo
2 Bar
@using (Html.BeginForm("Export", null, FormMethod.Post, new { id = "export" })) { @Html.HiddenFor(x => x.Csv) }

我们使用table2CSV jQuery plugin将HTML表格转换为CSV格式。 然后,在将表单提交给服务器之前,生成的CSV将存储在隐藏字段中。

如果要构建本机XLSX文件,则必须在服务器上使用OpenXML SDK 。 您不能只使用HTML表并将其转换为本机Excel文件。 此解决方案将更难以实施,因为您只需将数据发送到服务器,但它将允许您对生成的Excel文件进​​行更大的自定义。