我正在尝试将Excel
文件上传到SQL
数据库,并且在我的计算机上工作正常,但是一旦我上传到服务器,它就会给我这个错误:
异常详细信息:System.Data.OleDb.OleDbException:Microsoft Jet数据库引擎找不到对象'C:\ Windows \ SysWOW64 \ inetsrv \ Book1.xls'。确保对象存在,并且您正确拼写其名称和路径名称。
来源错误:
在执行当前Web请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常的起源和位置的信息。
这是我的代码:
protected void Button1_Click(object sender, EventArgs e) { string excelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'", FileUpload1.PostedFile.FileName); using (OleDbConnection connection = new OleDbConnection(excelConnectionString)) { OleDbCommand command = new OleDbCommand(("Select * FROM [Sheet1$]"), connection); connection.Open(); using (DbDataReader dr = command.ExecuteReader()) { using (SqlBulkCopy bulkCopy = new SqlBulkCopy("Data Source=WSCJTCSQ1;Initial Catalog=TestDB;Persist Security Info=True;User ID=test;Password=test")) { bulkCopy.DestinationTableName = "CoaTest"; bulkCopy.ColumnMappings.Add("First Name", "fName"); bulkCopy.ColumnMappings.Add("Last Name", "lName"); bulkCopy.ColumnMappings.Add("Agency", "agency"); bulkCopy.WriteToServer(dr); } } } Label1.ForeColor = System.Drawing.Color.Red; Label1.Text = "Successfully Uploaded The New Roster"; }
答案 0 :(得分:2)
string file = string.Format("{0}\\{1}", Request.PhysicalApplicationPath,
Guid.NewGuid().ToString().Replace("-",string.Empty));
FileUpload1.SaveAs(file)
现在在您的导入代码中
string excelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;
Data Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'", file);
答案 1 :(得分:0)
您需要在连接之前将文件保存在服务器上,例如:
string sServerFilespec = ("C:\\ServerFolder\\" + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName));
FileUpload1.PostedFile.FileName.SaveAs(sServerFilespec);