)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Essential JS2

Syncfusion jQuery based widgets are no longer in active development. Switch to our pure JavaScript based next generation Essential JS 2 library.

Syncfusion Feedback

How to save and retrieve the Spreadsheet data as JSON in database

Platform: jQuery |
Control: ejSpreadSheet |
Published Date: April 24, 2017 |
Last Revised Date: May 22, 2019

Description

This knowledge base explains the way to save and retrieve the Spreadsheet data as JSON in Database.

Solution

You can use “loadFromJSON()” and “saveAsJSON()” client side methods to achieve this requirement.

 

JavaScript

 

[JS]

 

    <div style="margin: 7px;">
        <!--  Save Spreadsheet data to database -->
        <input type="text" id="saveFileName" />
        <input type="button" value="Save" id="saveFileToDatabase" />
        <!--  Open Spreadsheet data from database -->
        <select id="importFileName">
            <!-- Existing saved files -->
            <option value="file1">File 1</option>
            <option value="file2">File 2</option>
        </select>
        <input type="button" value="Import" id="openFileFromDatabase" />
    </div>
    <div id="Spreadsheet"></div>
 
    <script>
         $(function () {
            $("#Spreadsheet").ejSpreadsheet({
                scrollSettings: {
                    height: "100%",
                    width: "100%"
                }
            });
        });
 
        $("#saveFileToDatabase").bind("click", function () {
            var xlObj = $("#Spreadsheet").data("ejSpreadsheet"), jsonData = xlObj.saveAsJSON(), filename = $("#saveFileName").val(); 
            $.ajax({
                type: "POST",
                data: { fileName: filename, jsonData: JSON.stringify(jsonData) },
                url: "/Spreadsheet/SaveFiletoDB",
                success: function (data) {
                    // Success code here.
                }
            });
 
 
        $("#openFileFromDatabase").bind("click", function () {
            var xlObj = $("#Spreadsheet").data("ejSpreadsheet"), fileName = $("#importFileName").val();
            if (fileName.length) {
                xlObj.showWaitingPopUp();
                $.ajax({
                    type: "POST",
                    url: "/Spreadsheet/OpenFileFromDB",
                    data: { filename: fileName },
                    success: function (data) {
                        xlObj.loadFromJSON(JSON.parse(data));
                        xlObj.hideWaitingPopUp();
                    }
                });
            }
        });
        });
    </script>
 

 

 [Web API]

 

 
        string connectionString = ConfigurationManager.ConnectionStrings["FileData"].ConnectionString;
        [OperationContract]
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare)]
        [System.Web.Http.ActionName("SaveFiletoDB")]
        [AcceptVerbs("POST")]
       // Save the Spreadsheet data as JSON to database
        public void SaveFiletoDB()
        {
            string fileName = HttpContext.Current.Request.Params["fileName"], jsonData = HttpContext.Current.Request.Params["jsonData"];
            try
            {
                if (fileName.Length > 0)
                {
                    SqlConnection sqlCon = new SqlConnection(connectionString);
                    sqlCon.Open();
                    SqlCommand sqlComm = new SqlCommand("INSERT INTO [dbo].[Table]([FileName], [FileData]) VALUES (@FileName, @FileData)", sqlCon);
                    sqlComm.Parameters.AddWithValue("@FileName", fileName);
                    sqlComm.Parameters.AddWithValue("@FileData", jsonData);
                    sqlComm.ExecuteNonQuery();
                    sqlCon.Close();
                }
             }
            catch (Exception e)
            {
                // Error handling code here.
            }
         } 
 
        //Open Saved Spreadsheet data from database
        [OperationContract]
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare)]
        [System.Web.Http.ActionName("OpenFileFromDB")]
        [AcceptVerbs("POST")]
        public string OpenFileFromDB()
        {
            string filename = HttpContext.Current.Request.Params["filename"];
            ImportRequest importRequest = new ImportRequest();
            SqlConnection sqlCon = new SqlConnection(connectionString);
            SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Table] WHERE [FileName] = '" + filename + "'", sqlCon);
            string JsonData = string.Empty;
            sqlCon.Open();
            SqlDataReader sqlDR = sqlComm.ExecuteReader();
            if (sqlDR.Read())
            {
                // Retrieve JSON from database
                JsonData = (string)sqlDR.GetValue(1);
            }
            sqlCon.Close();
            return JsonData;
        }
 

 

 

