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. Image for the cookie policy date

Save data from spreadsheet to database

Hi,
Is there a way to save/import data from Spreadsheet control to sql database?
My spreadsheet contains a matrix (n lines and m columns),and the user can add or modify the values (there is excel functions depends on these values), at the end of modification I want to save the data on thisspreadsheet.
Is this possible?

Regards,
Anis

23 Replies

SI Silambarasan I Syncfusion Team May 18, 2017 10:45 AM UTC

Hi Anis, 
 
Thank you for using Syncfusion products. 
 
We have checked your query and we would like to let you know that your requirement “To save/import, update data from Spreadsheet control to SQL database” has been achieved by using ‘Open()’ & ‘Save()’ server-side methods in Spreadsheet.  Please refer the following code example. 
 
CSHTML[VIEW] 
 
<table> 
<tr> 
    //... 
        @Html.DropDownList("ImportFileName", ViewBag.FileNameList as List<SelectListItem>, new { @style = "width:130px;" }) 
    <td> 
        <input type="button" value="Import" id="openFileFromDatabase" /> 
    </td> 
</tr> 
</table> 
 
<table> 
    //... 
    <tr> 
        //... 
        <td> 
            <input type="button" value="Save" id="saveFileToDatabase" /> 
        </td> 
        <td> 
            <input type="button" value="Save Changes" id="saveChangesOnly" /> 
        </td> 
    </tr> 
</table> 
 
@(Html.EJ().Spreadsheet<object>("Spreadsheet") 
    //... 
    .ClientSideEvents(eve => 
    { 
        eve.LoadComplete("onLoadComplete"); 
    }) 
) 
 
<script type="text/javascript"> 
    function onLoadComplete(args) { 
        if (this.isImport) 
            this.XLEdit.saveEditingValue();//Get or reset the saved changes collection on importing data from DB 
    } 
    $("#openFileFromDatabase").bind("click", function () { 
        var ssObj = $("#Spreadsheet").data("ejSpreadsheet"), fileName = $("#ImportFileName").val(); 
        if (fileName.length) { 
            ssObj.showWaitingPopUp(); 
            $.ajax({ 
                type: "POST", 
                data: { filename: fileName }, 
                url: "/Home/OpenFileFromDB", 
                success: function (data) { 
                    ssObj.loadFromJSON(JSON.parse(data)); 
                    ssObj.hideWaitingPopUp();                     
                } 
            }); 
        } 
    }); 
 
    $("#saveFileToDatabase").bind("click", function () { 
        var ssObj = $("#Spreadsheet").data("ejSpreadsheet"), exportProp = ssObj.XLExport.getExportProps(), filename = $("#exportFileName").val(); 
        $.ajax({ 
            type: "POST", 
            data: { fileName: filename, sheetModel: exportProp.model, sheetData: exportProp.data }, 
            url: "/Home/SaveAndUpdateToDatabase", 
            success: function (data) { 
                //... 
            } 
        }); 
    }); 
 
    $("#saveChangesOnly").bind("click", function () { 
        var ssObj = $("#Spreadsheet").data("ejSpreadsheet"), filename = $("#exportFileName").val(), editedChanges = ssObj.XLEdit.saveEditingValue(); 
        $.ajax({ 
            type: "POST", 
            data: { fileName: filename, editedValues: JSON.stringify(editedChanges.EditedData) }, 
            url: "/Home/SaveChangesToDatabase", 
            success: function (data) { 
                //... 
            } 
        }); 
    }); 
</script> 
 
 
 
C# [CONTROLLER] 
 
//File Open from database 
[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult OpenFileFromDB(string filename) 
{ 
    ImportRequest importRequest = new ImportRequest(); 
    SqlConnection sqlCon = new SqlConnection(connetionString); 
    SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Table] WHERE [FileName] = '" + filename + "'", sqlCon); 
    sqlCon.Open(); 
    SqlDataReader sqlDR = sqlComm.ExecuteReader(); 
    if (sqlDR.Read()) 
    { 
        importRequest.FileStream = new MemoryStream((byte[])sqlDR.GetValue(1)); // Get binary values from DB. 
    } 
    sqlCon.Close(); 
    return Content(Spreadsheet.Open(importRequest)); 
} 
 
[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult SaveAndUpdateToDatabase(string fileName, string sheetModel, string sheetData) 
{ 
    MemoryStream dataStream = (MemoryStream)Spreadsheet.Save(sheetModel, sheetData, ExportFormat.XLSX, ExcelVersion.Excel2013);             
    byte[] dataBytes = dataStream.ToArray(); 
    SqlConnection sqlCon = new SqlConnection(connetionString); 
    sqlCon.Open(); 
    SqlCommand selectComm = new SqlCommand("SELECT * FROM [dbo].[Table] WHERE [FileName] = '" + fileName + "'", sqlCon); 
    var hasFileInDB = selectComm.ExecuteScalar(); 
    if (hasFileInDB == null) 
    { 
        SqlCommand sqlComm = new SqlCommand("INSERT INTO [dbo].[Table]([FileName], [FileData]) VALUES (@FileName, @FileData)", sqlCon); 
        sqlComm.Parameters.AddWithValue("@FileName", fileName); 
        sqlComm.Parameters.AddWithValue("@FileData", dataBytes); 
        sqlComm.ExecuteNonQuery(); 
    } 
    else 
    { 
        SqlCommand updateComm = new SqlCommand("UPDATE [dbo].[Table] SET FileData=@nFileData WHERE FileName=@nFileName", sqlCon); // Update edited data to DB. 
        updateComm.CommandTimeout = 0; 
        updateComm.Parameters.AddWithValue("@nFileName", fileName); 
        updateComm.Parameters.AddWithValue("@nFileData", dataBytes); 
        updateComm.ExecuteNonQuery(); 
    } 
    sqlCon.Close(); 
    return Content(fileName); 
} 
 
//Save changes only 
[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult SaveChangesToDatabase(string fileName, string editedValues) 
{ 
    JavaScriptSerializer serialize = new JavaScriptSerializer(); 
    List<CellDetail> editedData = serialize.Deserialize<List<CellDetail>>(editedValues); 
 
    MemoryStream dataStream = new MemoryStream(); 
    SqlConnection sqlCon = new SqlConnection(connetionString); 
    SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Table] WHERE [FileName] = '" + fileName + "'", sqlCon); 
    sqlCon.Open(); 
    SqlDataReader sqlDR = sqlComm.ExecuteReader(); 
    if (sqlDR.Read()) 
    { 
        dataStream = new MemoryStream((byte[])sqlDR.GetValue(1)); // Get Stream values from DB. 
    } 
    sqlDR.Close(); 
    ExcelEngine excelEngine = new ExcelEngine(); 
    IApplication application = excelEngine.Excel; 
    IWorkbook workbook = application.Workbooks.Open(dataStream); 
    IWorksheet sheet; 
    for (int i = 0; i < editedData.Count; i++) 
    { 
        CellDetail data = editedData[i]; 
        sheet = workbook.Worksheets[data.SheetIndex - 1]; 
        // C# backend edit process by using XlsIo Library. 
        sheet.Rows[data.CellIndex.RowIndex].Cells[data.CellIndex.ColIndex].Value = data.Value; 
    } 
    MemoryStream newDataStream = new MemoryStream(); 
    workbook.Version = ExcelVersion.Excel2013; 
    workbook.Application.DefaultVersion = ExcelVersion.Excel2013; 
    workbook.SaveAs(newDataStream); 
 
    SqlCommand updateComm = new SqlCommand("UPDATE [dbo].[Table] SET FileData=@nFileData WHERE FileName=@nFileName", sqlCon);             
    byte[] dataBytes = newDataStream.ToArray(); 
    updateComm.Parameters.AddWithValue("@nFileName", fileName); 
    updateComm.Parameters.AddWithValue("@nFileData", dataBytes); 
    updateComm.ExecuteNonQuery(); 
    sqlCon.Close(); 
    return Content("Successfully updated"); 
} 
 
 
For your convenience, we have prepared a sample to demonstrate your requirement and the same can be downloaded from the below link, 
 
Could you please check the above sample and get back to us if we misunderstood your requirement? Also, please refer the below KB link, 
 
Regards, 
Silambarasan 



FR Francisco July 22, 2020 10:34 PM UTC

Hi Syncfusion, 
do you have a same example with ej2, asp.net mvc and Syncfusion.EJ2.Spreadsheet, Version=18.2500.0.45
the example is for save changes from cliente in web browser and save only rows with changes
thanks


MV Madhan Venkateshan Syncfusion Team July 28, 2020 06:50 AM UTC

Hi Francisco, 
 
Good day to you. 
 
We have prepared a sample based on your requirement. You can use ‘cellSave’ event to store the changes, please refer the below code snippets and sample link. 
 
Index.cshtml 
<div class="control"> 
        <button class="e-btn" id="saveChanges">Save Changes to DB</button> 
        <button class="e-btn" id="openFromDB">Open from DB</button> 
        @Html.EJS().Spreadsheet("spreadsheet").CellSave("cellSave").OpenUrl("Home/Open").SaveUrl("Home/Save").Render() 
    </div> 
    <script type="text/javascript"> 
        var dataChanged = []; 
        document.getElementById("saveChanges").addEventListener("click", () => { 
            var formData = new FormData(); 
            formData.append("fileName", "Sample"); 
            formData.append("cellDetail", JSON.stringify(dataChanged)); 
            fetch("Home/SaveChangesToDB", { 
                method: "POST", 
                body: formData 
            }).then((response) => { 
                dataChanged = []; 
            }); 
        }); 
 
        document.getElementById("openFromDB").addEventListener("click", () => { 
            var formData = new FormData(); 
            formData.append("fileName", "Sample"); 
            fetch("Home/LoadFromDataBase", { 
                method: "POST", 
                body: formData 
            }).then((response) => { 
                 response.json().then((data) => { 
                    var spreadsheetObj = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet'); 
                    spreadsheetObj.openFromJson({ file: data }); 
                }); 
            }); 
        }); 
 
        function cellSave(args) { 
            dataChanged.push({ value: args.value, address: args.address.split('!')[1], sheetIdx: this.activeSheetIndex }); 
        } 
    </script> 
 
 
HomeController.cs 
public ActionResult LoadFromDataBase(String fileName) 
        { 
            //Load file from database 
            OpenRequest openRequest = new OpenRequest(); 
            SqlConnection sqlCon = new SqlConnection(connectionString); 
            SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Table1] WHERE [filename] = '" + fileName + "'", sqlCon); 
            sqlCon.Open(); 
            SqlDataReader sqlDR = sqlComm.ExecuteReader(); 
            while (sqlDR.Read()) 
            { 
                HttpPostedFileBase objFile = (HttpPostedFileBase)new HttpPostedFile((byte[])sqlDR.GetValue(1), fileName); 
                HttpPostedFileBase[] theFiles = new HttpPostedFileBase[1]; 
                theFiles[0] = objFile; 
                openRequest.File = theFiles; 
            } 
            sqlCon.Close(); 
            return Content(Workbook.Open(openRequest)); 
        } 
 
        public string SaveChangesToDB(string fileName, string cellDetail) 
        { 
            JavaScriptSerializer serialize = new JavaScriptSerializer(); 
            List<CellDetail> editedData = serialize.Deserialize<List<CellDetail>>(cellDetail); 
 
            MemoryStream dataStream = new MemoryStream(); 
            SqlConnection sqlCon = new SqlConnection(connectionString); 
            SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Table1] WHERE [filename] = '" + fileName + "'", sqlCon); 
            sqlCon.Open(); 
            SqlDataReader sqlDR = sqlComm.ExecuteReader(); 
            while (sqlDR.Read()) 
            { 
                dataStream = new MemoryStream((byte[])sqlDR.GetValue(1)); 
                 
            } 
            sqlDR.Close(); 
            ExcelEngine excelEngine = new ExcelEngine(); 
            IApplication application = excelEngine.Excel; 
            IWorkbook workbook = application.Workbooks.Open(dataStream); 
            IWorksheet sheet; 
            for (int i = 0; i < editedData.Count; i++) 
            { 
                CellDetail cell = editedData[i]; 
                sheet = workbook.Worksheets[cell.sheetIdx]; 
                // C# backend edit process by using XlsIo Library.  
                sheet.Range[cell.address].Value = cell.value; 
            } 
            MemoryStream newDataStream = new MemoryStream(); 
            //workbook.Version = ExcelVersion.Excel2013; 
            //workbook.Application.DefaultVersion = ExcelVersion.Excel2013; 
            workbook.SaveAs(newDataStream); 
 
            SqlCommand updateComm = new SqlCommand("UPDATE [dbo].[Table1] SET databytes=@dataBytes WHERE fileName=@filename", sqlCon); 
            byte[] dataBytes = newDataStream.ToArray(); 
            updateComm.Parameters.AddWithValue("@filename", fileName); 
            updateComm.Parameters.AddWithValue("@dataBytes", dataBytes); 
            updateComm.ExecuteNonQuery(); 
            sqlCon.Close(); 
            return "success"; 
        } 
 
 
Regards, 
Madhan V 



ES esayas March 10, 2021 07:00 AM UTC

Nice work, will update the dependency package to try please. It brings a lot of error, even after installed; Nancy, Documentformat,openxml, system.data.sqlclient, microsoft.azure.activedirectory.graphclient(version issue for .net not .net core ).

please help a try for .net core 3 version with mentioned syncfusion version.


SP Sangeetha Priya Murugan Syncfusion Team March 11, 2021 08:17 AM UTC

Hi esayas, 
 
Thank you for your update. 
 
We have checked your reported requirement and we have prepared the sample in ASP.NET CORE. In this we have load the data from the sql table and save the edited changes in sql table using cellSave event as like as below. 
 
   
<ejs-spreadsheet id="spreadsheet" created="createdHandler" cellSave="cellSave"> 
    <e-spreadsheet-sheets> 
        <e-spreadsheet-sheet name="Shipment Details"> 
            <e-spreadsheet-ranges> 
                <e-spreadsheet-range> 
                    <e-data-manager url="https://localhost:44355/Home/LoadFromTable" crossdomain=true></e-data-manager> 
                </e-spreadsheet-range> 
            </e-spreadsheet-ranges> 
            
            <e-spreadsheet-columns> 
                <e-spreadsheet-column width=100></e-spreadsheet-column> 
                <e-spreadsheet-column width=130></e-spreadsheet-column> 
                <e-spreadsheet-column width=100></e-spreadsheet-column> 
                <e-spreadsheet-column width=220></e-spreadsheet-column> 
                <e-spreadsheet-column width=150></e-spreadsheet-column> 
                <e-spreadsheet-column width=180></e-spreadsheet-column> 
            </e-spreadsheet-columns> 
        </e-spreadsheet-sheet> 
    </e-spreadsheet-sheets> 
