Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Insert Rows to Table Object Inside an Excel Sheet?

I have difficulties trying to insert rows into an existing table object. Here is my code snippet:

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + @"C:\myExcelFile.xlsx" + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
    conn.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = conn;

    string insertQuery = String.Format("Insert into [{0}$] (ID, Title,NTV_DB, Type ) values(7959, 8,'e','Type1')", TabDisplayName);
    cmd.CommandText = insertQuery;
    cmd.ExecuteNonQuery();
    cmd = null;
    conn.Close();
}

As a result I get my rows inserted below a ready-made table object:

enter image description here

I've also tried inserting data inside a table object like so:

 string insertQuery = String.Format("Insert into [{0}$].[MyTable] (ID, Title,NTV_DB, Type ) values(7959, 8,'e','Type1')", TabDisplayName);

But I get an error:

The Microsoft Access database engine could not find the object 'MyTable'. Make sure the object exists and that you spell its name and the path name correctly. If 'MyTable' is not a local object, check your network connection or contact the server administrator.

As you can see, table with a name MyTable does exist. I would be very grateful if someone can shed some light on this mystery.

enter image description here

like image 472
Denis Molodtsov Avatar asked Dec 18 '14 19:12

Denis Molodtsov


People also ask

How do I add a row to a data table in Excel?

To insert a row, pick a cell or row that's not the header row, and right-click. To insert a column, pick any cell in the table and right-click. Point to Insert, and pick Table Rows Above to insert a new row, or Table Columns to the Left to insert a new column.

Why can't I add a row to a table in Excel?

You have probably inadvertently entered something in the last row of the worksheet and hence you "can't insert new cells because it would push non-empty cells off the end of the worksheet". Select the entire row (click on the row number at the left). Hold both the Shift and Control keys.

Can you add a table within a cell in Excel?

In a word, no, you can't. Even if you set a cell to be equal to the entire range on the table and set it to an array formula via Ctrl+Shift+Enter (for example: ={A1:B10} ) that cell would still evaluate to the top-left value of the table when used in formulas.


2 Answers

If you are using the Microsoft.ACE.OLEDB provider, then be aware that it doesn't support a named range. You need to provide the name of the sheet [Sheet1$] or the name of the sheet followed by the range [Sheet1$A1:P7928]. If the range is not provided, it will then define the table as the used range, which may contains empty rows.

One way to deal with empty rows would be to delete them, but the driver doesn't support the DELETE operation.

Another way is to first count the number of rows with a non empty Id and then use the result to define the range of the table for the INSERT statement:

using (OleDbConnection conn = new OleDbConnection(connectionString)) {
    conn.Open();

    string SheetName = "Sheet1";
    string TableRange = "A1:P{0}";

    // count the number of non empty rows
    using (var cmd1 = new OleDbCommand(null, conn)) {
        cmd1.CommandText = String.Format(
          "SELECT COUNT(*) FROM [{0}$] WHERE ID IS NOT NULL;"
          , SheetName);

        TableRange = string.Format(TableRange, (int)cmd1.ExecuteScalar() + 1);
    }

    // insert a new record
    using (var cmd2 = new OleDbCommand(null, conn)) {
        cmd2.CommandText = String.Format(
            "INSERT INTO [{0}${1}] (ID, Title, NTV_DB, Type) VALUES(7959, 8,'e','Type1');"
            , SheetName, TableRange);

        cmd2.ExecuteNonQuery();
    }
}
like image 120
Florent B. Avatar answered Oct 08 '22 01:10

Florent B.


If you execute this code:

var contents = new DataTable();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(string.Format("Select * From [{0}$]", TabDisplayName), conn))
{
    adapter.Fill(contents);
}
Console.WriteLine(contents.Rows.Count);//7938

you will see 7938 (last row number on your screenshot). And when you insert new row, it inserted at 7939 position. Empty content in (7929, 7930, ...) rows are ignored, because excel knows that last number is 7938.

Solutions:

  1. You must delete all rows after 7928 in excel file.
  2. You must insert on specific position.
like image 35
Dmitrii Zyrianov Avatar answered Oct 07 '22 23:10

Dmitrii Zyrianov