Articles in this section
Category / Section

How to export ASP.NET MVC Grid to CSV?

1 min read

To export the ASP.NET MVC Grid as a CSV file, create excel file as IWorkBook with the required properties using GridExcelExport class and export overload. Later, the created book has been downloaded as CSV document.

<div id="Grid"></div>
    <script type="text/javascript">
        $(function () {
            $("#Grid").ejGrid({
                dataSource: new ej.DataManager({
                    json: window.gridData
                }),
                allowPaging: true,
                toolbarSettings: {
                    showToolbar: true,
                    toolbarItems: ["excelExport"]
                },
                exportToExcelAction: "ExportToExcel",
                columns: [
                        { field: "OrderID", headerText: "Order ID", textAlign: ej.TextAlign.Right },
                        {
                            field: "EmployeeID", headerText: "Employee ID", textAlign: ej.TextAlign.Right
                        },
                        { field: "Freight", format: "{0:C}", textAlign: ej.TextAlign.Right },
                        { field: "CustomerID", headerText: "Customer ID" },
                        { field: "ShipCity", headerText: "Ship City" }
                ]
            });
        });
</script>

 

Razor:

@using Syncfusion.JavaScript.Models
 
 
@(Html.EJ().Grid<OrdersView>("Grid")
    .AllowPaging()
    .Datasource(ds =>
    {
        ds.Json((IEnumerable<object>)ViewBag.datasource);
    })
    .ToolbarSettings(toolBar => toolBar
        .ShowToolbar()
        .ToolbarItems(items =>
            {
                items.AddTool(ToolBarItems.ExcelExport);
            }))
    .Columns(col =>
    {
        col.Field("OrderID").HeaderText("Order ID")
            .TextAlign(TextAlign.Right).Add();
        col.Field("EmployeeID").HeaderText("EmployeeID")
            .TextAlign(TextAlign.Right).Add();
        col.Field("Freight").HeaderText("Freight")
            .TextAlign(TextAlign.Right)
            .Format("{0:C}").Add();
        col.Field("CustomerID").HeaderText("Customer ID").Add();
        col.Field("ShipCity").HeaderText("Ship City").Add();
    })
)

 

 

 
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.datasource = OrderRepository.GetAllRecords().ToList();
            return View();
        }
        public void ExportToExcel(string GridModel)
        {
            ExcelExport exp = new ExcelExport();
            var DataSource = OrderRepository.GetAllRecords().ToList();
            GridProperties gridObj = (GridProperties)Syncfusion.JavaScript.Utils.DeserializeToModel(typeof(GridProperties), GridModel);
            GridExcelExport exExport = new GridExcelExport();
            IWorkbook book = exp.Export(gridObj, DataSource, true, exExport);
            book.SaveAs("Export.csv", ",", System.Web.HttpContext.Current.Response, ExcelDownloadType.Open, ExcelHttpContentType.CSV); 
        } 
   }

Webforms:

    <ej:Grid ID="Grid" runat="server" AllowPaging="true" OnServerExcelExporting="Grid_ServerExcelExporting" >
        <ToolbarSettings ShowToolbar="true" ToolbarItems="excelExport"></ToolbarSettings>
        <Columns>
            <ej:Column Field="OrderID" TextAlign ="Right" HeaderText="Order ID" />
            <ej:Column Field="EmployeeID" HeaderText="Employee ID" TextAlign ="Right" />
            <ej:Column Field="Freight" HeaderText="Freight"  />
            <ej:Column Field="CustomerID" HeaderText="Customer ID" />
            <ej:Column Field="ShipCity" HeaderText="ShipCity" />
        </Columns>
    </ej:Grid>

 

namespace sqlbinding
{
    public partial class _Default : Page
    {
        public static List<Orders> order = new List<Orders>();
        protected void Page_Load(object sender, EventArgs e)
        {
            Grid.DataSource = order;
            Grid.DataBind();
        }
        protected void Grid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e)
        {
            ExcelExport exp = new ExcelExport();
            var DataSource = order;
            GridExcelExport exExport = new GridExcelExport();
            IWorkbook book = exp.Export(Grid.Model, DataSource, true, exExport);
            book.SaveAs("Export.csv", ",", System.Web.HttpContext.Current.Response, ExcelDownloadType.Open, ExcelHttpContentType.CSV);
        }    }
}

 

Figure: Grid with Exported CSV file.



Conclusion

I hope you enjoyed learning how to create row template in DataGrid.

You can refer to ASP.NET MVC Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!


Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied