Articles in this section
Category / Section

How should Group caption Format be handled when exporting in ASP.NET WebForms Grid?

1 min read

This Knowledge Base showcase the example to handle Group caption format while exporting the grid when GroupCaptionFormat is set in Localization

Solution:

If we set GroupCaptionFormat through localization, then while exporting we need to handle the Group Caption Format in server side using corresponding server event.

Step 1: Render the grid control.

HTML

 
<div id="Grid"></div>
 

 

JS

 
<script type="text/javascript">
$(function () {
        $("#Grid").ejGrid({
            dataSource: window.gridData, //The datasource "window.gridData" is referred from 'http://js.syncfusion.com/demos/web/scripts/jsondata.min.js'
            allowPaging: true,
            allowGrouping: true,
            groupSettings: { groupedColumns: ["EmployeeID"] },
            locale: "de-DE",
            toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport] },
            toolbarClick: function (e) {
                this.exportGrid = this["export"];
                if (e.itemName == "ExcelExport") {
                    this.exportGrid("/Grid/ExportToExcel");
                }
                if (e.itemName == "PdfExport") {
                    this.exportGrid("/Grid/ExportToPdf");
                }
                if (e.itemName == "WordExport") {
                    this.exportGrid("/Grid/ExportToWord");
                }
            },
            columns: [
                { field: "OrderID", headerText: "Order ID", width: 90 },
                { field: "EmployeeID", headerText: "Employee ID", width: 90 },
                { field: "CustomerID", headerText: "Customer ID", width: 90 },
                { field: "ShipCountry", headerText: "ShipCountry", width: 90 },
                { field: "Freight", headerText: "Freight", width: 90 }
            ],
        });
    });
    </script> 

MVC

@(Html.EJ().Grid<object>("FlatGrid")
          .Datasource((IEnumerable<object>)ViewBag.DataSource)
          .AllowPaging()
          .AllowGrouping()
          .GroupSettings(group => { group.GroupedColumns(col => { col.Add("EmployeeID"); }); })
          .ToolbarSettings(toolBar => toolBar.ShowToolbar().ToolbarItems(items =>
          {
              items.AddTool(ToolBarItems.ExcelExport);
              items.AddTool(ToolBarItems.WordExport);
              items.AddTool(ToolBarItems.PdfExport);
          }))
          .Locale("de-DE")
          .ClientSideEvents(eve => { eve.ActionComplete("complete"); })
          .Columns(col =>
          {
              col.Field("OrderID").HeaderText("Order ID").Width(90).Add();
              col.Field("EmployeeID").HeaderText("Employee ID").Width(90).Add();
              col.Field("CustomerID").HeaderText("Customer ID").Width(90).Add();
              col.Field("ShipCountry").HeaderText("Ship Country").Width(90).Add();
              col.Field("Freight").HeaderText("Freight")
          .Width(90).Add();
          }))

 

Excel Exporting

For excel exporting, use ServerExcelGroupCaptionInfo event to get the grouped column details and using that details set the GroupCaptionTemplate as like the format define in GroupCaptionFormat property of localization.

Pdf Exporting

For pdf exporting, use ServerPdfGroupCaptionInfo event to get the grouped column details and using that details set the GroupCaptionTemplate as like the format define in GroupCaptionFormat property of localization.

Word Exporting

For word exporting, use ServerWordGroupCaptionInfo event to get the grouped column details and using that details set the GroupCaptionTemplate as like the format define in GroupCaptionFormat property of localization.

 

[CS]
namespace GroupcaptionformatExport.Controllers
{
    public class GridController : Controller
    {
        public ActionResult GridFeatures()
        {
            var DataSource = new NorthwindDataContext().OrdersViews.ToList();
            ViewBag.datasource = DataSource;
            return View();
 
        }
        // Excel Exporting
      
