As a member of the Grid ASP.NET MVC team, I discovered a cross-browser way to access data pasted in an HTML <div> element. I was wondering whether this could be replicated in our Syncfusion grid control to paste data from Excel, and gave it a try. It actually works!
The following procedure illustrates how to perform this operation in the grid control.
For the purpose of this demo, I have used a simple grid configuration. The following code example illustrates how to define the grid in the view page and controller.
Controller
public ActionResult Index() { return View(); } // Passing Data to View. public JsonResult GetData() { IEnumerable data = EmployeeRepository.GetEmployees(); return Json(data, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult Index(string pastedData) { if (pastedData != null) { // Parsing pasted data to Actual type. var parsed = (List)new JavaScriptSerializer().Deserialize(pastedData, typeof(List)); // Updating the Database. EmployeeRepository.AddRange(parsed); } // Getting data from repository. var data = EmployeeRepository.GetEmployees().ToList(); return Json(data, JsonRequestBehavior.AllowGet); }
The HTML markup and jQuery scripts play a vital role in getting clipboard Excel information and converting it to JSON. Also, for this purpose, I have written the jquery.pastable.js file in the jQuery plug-in style.
Note: The jquery.pastable.js file is attached with the sample at the end of this post.
The final script and HTML markup are as follows.
[CSHTML]
Paste your Excel data here:
[jQuery]
$(document).ready(function () { // Binding the paste-able jQuery plug-in. $("#pastable").pastable({ OnPasteComplete: function (data) { var jsonData = []; // Ensuring the pasted information is Excel data or HTML table data. if (data instanceOf Object) { for (i = 0; i < data.length; i++) { jsonData.push(data[i]); } $.ajax({ url: "/Home/Index" type: "POST", data: { pastedData: JSON.stringify(jsonData) }, success: function (gridData) { // Acquiring grid object and updating data source. var gridObj = $("#Grid").data("ejGrid"); gridObj.dataSource(ej.parseJSON(gridData)); } }); } }); });
The output appears as follows.
Excel Data
Before pasting.
After pasting.
As seen here, the client-side and server-side libraries of Essential Grid for ASP.NET MVC are flexible and can be used for all programming needs of yours.
You can also download a sample on this here.
Content Contributors: Bharath M; Alan Sangeeth S Content Editor: GeeGee Inekeya