MVC

 

[CSHTML]

 

   <div style="margin: 7px;">
        <!--  Save Spreadsheet data to database -->
        <input type="text" id="saveFileName" />
        <input type="button" value="Save" id="saveFileToDatabase" />
        <!--  Open Spreadsheet data from database -->
         @Html.DropDownList("importFileName", ViewBag.FileNameList as List<SelectListItem>)
        <input type="button" value="Import" id="openFileFromDatabase" />
    </div>
 
<div style="height:550px;">
  @(Html.EJ().Spreadsheet<object>("Spreadsheet")
    .ScrollSettings(scroll =>
    {
        scroll.Height("100%");
        scroll.Width("100%");
    })
  )
    </div>
</div>
<script>
        $("#saveFileToDatabase").bind("click", function () {
            var xlObj = $("#Spreadsheet").data("ejSpreadsheet"), jsonData = xlObj.saveAsJSON(), filename = $("#saveFileName").val();
            $.ajax({
                type: "POST",
                data: { fileName: filename, jsonData: JSON.stringify(jsonData) },
                url: "/Home/SaveFiletoDB",
                success: function (data) {
                    // Success code here.            
                }
            });
 
        $("#openFileFromDatabase").bind("click", function () {
            var xlObj = $("#Spreadsheet").data("ejSpreadsheet"), fileName = $("#importFileName").val();
            if (fileName.length) {
                xlObj.showWaitingPopUp();
                $.ajax({
                    type: "POST",
                    data: { filename: fileName },
                    url: "/Home/OpenFileFromDB",
                    success: function (data) {
                        xlObj.loadFromJSON(JSON.parse(data));
                        xlObj.hideWaitingPopUp();
                        $("#saveFileName").val(fileName);
                    }
                });
            }
        });
 
        });
</script>

 

[Controller]

 

        string connectionString = ConfigurationManager.ConnectionStrings["FileData"].ConnectionString;      
        // Save the Spreadsheet data as JSON to database.
        [AcceptVerbs(HttpVerbs.Post)]
        public void SaveFiletoDB(string fileName, string jsonData)
        {
            try
            {
                if (fileName.Length > 0)
                {
                    SqlConnection sqlCon = new SqlConnection(connectionString);
                    sqlCon.Open();
                    SqlCommand sqlComm = new SqlCommand("INSERT INTO [dbo].[Table]([FileName], [FileData]) VALUES (@FileName, @FileData)", sqlCon);
                    sqlComm.Parameters.AddWithValue("@FileName", fileName);
                    sqlComm.Parameters.AddWithValue("@FileData", jsonData);
                    sqlComm.ExecuteNonQuery();
                    sqlCon.Close();
                }
            }
            catch (Exception e)
            {
                //Error handling code here.
            }
        } 
 
        //Open saved Spreadsheet data from database
        [AcceptVerbs(HttpVerbs.Post)]
        public string OpenFileFromDB(string filename)
        {
            ImportRequest importRequest = new ImportRequest();
            SqlConnection sqlCon = new SqlConnection(connectionString);
            SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Table] WHERE [FileName] = '" + filename + "'", sqlCon);
            string JsonData = string.Empty;
            sqlCon.Open();
            SqlDataReader sqlDR = sqlComm.ExecuteReader();
            if (sqlDR.Read())
            {
                // Retrieve JSON from database
                JsonData = (string)sqlDR.GetValue(1);
            }
            sqlCon.Close();
            return JsonData;
        }
 

 

 

ASP

 

[ASPX]

 

   <div style="margin: 7px;">
        <!--  Save Spreadsheet data to database -->
        <input type="text" id="saveFileName" />
        <input type="button" value="Save" id="saveFileToDatabase" />
        <!--  Open Spreadsheet data from database -->
         <asp:DropDownList ID="importFileName" runat="server" Height='30px' Width='150px' DataTextField="Text"></asp:DropDownList>
        <input type="button" value="Import" id="openFileFromDatabase" />
    </div>
 
    <ej:Spreadsheet ID="Spreadsheet" runat='server'>
            <ScrollSettings Width="100%" Height="100%" />
    </ej:Spreadsheet>
 