        public void ExportToExcel(string GridModel)  
        {
            ExcelExport exp = new ExcelExport();
            var DataSource = new NorthwindDataContext().OrdersViews.ToList();
            GridProperties obj = (GridProperties)Syncfusion.JavaScript.Utils.DeserializeToModel(typeof(GridProperties), GridModel);
        // Excel GroupCaptionInfo event
            obj.ServerExcelGroupCaptionInfo = captioninfo; 
            exp.Export(obj, DataSource, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-saffron");
        }
 
       // Word Exporting
 
        public void ExportToWord(string GridModel) 
        {
            WordExport exp = new WordExport();
            var DataSource = new NorthwindDataContext().OrdersViews.ToList();
            GridProperties obj = (GridProperties)Syncfusion.JavaScript.Utils.DeserializeToModel(typeof(GridProperties), GridModel);
            // Word GroupCaptionInfo
            obj.ServerWordGroupCaptionInfo = captioninfo; 
            exp.Export(obj, DataSource, "Export.docx", false, false, "flat-saffron");
        }
 
        // Pdf Export
 
        public void ExportToPdf(string GridModel)   
        {
            PdfExport exp = new PdfExport();
            var DataSource = new NorthwindDataContext().OrdersViews.ToList();
            GridProperties obj = (GridProperties)Syncfusion.JavaScript.Utils.DeserializeToModel(typeof(GridProperties), GridModel);
   
           // Pdf GroupCaptionInfo event           
            obj.ServerPdfGroupCaptionInfo = captioninfo; 
            exp.Export(obj, DataSource, "Export.pdf", false, false, "flat-saffron");
        }
 
        protected void captioninfo(object obj)
        {
            CaptionFormatEventArgs e = (CaptionFormatEventArgs)obj;
 
  // Based on the Key value (i.e. Groupedcolumn value) Group Caption template text is changed. 
 
            if ((int)e.Context.Key == 1 )
            {
                e.GroupCaptionTemplate = e.GroupedColum.Field + " : " + e.Context.Key + "-" + e.Context.Count + " Material";
 
            }
            else
                e.GroupCaptionTemplate = e.GroupedColum.Field + " : " + e.Context.Key + "-" + e.Context.Count + " Materialien";
 
        }
    }
}

 

ASP

 
<ej:Grid ID="Grid" runat="server" AllowPaging="True" Locale="de-DE" AllowGrouping="true" OnServerExcelExporting="Grid_ServerExcelExporting" OnServerWordExporting="Grid_ServerWordExporting" OnServerPdfExporting="Grid_ServerPdfExporting">
        <ToolbarSettings ShowToolbar="true" ToolbarItems="excelExport,wordExport,pdfExport"></ToolbarSettings>
        <GroupSettings GroupedColumns="EmployeeID"></GroupSettings>
        <Columns>
            <ej:Column Field="OrderID" HeaderText="Order ID"  Width="90" />
 
            <ej:Column Field="EmployeeID" HeaderText="Employee ID"  Width="90" />
 
            <ej:Column Field="CustomerID" HeaderText="Customer ID" Width="90" />
 
            <ej:Column Field="ShipCountry" HeaderText="Ship Country" Width="90" />
 
            <ej:Column Field="Freight" HeaderText="Freight" Width="90"  />
 
        </Columns>
    </ej:Grid>
 

 

 
[CS]
 
  protected void Page_Load(object sender, EventArgs e)
        {
          // DataSource Binding
 
            BindDataSource(); 
        }
        private void BindDataSource()
        { 
                this.Grid.DataSource = order;  
                this.Grid.DataBind(); 
        }
 
        // Excel Exporting
 
        protected void Grid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e)  
        {
            ExcelExport exp = new ExcelExport();
            GridProperties obj = ConvertGridObject(e.Arguments["model"].ToString());
 
        // Excel GroupCaptionInfo
 
            obj.ServerExcelGroupCaptionInfo = captioninfo; 
            exp.Export(obj, (IEnumerable)Grid.DataSource, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-saffron");
        }
 
        // Word Exporting
 
        protected void Grid_ServerWordExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e) 
        {
            WordExport exp = new WordExport();
            GridProperties obj = ConvertGridObject(e.Arguments["model"].ToString());
 
        // Word GroupCaptionInfo event
 
            obj.ServerWordGroupCaptionInfo = captioninfo; 
            exp.Export(obj, (IEnumerable)Grid.DataSource, "Export.docx", false, false, "flat-saffron");
        }
 
       // Pdf Export
 
        protected void Grid_ServerPdfExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e) 
 
        {
            PdfExport exp = new PdfExport();
            GridProperties obj = ConvertGridObject(e.Arguments["model"].ToString());
 
        // Pdf GroupCaptionInfo event
 
            obj.ServerPdfGroupCaptionInfo = captioninfo; 
            exp.Export(obj, (IEnumerable)Grid.DataSource, "Export.pdf", false, false, "flat-saffron");
        }
 
        protected void captioninfo(object obj)  
        {
            CaptionFormatEventArgs e = (CaptionFormatEventArgs)obj;
 
              // Based on the Key value (i.e. Groupedcolumn value) Group Caption template text is changed
 
            if ((int)e.Context.Key == 1)
            {
                e.GroupCaptionTemplate = e.GroupedColum.Field + " : " + e.Context.Key + "-" + e.Context.Count + " Material";
 
            }
            else
                e.GroupCaptionTemplate = e.GroupedColum.Field + " : " + e.Context.Key + "-" + e.Context.Count + " Materialien";
 
        }
        private GridProperties ConvertGridObject(string gridProperty)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty, typeof(IEnumerable));
            GridProperties gridProp = this.Grid.Model;
            foreach (KeyValuePair<string, object> ds in div)
            {
                var property = gridProp.GetType().GetProperty(ds.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
 
                if (property != null)
                {
                    Type type = property.PropertyType;
                    string serialize = serializer.Serialize(ds.Value);
                    object value = serializer.Deserialize(serialize, type);
                    property.SetValue(gridProp, value, null);
                }
            }
            return gridProp;
        }
    }
}
 

 

.Net core

 
<ej-grid id="FlatGrid" datasource="ViewBag.datasource" allow-paging="true" locale="de-DE" group-settings="@(new GroupSettings { GroupedColumns = new List<string>() { "EmployeeID" } })" allow-grouping="true">
        <e-toolbar-settings show-toolbar="true" toolbar-items=@(new List<string>() {"excelExport","wordExport","pdfExport" })>
        </e-toolbar-settings>
        <e-columns>
            <e-column field="OrderID" header-text="Order ID" width="90"></e-column>
            <e-column field="EmployeeID" header-text="Employee ID" width="90"></e-column>
            <e-column field="CustomerID" header-text="Customer ID" width="90"></e-column>
            <e-column field="ShipCountry" header-text="Ship Country" width="90"></e-column>
            <e-column field="Freight" header-text="Freight" width="90"></e-column>
        </e-columns>
    </ej-grid>
 

 

 
[CS]
 
public partial class GridController : Controller
    {
        public ActionResult GridFeatures()
        {
            if (order.Count == 0)
                BindDataSource();
            ViewBag.datasource = order;
            return View();
        } 
 
      //Excel Export
 
        public ActionResult ExportToExcel(string GridModel) 
        {
            ExcelExport exp = new ExcelExport();
            BindDataSource();
            GridProperties gridProp = ConvertGridObject(GridModel);
 
      // Excel GroupCaptionInfo event
 
            gridProp.ServerExcelGroupCaptionInfo = captioninfo; 
            return exp.Export(gridProp, order, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-saffron");
        }
 
     // Word Export
 
        public ActionResult ExportToWord(string GridModel) 
        {
            WordExport exp = new WordExport();
            BindDataSource();
            GridProperties gridProp = ConvertGridObject(GridModel);
 
        // Word GroupCaptionInfo event
 
            gridProp.ServerWordGroupCaptionInfo = captioninfo; 
            return exp.Export(gridProp, order, "Export.docx", false, false, "flat-saffron");
        }
     
       // Pdf Export
 
        public ActionResult ExportToPdf(string GridModel) 
        {
            PdfExport exp = new PdfExport();
            BindDataSource();
            GridProperties gridProp = ConvertGridObject(GridModel);
 
       // Pdf GroupCaptionInfo event
 
            gridProp.ServerPdfGroupCaptionInfo = captioninfo; 
            return exp.Export(gridProp, order, "Export.pdf", false, false, "flat-saffron");
        }
 
        protected void captioninfo(object obj)
        {
            CaptionFormatEventArgs e = (CaptionFormatEventArgs)obj;
 
                // Based on the Key value (i.e. Groupedcolumn value) Group Caption template text is changed.
 
            if ((int)e.Context.Key == 1) 
            {
                e.GroupCaptionTemplate = e.GroupedColum.Field + " : " + e.Context.Key + "-" + e.Context.Count + " Material";
 
            }
            else
                e.GroupCaptionTemplate = e.GroupedColum.Field + " : " + e.Context.Key + "-" + e.Context.Count + " Materialien";
 
        }
 
        private GridProperties ConvertGridObject(string gridProperty)
        {
            GridProperties gridProp = new GridProperties();
            gridProp = (GridProperties)JsonConvert.DeserializeObject(gridProperty, typeof(GridProperties));
            return gridProp;
        }
 
    }
 

 

Step 2: Define the localization text for corresponding culture “de-DE”

 
<script>
    ej.Grid.Locale["de-DE"] = {
        EmptyRecord: "Keine Aufzeichnungen angezeigt",
        GroupDropArea: "Ziehen Sie eine Spaltenüberschrift hier",
        DeleteOperationAlert: "Keine Einträge für Löschvorgang ausgewählt",
        EditOperationAlert: "Keine Einträge für Bearbeiten Betrieb ausgewählt",
        SaveButton: "Speichern",
        CancelButton: "stornieren",
        EditFormTitle: "Korrektur von",
        GroupCaptionFormat: "{{:field}}: {{:key}} - {{:count}} {{if key == 1}}Material{{else}}Materialien{{/if}}",
        UnGroup: "Klicken Sie hier, um die Gruppierung aufheben"
    };
</script>
 

 

 

 

Output:

Figure 1: Excel Exporting

 

 

 

Figure 2:Pdf Exporting

 

 

 

Figure 3: Word Exporting


 

 

 Note:

A new version of Essential Studio for ASP.NET is available. Versions prior to the release of Essential Studio 2014, Volume 2 will now be referred to as a classic versions.The new ASP.NET suite is powered by Essential Studio for JavaScript providing client-side rendering of HTML 5-JavaScript controls, offering better performance, and better support for touch interactivity. The new version includes all the features of the old version, so migration is easy.

The Classic controls can be used in existing projects; however, if you are starting a new project, we recommend using the latest version of Essential Studio for ASP.NET. Although Syncfusion will continue to support all Classic Versions, we are happy to assist you in migrating to the newest edition.

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