繁体   English   中英

导入Excel到SQL C#

[英]importing excel to sql c#

我一直在尝试将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连接没有问题(运行程序后将清除数据库)。 但是我无法将任何信息输入数据库。 我的excel文件称为test.xlsx,存储在D:\\ Users \\ Haners中。 我的数据库选项称为“测试”。 如何使我的程序将excel文件中的信息导入数据库?

先前的代码:

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

希望这可以解决您的问题。 快乐的编码。 干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM