C# 如何将Excel文件第6行中的数据读入SQL Server?

C# 如何将Excel文件第6行中的数据读入SQL Server?,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我想从Excel文件的第6行导入数据。Excel的第1到第5行有标题。导入数据时,该值为null,因为Excel第二行中没有任何数据 conString = string.Format(conString, excelPath); using (OleDbConnection excel_con = new OleDbConnection(conString)) { excel_con.Open(); string sheet1 = excel_con.GetOleDbSch

我想从Excel文件的第6行导入数据。Excel的第1到第5行有标题。导入数据时,该值为null,因为Excel第二行中没有任何数据

conString = string.Format(conString, excelPath);

using (OleDbConnection excel_con = new OleDbConnection(conString))
{
    excel_con.Open();

    string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
    DataTable dtExcelData = new DataTable();

    //[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
    dtExcelData.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
    new DataColumn("Name", typeof(int)),
    new DataColumn("Salary",typeof(decimal)) });

    using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
    {
        oda.Fill(dtExcelData);
    }

    excel_con.Close();

    string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    using (SqlConnection con = new SqlConnection(consString))
    {
        using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
        {
            //Set the database table name
            sqlBulkCopy.DestinationTableName = "dbo.tblPerson";

            //[OPTIONAL]: Map the Excel columns with that of the database table
            sqlBulkCopy.ColumnMappings.Add("Id", "PersonId");
            sqlBulkCopy.ColumnMappings.Add("Name", "Name");
            sqlBulkCopy.ColumnMappings.Add("Salary", "Salary");

            con.Open();
            sqlBulkCopy.WriteToServer(dtExcelData);
            con.Close();
        }
    }
}

您可以在dtExcelData中逐行插入数据,而不是批量复制

   for (int i = 0; i < dtExcelData.Rows.Count; i++)
     {
        sql = sql + "insert into your_table_name (PersonId, Name, Salary) values('"
              + dtExcelData.Rows[i]["Id"].ToString().Trim() + "','"
              + dtExcelData.Rows[i]["Name"].ToString().Trim() + "','" 
              + dtExcelData.Rows[i]["Salary"].ToString().Trim() + "')";
    //execute the sql here in try catch
     }
for(int i=0;i
我正在尝试这个。使用(OleDbDataAdapter oda=新的OleDbDataAdapter(“从[“+sheet1+”$“+”A7:ZZ]”,excel_-con中选择*){oda.Fill(dtExcelData);}excel_-con.Close();但由于Microsoft Office Access数据库引擎找不到对象“Sheet1$$A7:ZZ”,因此出现错误。确保对象存在,并且正确拼写其名称和路径名。我找到了解决方案。我刚刚在使用时更改了代码(OleDbDataAdapter oda=新的OleDbDataAdapter(“从[“+sheet1+”A6:F]”中选择*,excel_-con))