将Excel加载到没有标题的数据表中

时间:2015-10-23 16:30:18

标签: c# sql xlsx import-from-excel

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

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


    }

1 个答案:

答案 0 :(得分:0)

我使用do而不是while而我的问题得到了解决。因为datareader只在Forward Direction中工作,所以在调用while循环时,它已经移动了i ++,当我们将它写入服务器时,它会写入第二行。