简体   繁体   中英

c# IExcelDataReadReader and a specific Sheet

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!");

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);
        }

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