</ejs-spreadsheet> 
 
<script> 
 
    function cellSave(args) { 
                var ssObj = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet'); 
        var indices =ssObj.getAddressInfo(args.address).indices; 
        var fieldName; 
        var key; 
        ssObj.getData(ej.spreadsheet.getRangeAddress([0, indices[1]])).then((cells) => { 
            cells.forEach((cell) => { 
                fieldName = cell.value; 
                ssObj.getData(ej.spreadsheet.getRangeAddress([indices[0], 0])).then((cells) => { 
                    cells.forEach((cell) => { 
                        key = cell.value; 
                        var formData = new FormData(); 
                        formData.append('fieldName', fieldName); 
                        formData.append('key', key); 
                        formData.append('value', args.value); 
                        fetch('https://localhost:44355/Home/SaveToTable', { 
                            method: 'POST', 
                            body: formData 
                        }).then((response) => console.log(response)); 
                    }); 
                }); 
            }); 
        }); 
    } 
</script> 
 
 
public object LoadFromTable() 
        { 
            List<EmployeeData> datas = new List<EmployeeData>(); 
            SqlConnection sqlCon = new SqlConnection(connectionString); 
            SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Employees]", sqlCon); 
            sqlCon.Open(); 
            SqlDataReader sqlDR = sqlComm.ExecuteReader(); 
            while (sqlDR.Read()) 
            { 
                EmployeeData data = new EmployeeData(); 
                data.EmployeeID = (int)sqlDR.GetValue(0); 
                data.LastName = sqlDR.GetValue(1).ToString(); 
                data.FirstName = sqlDR.GetValue(2).ToString(); 
                data.Title = sqlDR.GetValue(3).ToString(); 
                data.TitleOfCourtesy = sqlDR.GetValue(4).ToString(); 
                datas.Add(data); 
            } 
            sqlCon.Close(); 
            return new { Result= datas, Count= datas.Count }; 
        } 
 
        public string SaveToTable(string value, string fieldName, string key) 
        { 
            SqlConnection sqlCon = new SqlConnection(connectionString); 
            sqlCon.Open(); 
            SqlCommand sqlComm = new SqlCommand("UPDATE [dbo].[Employees] SET " + fieldName + "=@field WHERE EmployeeID=" + key, sqlCon); 
            sqlComm.CommandTimeout = 0; 
            sqlComm.Parameters.AddWithValue("@field", value); 
            sqlComm.ExecuteNonQuery(); 
            sqlCon.Close(); 
            return "Saved succefully"; 
        } 
 
 
