maztt
maztt

Reputation: 12304

c# excel insert checking if the sheet exist

   using (DbCommand command = oconn.CreateCommand())
                {
                    command.CommandText = "CREATE TABLE [Sheet2$] (F1 number, F2 char(255), F3 char(128))";
                    command.ExecuteNonQuery();
                    for (int i = 1; i <= 20; i++)
                    {
                        //now we insert the values into the existing sheet...no new sheet is added.
                        command.CommandText = "INSERT INTO [Sheet2$] (F1, F2, F3) VALUES(1,\"Fake Record\",\"Fake Record\")";
                        command.ExecuteNonQuery();
                    }
                }

I am using this code to insert some records in excel file sheet . What i want to do is to see if for example Sheet1 is there then create sheet 2 and insert these records there . and if it only finds sheet 3 then i want to create another sheet4 and insert the records there and so on. how can i do this?

Upvotes: 1

Views: 1706

Answers (2)

tiru
tiru

Reputation: 789

The same solution we can find here: https://mudassarkhan.wordpress.com/tag/c-excel/

Upvotes: 0

Asken
Asken

Reputation: 8081

Try to check the tables of the data schema:

DataTable dtSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

DataRow[] dr = dtSchema.Select("TABLE_NAME = 'Sheet1$'");

bool exist = dr == null || dr.Length == 0;

Upvotes: 5

Related Questions