c# IExcelDataReadReader and a specific Sheet

50 views Asked by At

I have a program that needs to read an excel file and write it to sql server.I am using IExcelDataReader and my code works as long as I have one worksheet. If I have another that for an example has some information that I don't need to insert,I can't specific a sheet that I need. I know that I should probably use NextRecord() somehow,but I can't make it work.

This is my code so far:

OpenFileDialog ope = new OpenFileDialog();
        ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
        if (ope.ShowDialog() == false)
            return;
        FileStream stream = new FileStream(ope.FileName, FileMode.Open);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        excelReader.IsFirstRowAsColumnNames = true;
        DataSet result = excelReader.AsDataSet();
        DataClasses1DataContext conn = new DataClasses1DataContext();

        foreach (DataTable table in result.Tables)
        {

            foreach (DataRow dr in dd.Rows)
            {

                Excel addTable = new Excel()
                {

                    id = Convert.ToInt32(dr[0]),
                    ime = Convert.ToString(dr[1])

                };

                conn.ExecuteCommand("TRUNCATE TABLE Excel");

                conn.Excels.InsertOnSubmit(addTable);

            }
        }

        conn.SubmitChanges();
        excelReader.Close();
        stream.Close();
        MessageBox.Show("success!");
1

There are 1 answers

0
Alexander On

I found the aswer.. in the foreach there should be only:

foreach (DataRow dr in result.Tables[0].Rows)
        {
            Excel addTable = new Excel()
            {


                ime = Convert.ToString(dr[1])

            };

            //   conn.ExecuteCommand("TRUNCATE TABLE Excel");
            conn.ExecuteCommand("DELETE FROM Excel where ime='a'");
            conn.Excels.InsertOnSubmit(addTable);
        }