2015-10-23 80 views
0

我在C#中编写了一个代码,用于将数据从excel复制到sql表中。问题在于它在将数据导入到sql表时跳过了前两行。如果我插入HDR =否,则只跳过第一行。我该如何解决这个问题,以免跳过任何行?将Excel加载到无标题数据表中

string excelfilepath = @"C:\Users\atola\Desktop\BS\ctest.xlsx"; 
     string ssqltable = "student"; 
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different 
string myexceldataquery = "select * from [sheet1$]"; 
try 
{ 
    //create our connection strings 
    string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1;'"; 


    string ssqlconnectionstring = "Data Source=MCKSQLDW1;Initial Catalog=AS400_Integration;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"; 
    //execute a query to erase any previous data from our destination table 
    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) 
     { 
      Console.WriteLine(ex.ToString()); 
     } 


    } 
+0

也许尝试在Excel中使用命名范围而不是表格名称。 – agileMike

+0

我无法使用范围,因为每次记录的数量都会有所不同 – user5480934

回答

0

我以前做的,而不是一段时间,我的问题得到了solved.Because DataReader的正向才能正常运行,所以当调用while循环,它已经移到我++,当我们把它写入服务器,将其写入第二排。