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

问题描述 投票:1回答:1

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

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到已知的托管提供程序本机类型不存在映射

.net sql-server excel c#-4.0
1个回答
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);
        }
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.