【问题标题】:Insert data from Excel to Database using C#使用 C# 将数据从 Excel 插入数据库
【发布时间】:2026-01-21 13:25:01
【问题描述】:

大家好,我想从 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 到已知托管提供程序本机类型的映射

【问题讨论】:

  • (a) 请完成你的代码 sn-p :/ 至少平衡你的大括号。 (b) 解释问题是什么,描述出了什么问题。
  • 您好首先感谢您的回复。我已经编辑了我在 Visual Studio 中编写的内容。我已经尝试过上述逻辑来做到这一点。是的,存在一些错误,但我不知道如何编写逻辑以通过存储的过程将 excel 数据插入数据库。我需要将 3 列 excel 数据从存储过程中插入到表中
  • 现在请修复缩进,您的foreach 似乎不再在Main() 中?另外,请说明您收到错误的行以及问题中错误消息的全文。
  • 我在 ExecuteNonQuery iam 再次编辑 :) 收到此错误:不存在从对象类型 System.Data.Common.DataRecordInternal 到已知托管提供程序本机类型的映射。而且我不确定我写的逻辑是否正确,上面的代码在语法上是否正确??

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


【解决方案1】:

试试这个方法

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

【讨论】: