【问题标题】:Export html table to excel in asp.net MVC2在asp.net MVC2中将html表导出到excel
【发布时间】:2012-12-27 09:24:30
【问题描述】:

您好,我正在寻找如何在 ASP.NET MVC 中导出到 excel 的最佳方法

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

Export to Excel or CSV from ASP.NET MVC with 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。

现在我需要做的是获取我的 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 client 等等,..

它是如何在 MVC 上完成的?我已经在寻找一些类似的主题,但它总是让我进入我的第一个工作示例。

在此致谢

【问题讨论】:

  • 对于这种类型的错误,我们通常在控制器上使用 validateRequest="false" attr...试试看..

标签: c# jquery ajax asp.net-mvc-2 export-to-excel


【解决方案1】:

最简单的解决方案是将 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");
    }
}

现在在对应的视图里面我们假设我们已经生成了一些&lt;table&gt;(这个表的生成方式在这里真的没什么意思):

@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 plugin 将 HTML 表格转换为 CSV 格式。然后,生成的 CSV 将在表单提交到服务器之前存储在隐藏字段中。

如果您想构建原生 XLSX 文件,您必须在服务器上使用 OpenXML SDK。您不能只获取 HTML 表格并将其转换为原生 Excel 文件。此解决方案将更难付诸实践,因为您只需将数据发送到服务器,但它可以让您对生成的 Excel 文件进行更大程度的自定义。

【讨论】:

  • 嗨 @Darin Dimitrov 我正在使用 mvc2 AllowHtml 仅适用于 mvc3 及以上版本.. :)
  • 好吧,然后用[ValidateInput(false)] 属性装饰Export 控制器动作。
  • 感谢它有效,但显示不正确。 Id Name"1 Foo"2 条只有一行
猜你喜欢
  • 2012-03-10
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 2015-08-05
相关资源
最近更新 更多