C#将指定Excel工作表中的数据导入SQL Server

时间:2017-03-13 04:49:20

标签: c# sql-server excel

我有一些C#代码将Excel导入数据库,但它只能将第一张(Sheet1)中的数据导入SQL Server数据库。我想将数据从Excel文件的第二张(Sheet2)导入数据库。请修改代码,教我如何做到这一点。

private void button1_Click(object sender, EventArgs e)
{
        OpenFileDialog ope = new OpenFileDialog();
        ope.Filter = "Excel Files|*.xls;*.xlsx;*slsm";

        if (ope.ShowDialog() == DialogResult.Cancel)
            return;

        FileStream stream = new FileStream(ope.FileName, FileMode.Open);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

        DataSet result = excelReader.AsDataSet();
        DataClasses1DataContext conn = new DataClasses1DataContext();           

        foreach(DataTable table in result.Tables)
        {
            //Default start value of foreach statement is 0
            //Please tell me: How to count dr from 1 instead of 0???
            foreach (DataRow dr in table.Rows)
            {
                //if index of dr==1, then continue
                if (table.Rows.IndexOf(dr) == 0)
                {
                    continue;
                }

                test addtable = new test()
                {
                    id = Convert.ToInt32(dr[0]),
                    name = Convert.ToString(dr[1]),
                    surname = Convert.ToString(dr[2]),
                    age = Convert.ToInt32(dr[3])
                };

                conn.tests.InsertOnSubmit(addtable);
            }
        }

        conn.SubmitChanges();
        excelReader.Close();
        stream.Close();

        MessageBox.Show("Import table completed!");
}

1 个答案:

答案 0 :(得分:1)

假设您希望从电子表格 Sheet2 获取数据,这应该有效:

DataSet result = excelReader.AsDataSet();
while (excelReader.NextResult())
{
    if (excelReader.Name == "Sheet2")
    {
        result = excelReader.AsDataSet();
        break;
    }
}