使用asp.net将Excel数据导入sql数据库

时间:2014-07-30 07:05:00

标签: asp.net sql-server c#-4.0

string filepath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filepath);
string ext = Path.GetExtension(filename);
String strConnection = "Data Source=192.168.51.02;Initial Catalog=****;User   ID=*****;Password=*****;Integrated Security=True";
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=YES;IMEX=1;\"";

OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

OleDbCommand cmd = new OleDbCommand("Select [Emp ID],[Emp Name],[Log Date],[Logtime],[Type] from [One Month Report$]", excelConnection);
excelConnection.Open();

//cmd.ExecuteNonQuery();


//DataSet ds = new DataSet();
//SqlDataAdapter da = new SqlDataAdapter("Select [sno],[Name],[Designation] from [Sheet1$]", strConnection);

OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);

sqlBulk.DestinationTableName = "K_Master_EmpAttendanceDet";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();

我希望使用asp.net从excel导入数据到数据库。我试过这样但是我收到了这个错误:

  

用户登录失败。用户未与受信任的用户关联   SQL Server连接。

我的代码中是否需要任何Dll文件或任何错误。请帮助我。

1 个答案:

答案 0 :(得分:2)

Just Remove the "integrated security" part from your strConnection . Here your connection will use the windows authentication instead of the sql authentication.