我正在使用以下代碼將數據從excel導出到使用ASP.NET的SQL中。使用ASP.NET通過跳過n行將數據導入到SQL中使用ASP.NET
protected void Upload(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[3]
{
new DataColumn("ID", typeof(string)),
new DataColumn("Name", typeof(DateTime)),
new DataColumn("Designation",typeof(DateTime))});
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Employee";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("ID", "ID");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Designation", "Designation");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
的問題是,在我的Excel文件中的實際數據是從第7行 開頭,所以它不工作,但每當我將數據移動到第1行其取出並uploades在SQL數據就好了。 所以我想要的是在我的代碼中預先定義在Excel文件中從第7行中選擇數據。 另外一個查詢,我的SQL和Excel工作表的標題名稱是不同的,所以除非兩個標題都是相同的,否則它不會選擇數據,所以是否有可以保持標題不同並仍然獲取數據? 請幫忙,因爲我真的被困在這裏。
http://stackoverflow.com/questions/9713048/skip-first-row-in-read-of-excel-file – Kostis