Articles in this section
Category / Section

How to export Grid to Word, Excel and PDF in JavaScript application?

9 mins read

You can export ejGrid from the HTML file by using the Export function. However for exporting, you need some server-side services. Used here is the WebAPI and the provided code example related to it for exporting the Grid to Excel, Word and PDF. In the code example provided toolbarClick event is used to call the Export method in the WebAPI controller.

HTML

<div id="Grid"></div>
    <script type="text/javascript">
        $(function () {
            //The datasource "window.gridData" is referred from jsondata.min.js.            
            $("#Grid").ejGrid({
                dataSource: ej.DataManager({ url: "api/Export", adaptor: "WebApiAdaptor" }),
                toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.ExcelExport,                                                           ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport] },
                toolbarClick: function (args) {
                    if (args.itemName == "Excel Export") {
                        args.cancel = true;
                        this.export("api/Export/ExcelExport"); // Excel Export method.
                    }
                    if (args.itemName == "Word Export") {
                        args.cancel = true;
                        this.export("api/Export/WordExport"); // Word Export method.
                    }
                    if (args.itemName == "PDF Export") {
                        args.cancel = true;
                        this.export("api/Export/PdfExport"); // PDF Export method.
                    } },
                columns: [
                        { field: "OrderID", headerText: "Order ID", width: 75, textAlign:        ej.TextAlign.Right },
                        …..
                ]
            });
        });
    </script>

Controller

    public class ExportController : ApiController
    {
        // GET api/<controller>
        NorthwindDataContext db = new NorthwindDataContext();
        public PageResult<Order> Get(ODataQueryOptions opts)
        {
            var results = opts.ApplyTo(db.Orders.AsQueryable());
            var data = db.Orders.AsQueryable();
            return new PageResult<Order>((IEnumerable<Order>)results, null, data.Count());
        }        
        public string Get(int id)
        {
            return "value";
        }        
               //Excel Export Method.
        [System.Web.Http.ActionName("ExcelExport")]
        [AcceptVerbs("POST")]
        public void ExcelExport()
        {
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
            GridProperties gridProperty = ConvertGridObject(gridModel);
            ExcelExport exp = new ExcelExport();            
            IEnumerable<Order> result = db.Orders.ToList();
            exp.Export(gridProperty, result, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-                                                                                                                                                              saffron");
        }      
               //Word Export Method.
        [System.Web.Http.ActionName("WordExport")]
        [AcceptVerbs("POST")]
        public void WordExport()
        {
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
            GridProperties gridProperty = ConvertGridObject(gridModel);
            WordExport exp = new WordExport();
            IEnumerable<Order> result = db.Orders.ToList();
            exp.Export(gridProperty, result, "Export.docx", false, false, "flat-saffron");
        }
               //PDF Export Method.
        [System.Web.Http.ActionName("PdfExport")]
        [AcceptVerbs("POST")]
        public void PdfExport()
        {
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
            GridProperties gridProperty = ConvertGridObject(gridModel);
            PdfExport exp = new PdfExport();           
            IEnumerable<Order> result = db.Orders.ToList();
            exp.Export(gridProperty, result, "Export.pdf");
        }      
               //Grid Model conversion Method.
        private GridProperties ConvertGridObject(string gridProperty)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty, typeof(IEnumerable));
            GridProperties gridProp = new GridProperties();
            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;
        }

Server Side Dependencies:

Export helper functions are available in the Assembly Syncfusion.EJ.Export which are needed for exporting of the Grid. Full list of assemblies needed for the Grid export are as follows.

  1. Syncfusion.EJ
  2. Syncfusion.EJ.Export
  3. Syncfusion.Compression.Base
  4. Syncfusion.Linq.Base
  5. Syncfusion.DocIO.Base
  6. Syncfusion.XlsIO.Base
  7. Syncfusion.PDF.Base

Parameter used in excel export method

Parameter

Type

Defination

  1. gridmodel

GridProperties

Add the grid collection to export

  1. datasource

IEnumerable

Include the grid data source

  1. excelname

string

To set the excel file name

  1. excelversion

ExcelVersion

To set the machine supported version to excel

  1. isHideColumnIncude

bool

To show or hide the visible false column

  1. isTemplateColumnIclude

bool

To show the template column in export method

  1. theme

string

To set the required theme to grid

  1. multipleExport

bool

To enable multiple exporting

  1. workBook

IWorkbook

Open existing file or create new file

  1.  exportType

MultipleExportType

To export in multiple sheet

  1. headerText

string

To set the title to grid

Parameter used in word export method

Parameter

Type

Defination

  1. gridmodel

GridProperties

Add the grid collection to export

  1. datasource

IEnumerable

Include the grid data source

  1. fileName

string

To set the word file name

  1. isHideColumnIncude

bool

To show or hide the visible false column

  1. isTemplateColumnIclude

bool

To show the template column in export method

  1. theme

string

To set the required theme to grid

  1. multipleExport

bool

To enable multiple exporting

  1. document

IWordDocument

Open existing file or create new file

  1. headerText

string

To set the title to grid

Parameter used in PDF export method

Parameter

Type

Defination

  1. gridmodel

GridProperties

Add the grid collection to export

  1. datasource

IEnumerable

Include the grid data source

  1. fileName

string

To set the excel file name

  1. isHideColumnIncude

bool

To show or hide the visible false column

  1. isTemplateColumnIclude

bool

To show the template column in export method

  1. theme

string

To set the required theme to grid

  1. multipleExport

bool

To enable multiple exporting

  1. document

PdfDocument

Open existing file or create new file

  1. headerText

string

To set the title to grid

Result

Output

Exported gridFigure 1: Output


Conclusion

I hope you enjoyed learning about how to export Grid to Word, Excel and PDF in JavaScript application.

You can refer to our JavaScript 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 JavaScript 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