<script>
        // Save the Spreadsheet data as JSON to database.
        $("#saveSpreadsheetToDatabase").bind("click", function () {
            var xlObj = $("#MainContent_Spreadsheet").data("ejSpreadsheet"), fileName = $("#saveFileName").val(), jsonData = JSON.stringify(xlObj.saveAsJSON());
            $.ajax({
                type: "POST",
                url: "SpreadsheetFeatures.aspx/SaveSpreadsheetToDB",
                data: JSON.stringify({ fileName: fileName, jsonData: jsonData }),
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (data) {
                    // Success code here.
                }
            });
        });
        // Open the saved Spreadsheet data from database.
        $("#openFileFromDatabase").bind("click", function () {
            var xlObj = $("#MainContent_Spreadsheet").data("ejSpreadsheet"), fileName = $("#MainContent_ImportFileName").val();
            xlObj.showWaitingPopUp();
            $.ajax({
                type: "POST",
                url: "SpreadsheetFeatures.aspx/OpenSpreadsheetFromDB",
                data: JSON.stringify({ filename: fileName }),
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (data) {
                    xlObj.loadFromJSON(JSON.parse(data.d));
                    xlObj.hideWaitingPopUp();
                }
            });
        });
</script>

 

[C#]

 

        string connectionString = ConfigurationManager.ConnectionStrings["FileData"].ConnectionString;  
        // Save the Spreadsheet data as JSON to database.
        [WebMethod]
        public static void SaveSpreadsheetToDB(string fileName, string jsonData)
        {
            try
            {
                if (fileName.Length > 0)
                {
                    SqlConnection sqlCon = new SqlConnection(connetionString);
                    sqlCon.Open();
                    SqlCommand sqlComm = new SqlCommand("INSERT INTO [dbo].[Table]([FileName], [FileData]) VALUES (@FileName, @FileData)", sqlCon);
                    sqlComm.Parameters.AddWithValue("@FileName", fileName);
                    sqlComm.Parameters.AddWithValue("@FileData", jsonData);
                    sqlComm.ExecuteNonQuery();
                    sqlCon.Close();
                }
            }
            catch (Exception e)
            {
                // Error handling code here.
            }
        } 
 
        //Open saved Spreadsheet data from database
        [WebMethod]
        public static string OpenSpreadsheetFromDB(string filename)
        {
            SqlConnection sqlCon = new SqlConnection(connectionString);
            SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Table] WHERE [FileName] = '" + filename + "'", sqlCon);
            string JsonData = string.Empty;
            sqlCon.Open();
            SqlDataReader sqlDR = sqlComm.ExecuteReader();
            if (sqlDR.Read())
            {
                // Retrieve JSON from database
                JsonData = (string)sqlDR.GetValue(1);
            }
            sqlCon.Close();
            return JsonData;
        }

Also please refer the below UG Documentation link,

 

https://help.syncfusion.com/api/js/ejspreadsheet#methods:saveasjson

https://help.syncfusion.com/api/js/ejspreadsheet#methods:loadfromjson

ADD COMMENT
You must log in to leave a comment
Comments
Pradeep Kumar
May 19, 2017
Hi,

I have tried both examples 
1) Open and Save Data to SQL Server As Stream
2) Open and Save Data to SQL Server as JSON Data

Both example are running properly.

But i have to Open And Save data from sql as Sql Table Data

I have one tables of Order in SQL and I have to Open this Table Data in Excel And After Changing Contents ,Save this Order Table Back To Server.

Is There any way to do this????

Eg.

OrderIDCustomerIDOrder DescriptionQtyPriceLink
1111Test Item3900--
2222Test Item520400--


Reply
Shanmugaraja K [Syncfusion]
May 22, 2017

Hi Pradeep,

 

Please refer the below forum link to achieve your requirement,

 

https://www.syncfusion.com/forums/130584/open-and-save-data-from-sql-table-in-spreadsheet

 

Regards,

Shanmugaraja K

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon