0

在此处输入图像描述

我正在我的 MVC 项目中执行导出到 csv 功能。目前,如果我在每个页面上编写代码,它就可以正常工作。但我想避免重复执行集中导出功能的代码。

这是我的控制器代码

public ActionResult Export(string filterBy)
        {
            GridState gs = new GridState();
            gs.Filter = filterBy;
            gs.Page = 1;
            gs.Size = int.MaxValue;
            IEnumerable cities = City.GetAll().AsEnumerable().AsQueryable().ToGridModel(gs).Data;
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
            writer.Write("Country Name,");
            writer.Write("State Name,");
            writer.Write("City Name,");
            writer.Write("City STD Code,");
            writer.Write("Is Display");
            writer.WriteLine();
            foreach (CityViewModel city in cities)
            {
                writer.Write(city.CountryName);
                writer.Write(",");
                writer.Write("\"");
                writer.Write(city.StateName);
                writer.Write("\"");
                writer.Write(",");
                writer.Write("\"");
                writer.Write(city.City.Name);
                writer.Write("\"");
                writer.Write(",");
                writer.Write(city.City.STDCode);
                writer.Write("\"");
                writer.Write(",");
                writer.Write(city.City.IsDisplay);
                writer.WriteLine();
            }
            writer.Flush();
            output.Position = 0;

            return File(output, "text/comma-separated-values", "city.csv");

        }

这是我的观点:

@model Telerik.Web.Mvc.GridModel<QuexstERP.BusinessCore.BusinessEntities.SysAdmin.CityViewModel>
@using Telerik.Web.Mvc.UI
@{
    ViewBag.Title = "City List";
}

@(Html.Telerik().Grid(Model.Data)
        .Name("Grid")
        .DataKeys(keys => keys.Add(c => c.City.Id))
            .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.Image).ImageHtmlAttributes(new { style = "margin-left:0", title = "Add" }))
                                .ToolBar(commands => commands
                .Custom()
                .HtmlAttributes(new { id = "TestFilter", onclick = "command_onClick(this)" })
                .Text("Export to csv")
                                        .Action("Export", "City", new { filterBy = "~" }))
            .DataBinding(dataBinding =>
                dataBinding.Server()
                    .Select("Select", "City", new { GridButtonType.Text })
                            .Insert("Create", "City", new { GridButtonType.Text })
                        .Update("Save", "City", new { GridButtonType.Text })
                        .Delete("Delete", "City", new { GridButtonType.Text }))
            .Columns(columns =>
            {
                columns.Command(commands =>
                {
                    commands.Custom("Edit").Action("Edit", "City").ImageHtmlAttributes(new { @class = "t-edit" }).ButtonType(GridButtonType.Image).HtmlAttributes(new { title = "Edit", @class = "RightAlign" });
                }).Width(40).Title("Edit").Visible(OperationHelper.EditOperation);

                columns.Command(commands =>
                {
                    commands.Delete().ButtonType(GridButtonType.Image).HtmlAttributes(new { title = "Delete", @class = "RightAlign" });
                }).Width(40).Title("Delete").Visible(OperationHelper.DeleteOperation);

                columns.Bound(p => p.CountryName).Width(200).Title("Country");
                columns.Bound(p => p.StateName).Width(200).Title("State");
                columns.Bound(p => p.City.Name).Width(310).Title("City");
                columns.Bound(p => p.City.STDCode).Width(200).Title("STD Code");
                columns.Bound(p => p.City.IsDisplay).Width(110).Title("IsDisplay");
            })
            .Pageable()
                .Scrollable()
            .Sortable()
                .Filterable()
                    .Resizable(command => command.Columns(true))
    )
@section HeadContent {

    <script type="text/javascript">
        function command_onClick(e) {

            var grid = $('#Grid').data('tGrid');

            var $cmd = $('#TestFilter');

            // Get its 'href' attribute - the URL where it would navigate to
            var href = $cmd.attr('href');

            // Update the 'filter' parameter with the grids' current filtering state
            href = href.replace(/filterBy=(.*)/, 'filterBy=' + (grid.filterBy || '~'));

            // Update the 'order' parameter with the grids' current ordering state
            href = href.replace(/orderBy=([^&]*)/, 'orderBy=' + (grid.orderBy || '~'));

            // Update the 'page' parameter with the grids' current page
            href = href.replace(/page=([^&]*)/, 'page=' + grid.currentPage);

            // Update the 'href' attribute
            $cmd.attr('href', href);
        }

    </script>
}

我想集中导出到 CSV。我的项目中的许多表格(例如州、国家和国家/地区)都具有导出功能。是否可以编写一个泛型类并将参数传递给它。导出到 csv 是集中完成的???

4

2 回答 2

1

我们通过在控制器方法中将数据源绑定到 GridView 来实现类似的效果,例如

var data = GetSomeData();
var grid = new GridView { DataSource = data };
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcel.xls");

Response.ContentType = "application/vnd.ms-excel";
var sw = new StringWriter();
var htw = new HtmlTextWriter(sw);

grid.RenderControl(htw);

Response.Write(sw.ToString());
Response.End();

这样,您只需在 GridView 上设置相关数据源,并在输出流中返回网格数据的转储。通过一些重构,我们能够使其通用,现在我们所有的 UI 网格都使用它来导出到 Excel/CSV。

于 2013-04-22T08:39:19.217 回答
0

仅供参考。不要将数据绑定到网格,然后将其导出到 Excel。它会给你

您尝试打开的文件与文件扩展名指定的格式不同

尝试打开 Excel 时出错。

我已经为上述问题做了这个解决方案

public static void ExportToExcel(IEnumerable<dynamic> data, string sheetName)
{
    XLWorkbook wb = new XLWorkbook();
    var ws = wb.Worksheets.Add(sheetName);
    ws.Cell(2, 1).InsertTable(data);
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx",sheetName.Replace(" ","_")));

    using (MemoryStream memoryStream = new MemoryStream())
    {
        wb.SaveAs(memoryStream);
        memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
        memoryStream.Close();
    }

    HttpContext.Current.Response.End();
}

它动态地获取数据。使用ClosedXml所以没有错误,并且导出到 Excel 功能是应用程序的核心希望这会对某人有所帮助。:)

于 2013-04-29T05:43:29.273 回答