Could you please check the above details and get back to us, if you need any further assistance on this. 
 
Regards, 
Sangeetha M 




ES esayas May 7, 2021 11:39 AM UTC

Dear Sangeetha M
Greetings,
Great to hear from you to get the idea of this. 
I am in try whether sync fusion spreadsheet suit for my study, and actually now remain small work with a great effort and effect from you. For this I thank you cardinally and open my vision to use sync fusion spreadsheet my goal.
it bring's one error as shown below and please I need your help as usual. I was pend and stop my try in studying sync fusion spreadsheet due to covid-19 caught me.  

An error occurred while starting the application.


NullReferenceException: Object reference not set to an instance of an object. 
         

IMRRDIPF1.Startup.ConfigureServices(IServiceCollection services) in Startup.cs

  1.         public IConfiguration Configuration { get; }
  2.         // This method gets called by the runtime. Use this method to add services to the container.
  3.         public void ConfigureServices(IServiceCollection services)
  4.         {
  5.             string conn = Configuration.GetConnectionString("DefaultConnection");
  1.             if (conn.Contains("%CONTENTROOTPATH%"))
  1.             {
  2.                 conn = conn.Replace("%CONTENTROOTPATH%", _contentRootPath);
  3.             }
  4.             services.AddControllersWithViews();
  5.             services.AddDbContext<RelidbContext>(Options =>
  6.             Options.UseMySQL(Configuration.GetConnectionString("Relidbcontext")));

IMRRDIPF1.Program.Main(string[] args) in Program.cs

  1. namespace IMRRDIPF1
  2. {
  3.     public class Program
  4.     {
  5.         public static void Main(string[] args)
  6.         {
  1.             CreateHostBuilder(args).Build().Run();
  1.         }
  2.         public static IHostBuilder CreateHostBuilder(string[] args) =>
  3.             Host.CreateDefaultBuilder(args)
  4.                 .ConfigureWebHostDefaults(webBuilder =>
  5.                 {


kind regards;



SP Sangeetha Priya Murugan Syncfusion Team May 10, 2021 10:56 AM UTC

Hi esayas, 
 
Thank you for your update. 
 
We have checked your reported issue and the provided sample works properly in our end. For your convenience, we have prepared the video demonstration of this. Please find the link below. 
 
 
We suspect that your application doesn’t install the dependent package for ASP.NET Core 3.x version. So, please check the installed SDK version and packages in your end. For more details, please refer the below links. 
 
 
 
Could you please check the above links and get back to us, if you still facing the issue or need further assistance on this. 
 
Regards, 
Sangeetha M 



ES esayas May 11, 2021 09:31 AM UTC

Thank you I get the problem due to default connection string link not included. 
try to check and fix 
1. server name changed to 
         "DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDBFilename=%CONTENTROOTPATH%   \\App_Data\\NORTHWND.MDF;Trusted_Connection=true;MultipleActiveResultSets=true", 

and this is working. But How I connect to MySQL database instead off \\App_Data\\NORTHWND.MDF
  
2.  created="createdHandler", not defined 
3. "https://localhost:44384/home/SaveToTable" run on the chrome URL , display the following error 


An unhandled exception occurred while processing the request.

SqlException: Incorrect syntax near "=".

System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

  • SqlException: Incorrect syntax near "=".

    • System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

    • System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

    • System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool callerHasConnectionLock, bool asyncClose)

    • System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, out bool dataReady)

    • System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, string resetOptionsString)

    • System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async, int timeout, out Task task, bool asyncWrite, SqlDataReader ds)

    • System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, TaskCompletionSource < object > completion, int timeout, out Task task, bool asyncWrite, string method)

    • System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource < object > completion, bool sendToPipe, int timeout, bool asyncWrite, string methodName)

    • System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

    • IMRRDIPF1.Controllers.HomeController.SaveToTable(string value, string fieldName, string key) in HomeController.cs

      1.             sqlComm.ExecuteNonQuery();
    • lambda_method2(Closure , object , object[] )




SP Sangeetha Priya Murugan Syncfusion Team May 12, 2021 10:43 AM UTC

Hi esayas, 
 
Thank you for your update. 
 
We have checked your reported issue and we suspect that it is related to Sql connectivity related issue in your application. As we have update previously, our sample works properly in our end, if you don’t need to customize the spreadsheet in created event you can remove this in your application. For more details, please refer the below links. 
 
 
Please refer below link for Sql connectivity 
 
 
 
Could you please check the above details and get back to us, if you need any further assistance on this. 
 
Regards, 
Sangeetha M 



ES esayas May 25, 2021 06:31 AM UTC

Dear Sangeetha M
Greetings,
Thank you for the unreserved help, and checked all provided link.
The problem persists for the code:

SqlCommand sqlComm = new SqlCommand("UPDATE [dbo].[Employees] SET " + fieldName + "=@field WHERE EmployeeID=" + key, sqlCon);



error displayed 

SqlException: Incorrect syntax near '='.


latest error :

MySqlException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=NULL WHERE Aircraft_msn_Id=' at line 1



line of the error:

IMRRDIPF1.Controllers.HomeController.SaveToTable(string value, string fieldName, string key) in HomeController.cs

  1. sqlComm.ExecuteNonQuery();
Please I need your help as usual.
Best Regards;




SP Sangeetha Priya Murugan Syncfusion Team May 25, 2021 06:44 AM UTC

Hi esayas, 
 
Thank you for your update. 
 
Please follow the incident ticket (“329502”) for further updates. 
 
