我試圖使用C#將ASP.NET從Excel導入200,000條記錄到SQL Server 2005。但是,當我嘗試瀏覽並導入文件時,只插入了幾條記錄(僅限於100條記錄)。我無法得到任何解決方案。我只能將少量記錄插入到SQL Server數據庫中
這裏是我的示例代碼
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class UploadExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
///***when the button press, this code will execute***
protected void Upload_Click(object sender, EventArgs e)
{
int count = 0;
try
{
string path = string.Concat(Server.MapPath("~/TempFiles/"), UploadExcel1.FileName);
//Save File as Temp then you can delete it if you want
UploadExcel1.SaveAs(path);
DataTable dtExcel = new DataTable();
string SourceConstr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0",path);
OleDbConnection con1 = new OleDbConnection(SourceConstr);
string query = "Select * from [Sheet1$]";
OleDbDataAdapter dataadapt = new OleDbDataAdapter(query,con1);
dataadapt.Fill(dtExcel);
///connection string with in the database below
string sqlconn = System.Configuration.ConfigurationManager.ConnectionStrings["zena"].ToString();
//all the excel file is stored in the data table here
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
try
{
SqlConnection sconn = new SqlConnection(sqlconn);
sconn.Open();
string insert_query12 = "insert into FCROperation (CallingNumber,OperatorId,OperatorName,CallReason) values("+dtExcel.Rows[i][0]+","+dtExcel.Rows[i][1]+",'"+dtExcel.Rows[i][2]+"','"+dtExcel.Rows[i][3]+"')";
SqlCommand cmd = new SqlCommand(insert_query12,sconn);
count+=cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//continue;
}
//Label1.Text = ex.Message;
}
if (count == dtExcel.Rows.Count)
{
Label1.Text = "Success" + dtExcel.Rows.Count + count;
}
else
{
Label1.Text = "Failed" + dtExcel.Rows.Count + count;
//Label1 = dtExcel.Rows.Count;
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
//throw ex;
}
finally
{
}
}
}
如果您的Excel單元格爲空,則必須應用DBNull.Value值。 –
親愛的謝謝你的寶貴支持,我的excel充滿了記錄,並有可能在表中插入空值。 – Sapna
您是如何確認僅插入100條記錄的?您是使用SELECT COUNT(*)還是使用右鍵單擊表並在編輯模式下打開?因爲在編輯模式下SSMS僅默認顯示100條記錄。 –