使用C#将数据从Excel插入数据库

时间:2018-08-29 10:02:01

标签: .net sql-server excel c#-4.0

您好,我想从Excel插入数据。我在Excel Excela,Excelb,Excelc中有三列。这些值我想插入表存储过程中这是我的代码,请纠正我

static void Main(string[] args)
{
    string Path = @"D:\Angular\SIRStatus.xlsx";
    OleDbConnection connStr = new 
    OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=Excel 12.0;");
    OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", connStr);
    connStr.Open();
    DbDataReader dr = cmd.ExecuteReader();
    // I dont now how to proceed after this Below code i tried but it is not working Please help me here with this

    foreach (var PCN in dr)
    {
        while (dr.Read())
        {
            SqlConnection con = new SqlConnection("Data Source=SQL ZCTS;Initial Catalog=ReportsDB;user id=sa;Password=Sa@12345");
            SqlCommand cmd1 = new SqlCommand("Insert1", con);
            cmd1.CommandType = CommandType.StoredProcedure;
            cmd1.Parameters.AddWithValue("@PCN", PCN);
            con.Open();
            cmd1.ExecuteNonQuery(); 
         } 
     }
 }

最后一行给出此错误

  

不存在从对象类型System.Data.Common.DataRecordInternal到已知托管提供程序本机类型的映射

1 个答案:

答案 0 :(得分:0)

尝试此方法

 public static void SaveFileToDatabase(string filePath)
    {
        String strConnection = "SQL Connection";

        String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);

        using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
        {

            using (OleDbCommand cmd = new OleDbCommand("Select [A],[B],[C],[D] from [Plan1$]", excelConnection))
            {
                excelConnection.Open();
                using (OleDbDataReader dReader = cmd.ExecuteReader())
                {
                    using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                    {

                        sqlBulk.DestinationTableName = "Table in SQL";
                        sqlBulk.WriteToServer(dReader);
                    }
                }
            }
        }
    }

稍后您转到按钮(示例)并将其放置

            if (OpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            string directoryPath = OpenFileDialog.FileName;
            Excel.SaveFileToDatabase(directoryPath);
        }