Regards, 
Sangeetha M 



ES esayas May 25, 2021 11:03 AM UTC

DearSangeetha M
greetings,
not found incident ticket (“329502”)
kind regards;


SP Sangeetha Priya Murugan Syncfusion Team May 25, 2021 11:07 AM UTC

 
Thank you for your update. 
 
Please find the ticket (“329502”) link below for further updates. 
 
 
Regards, 
Sangeetha M 



ES esayas May 27, 2021 08:03 AM UTC

DearSangeetha M
greetings,
Thank you for your reply and that was access deniable. please tell me what I should do. the issue fixed using event.preventdefault() and try, catch. thank you. 
Is it possible to get inserting jquery and C# code with similar to the above for new data insert to the mysql database. 
kind regards;


SP Sangeetha Priya Murugan Syncfusion Team May 28, 2021 01:58 PM UTC

HI esayas, 
 
Thank you for your update. 
 
We have checked your reported requirement and we would like to let you know that, we have resolved the access denied issue while accessing the support ticket in our end. Meanwhile, we have modified our sample that uses jQuery for post function as like as below. In this we have send the whole modified JSON data into the server with newly added row data (Insert command) to save the modified changes in database in button click event. 
 
Code Example: 
 
 
     document.getElementById('save').addEventListener('click', function () { 
        var ssObj = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet'); 
        json = []; 
        var obj = {}; 
        var ssObj = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet'); 
        var usedRange = ssObj.getActiveSheet().usedRange; 
        var selIndex = [1, 0, usedRange.rowIndex, usedRange.colIndex]; 
        var range = 
            ssObj.getActiveSheet().name + 
            "!" + 
            ejs.spreadsheet.getRangeAddress([1, 0, selIndex[2] - 1, selIndex[3]]); 
        ssObj.getData(range).then( 
            (value) => { 
                (value).forEach( 
                    (cell, key) => { 
                        if (cell) { 
                            // constructing the key value object 
                            var indexes = ejs.spreadsheet.getRangeIndexes(key); 
                            if (key.indexOf("A") > -1) { 
                                obj["employeeID"] = cell.value; 
                            } else if (key.indexOf("B") > -1) { 
                                obj["lastName"] = cell.value; 
                            } else if (key.indexOf("C") > -1) { 
                                obj["firstName"] = cell.value; 
                            } else if (key.indexOf("D") > -1) { 
                                obj["title"] = cell.value; 
                            } else if (key.indexOf("E") > -1) { 
                                obj["titleOfCourtesy"] = cell.value; 
                            } 
                            if (indexes[1] === selIndex[3]) { 
                                // row last index 
                                json.push(obj); 
                                obj = {}; 
                            } 
 
                        } 
                    } 
                ); 
                console.log(json); 
                var formData = new FormData(); 
                formData.append('JSONData', JSON.stringify(json)); 
 
                $.ajax({ 
                    type: "POST", 
                    data: { JSONData: JSON.stringify(json) }, 
                    url: https://localhost:44355/Home/SaveChangesToDatabase, 
                    success: function (data) { 
                        console.log(data); 
                    } 
                }); 
 
            } 
        ); 
 
    }); 
 
public object LoadFromTable() 
        { 
            List<EmployeeData> datas = new List<EmployeeData>(); 
            SqlConnection sqlCon = new SqlConnection(connectionString); 
            SqlCommand sqlComm = new SqlCommand("SELECT * FROM [dbo].[Employees]", sqlCon); 
            sqlCon.Open(); 
            SqlDataReader sqlDR = sqlComm.ExecuteReader(); 
            while (sqlDR.Read()) 
            { 
                EmployeeData data = new EmployeeData(); 
                data.employeeID = (int)sqlDR.GetValue(0); 
                data.lastName = sqlDR.GetValue(1).ToString(); 
                data.firstName = sqlDR.GetValue(2).ToString(); 
                data.title = sqlDR.GetValue(3).ToString(); 
                data.titleOfCourtesy = sqlDR.GetValue(4).ToString(); 
                datas.Add(data); 
            } 
            sqlCon.Close(); 
            return new { Result= datas, Count= datas.Count }; 
        } 
 
        [AcceptVerbs("Post")] 
        public string SaveChangesToDatabase(string JSONData) 
        { 
            JavaScriptSerializer serialize = new JavaScriptSerializer(); 
            List<EmployeeData> editedData = serialize.Deserialize<List<EmployeeData>>(JSONData); 
            SqlConnection sqlCon = new SqlConnection(connectionString); 
            sqlCon.Open(); 
            SqlCommand sqlComm = new SqlCommand("SET IDENTITY_INSERT Employees ON", sqlCon); 
            sqlComm.ExecuteNonQuery(); 
            for (int i = 0; i < editedData.Count; i++) 
            { 
    
                var order = editedData[i]; 
                SqlCommand selectComm = new SqlCommand("SELECT * FROM [dbo].[Employees] WHERE [EmployeeID] = '" + order.employeeID + "'", sqlCon); 
                var hasFileInDB = selectComm.ExecuteScalar(); 
                if (hasFileInDB == null) 
                { 
                    // insert newly inserted row data in database. 
                    sqlComm = new SqlCommand("INSERT INTO [dbo].[Employees]([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy]) VALUES (@EmployeeID, @LastName, @FirstName, @Title, @TitleOfCourtesy)", sqlCon); 
                    sqlComm.Parameters.AddWithValue("@LastName", order.lastName); 
                    sqlComm.Parameters.AddWithValue("@FirstName", order.firstName); 
                    sqlComm.Parameters.AddWithValue("@Title", order.title); 
                    sqlComm.Parameters.AddWithValue("@TitleOfCourtesy", order.titleOfCourtesy); 
                    sqlComm.ExecuteNonQuery(); 
                } 
                else 
                { 
                    SqlCommand updateComm = new SqlCommand("UPDATE [dbo].[Employees] SET LastName=@LastName, FirstName=@FirstName, Title=@Title, TitleOfCourtesy=@TitleOfCourtesy WHERE EmployeeID=@EmployeeID", sqlCon); // Update edited data to DB. 
                    updateComm.CommandTimeout = 0; 
                    updateComm.Parameters.AddWithValue("@EmployeeID", order.employeeID); 
                    updateComm.Parameters.AddWithValue("@LastName", order.lastName); 
                    updateComm.Parameters.AddWithValue("@FirstName", order.firstName); 
                    updateComm.Parameters.AddWithValue("@Title", order.title); 
                    updateComm.Parameters.AddWithValue("@TitleOfCourtesy", order.titleOfCourtesy); 
                    updateComm.ExecuteNonQuery(); 
                } 
            } 
            sqlCon.Close(); 
            return "Successfully updated"; 
        } 
 
Please find the link below. 
 
 
Could you please check the above details and get back to us, if you need any further assistance on this. 
 
Regards, 
Sangeetha M 



ES esayas May 29, 2021 02:14 PM UTC

Dear Sangeetha M,
Greetings,
Thank you cardinally , and I will check and update you. 
If I am confident to work on this project, then the next is to plan to convince my team to use your tools and support. 
Best Regards;


SP Sangeetha Priya Murugan Syncfusion Team May 31, 2021 06:12 AM UTC

Hi esayas, 
 
Thank you for your update, we will wait to hear from you. 
 
Regards, 
Sangeetha M 



ES esayas June 3, 2021 01:59 PM UTC

Dear Sangeetha M ,

Greetings,
thank you for the result and I am also highly want to work this 
I can't insert latest and updated data to the database.
My database is MYSQL at localhost, and yours is MDF in the App_Data.

here is below error displayed while inspect at chrome