简体   繁体   中英

Excel does not have updated values using oledb c#

I am new to C# and trying to write values to an excel file using OLEDB. The problem here is the first time if there is no excel file present in that location it works fine and prints the value to excel, but the second time if the excel is present it does not overwrite or write a new value to the excel. I also need to run this in a loop as I have four rows to print and not one. Need help with this.

This is my code snippet and I know I it has code for only one row to print but I don't know the place to add the loop :

            try
        {

            var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyLearn\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
            var sqlText = "CREATE TABLE TimeData ([HH] INT, [MM] INT,[AM / PM] VARCHAR(10))";

            using (var excelConnection = new OleDbConnection(connectionString))
            {


                // data is an object so it works with DBNull.Value
                object HHValue = TimeInHH.Text;
                object MMValue = TimeInMM.Text;
                object AMPMValue = Combo1AMPM.Text;




                // Executing this command will create the worksheet inside of the workbook
                // the table name will be the new worksheet name
                using (var command = new OleDbCommand(sqlText, excelConnection))
                {
                    if (excelConnection.State != ConnectionState.Open) {
                        excelConnection.Open();
                        command.ExecuteNonQuery();
                    }
                }

                // Add (insert) data to the worksheet
                var commandText = $"Insert Into TimeData ([HH], [MM], [AM / PM]) Values (@PropertyOne, @PropertyTwo, @PropertyThree)";

                using (var command = new OleDbCommand(commandText, excelConnection))
                {
                    // We need to allow for nulls just like we would with
                    // sql, if your data is null a DBNull.Value should be used
                    // instead of null 
                    command.Parameters.AddWithValue("@PropertyOne", HHValue ?? DBNull.Value);
                    command.Parameters.AddWithValue("@PropertyTwo", MMValue ?? DBNull.Value);
                    command.Parameters.AddWithValue("@PropertyThree", AMPMValue ?? DBNull.Value);
                    command.ExecuteNonQuery();
                }
            }


        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }

This is the screen which I am capturing data from and would like to print on excel on click of Submit button. 在此处输入图片说明

You need to check if table already exist , If yes , then simply go for adding records.

Here is a working example

        try
        {
            var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyLearn\ExcelWorkBook.xls;Extended Properties=Excel 8.0";

            var sqlText = "CREATE TABLE TimeData ([HH] INT, [MM] INT,[AM / PM] VARCHAR(10))";

            using (var excelConnection = new OleDbConnection(connectionString))
            {
                object HHValue = TimeInHH.Text;
                object MMValue = TimeInMM.Text;
                object AMPMValue = Combo1AMPM.Text;

                // Executing this command will create the worksheet inside of the workbook
                // the table name will be the new worksheet name
                using (var command = new OleDbCommand(sqlText, excelConnection))
                {
                    if (excelConnection.State != ConnectionState.Open)
                    {
                        excelConnection.Open();
                        //check if table already exists.
                        var exists = excelConnection.GetSchema("Tables", new string[4] { null, null, "TimeData", "TABLE" }).Rows.Count > 0;

                        if(!exists)
                           command.ExecuteNonQuery();
                    }
                }

                // Add (insert) data to the worksheet
                var commandText = $"Insert Into TimeData ([HH], [MM], [AM / PM]) Values (@PropertyOne, @PropertyTwo, @PropertyThree)";

                using (var command = new OleDbCommand(commandText, excelConnection))
                {
                    // We need to allow for nulls just like we would with
                    // sql, if your data is null a DBNull.Value should be used
                    // instead of null 
                    command.Parameters.AddWithValue("@PropertyOne", HHValue ?? DBNull.Value);
                    command.Parameters.AddWithValue("@PropertyTwo", MMValue ?? DBNull.Value);
                    command.Parameters.AddWithValue("@PropertyThree", AMPMValue ?? DBNull.Value);
                    command.ExecuteNonQuery();
                }
            }


        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM