【问题标题】:importing excel to sql c#将excel导入sql c#
【发布时间】:2015-07-23 17:04:47
【问题描述】:

我一直在尝试将 excel 表导入我的 sql 数据库。我试过这个例子:

     void importdata(string excelfilepath)
     {
        //declare variables - edit these based on your particular situation
        string ssqltable = "tTableExcel";
        // make sure your sheet name is correct, here sheet name is sheet1,      so you can change your sheet name if have
        string myexceldataquery = "select student,rollno,course from [sheet1$]";
        try
        {
           //create our connection strings
           string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath +
           ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
           string ssqlconnectionstring = "server=mydatabaseservername;userid=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";


           string sclearsql = "delete from " + ssqltable;
           SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
           SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
           sqlconn.Open();
           sqlcmd.ExecuteNonQuery();
           sqlconn.Close();
           //series of commands to bulk copy data from the excel file into our sql table

           OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
           OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
           oledbconn.Open();
           OleDbDataReader dr = oledbcmd.ExecuteReader();
           SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
           bulkcopy.DestinationTableName = ssqltable;
           while (dr.Read())
           {
              bulkcopy.WriteToServer(dr);
           }

           oledbconn.Close();
        }
        catch (Exception ex)
        {
           //handle exception
        }
     }

我的编程不是很好,我无法让它工作。 SQL连接没有问题(运行程序后db被清除)。但我无法将任何信息输入数据库。 我的 excel 文件名为 test.xlsx,存储在 D:\Users\Haners 中。我的数据库表名为 Test。如何让我的程序将excel文件中的信息导入数据库???

【问题讨论】:

  • 插入数据库时​​是否收到任何错误通知?
  • 你试过SSMS中的导入向导吗?
  • 还要从源 Excel 中验证工作表名称。

标签: c# sql-server excel


【解决方案1】:

以前的代码:

       SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
       bulkcopy.DestinationTableName = ssqltable;
       while (dr.Read())
       {
          bulkcopy.WriteToServer(dr);
       }

新代码:

       SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
       bulkcopy.DestinationTableName = ssqltable;
       bulkcopy.BatchSize=100;
       bulkcopy.WriteToServer(dr);

希望这有助于解决您的问题。快乐编码。干杯

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多