导出HTML表在asp.net MVC2练成练成、asp、HTML、net

2023-09-10 13:50:36 作者:年轻卜是罪%

嗨正在寻找最好的方式如何导出到Excel做的ASP.NET MVC

Hi am looking for the best way on how export to excel does in ASP.NET MVC

现在我得到这个从billsternberger.net

Now i got this one from billsternberger.net

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

        //Export to excel
        public ActionResult Download()
        {

            List<Lookup> 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工作。

which is working from binding to datagrid and export to excel.

现在我需要做的就是在我的HTML表格并将其导出到excel我曾经jQuery的数据表的操作表中的数据,因此将更多重量轻,因为它是在客户端完成。

Now what i need to do is get the my html table and export it to excel where i used jquery datatable on manipulating table data so it will be more light weight because it is done on client side.

我尝试使用jQuery和AJAX在这里我把我的HTML表格到我的单位在我的控制器

I tried using jquery and ajax where i pass my html table to my entities on my controller

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

};

但它引发了我有潜在危险的Request.Form值从客户端检测到等。

它是如何做的MVC?我已经找一些类似的主题,但它总是给我给我的第一工作示例。

How is it done on MVC? I already look for some similar topic but it always drop me to my first working sample.

感谢的问候

推荐答案

最简单的解决办法是将HTML表格导出为CSV文件,发送到服务器。让我们来举个例子。假设我们已经定义视图模型:

The easiest solution would be to export the HTML table as CSV file and send to the server. Let's take an example. Suppose that we have defined a view model:

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

现在相应的视图中,我们假设我们已经产生了一些&LT;表&gt; (生成此表的方式实在是没有兴趣在这里):

Now inside the corresponding view we suppose that we have generated some <table> (the way this table is generated is really not interesting here):

@model ExportViewModel

<table id="myTable">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Foo</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Bar</td>
        </tr>
    </tbody>
</table>

@using (Html.BeginForm("Export", null, FormMethod.Post, new { id = "export" }))
{
    @Html.HiddenFor(x => x.Csv)
    <button type="submit">Export to Excel</button>
}

<script type="text/javascript" src="http://www.kunalbabre.com/projects/table2CSV.js"></script>
<script type="text/javascript">
    $('#export').submit(function () {
        $('#Csv').val($('#myTable').table2CSV({ delivery: 'value' }));
    });
</script>

我们使用的是 table2CSV jQuery插件 以HTML表格转换为CSV格式。由此产生的CSV将被存储在一个隐藏字段之前的形式提交到服务器中。

We are using the table2CSV jQuery plugin to convert the HTML table into a CSV format. The resulting CSV will then be stored inside a hidden field just before the form is submitted to the server.

如果你想建立当地XLSX文件,你将不得不使用 OpenXML的SDK 的服务器上。你不能只取一个HTML表格,并把它变成一个本地Excel文件。该解决方案将更加难以付诸实践,你将不得不只将数据发送到服务器,但它可以让你更大的定制在生成的Excel文件。

If you want to build native XLSX files you will have to use the OpenXML SDK on the server. You cannot just take an HTML table and turn it into a native Excel file. This solution will be more difficult to put into practice as you will have to send only the data to the server but it will allow you far greater customization over the resulting Excel file.