上载Excel工作表并将数据导入SQL Server数据库

我正在开发这个简单的应用程序来上传Excel文件( .xlsx )并将该Excel工作表中的数据导入.NET中的SQL Server Express数据库

我在浏览并选择要执行此操作的文件后单击导入按钮时使用以下代码。

 protected void Button1_Click(object sender, EventArgs e) { String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True"; //file upload path string path = FileUpload1.PostedFile.FileName; //string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx"; //Create connection string to Excel work book string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False"; //Create Connection to Excel work book OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); //Create OleDbCommand to fetch data from Excel OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection); excelConnection.Open(); OleDbDataReader dReader; dReader = cmd.ExecuteReader(); SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection); //Give your Destination table name sqlBulk.DestinationTableName = "Excel_table"; sqlBulk.WriteToServer(dReader); excelConnection.Close(); } 

但是当我使用时,代码不会运行

 string path = FileUpload1.PostedFile.FileName;` 

乃至

 string path="C:\ Users\ Hemant\Documents\example.xlsx";` 

dReader无法以此格式获取路径。

它只能采用以下格式的路径

 string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx"; 

即在路径中使用\\ 。我必须对路径进行硬编码,但我们必须浏览文件。

那么,任何人都可以建议一个解决方案来使用FileUpload1导入数据的路径吗?

你正在处理一个HttpPostedFile; 这是“上传”到Web服务器的文件。 你真的需要在某处保存该文件然后使用它,因为…

…在您的实例中,恰好是您在文件所在的同一台计算机上托管您的网站,因此可以访问该路径。 只要将站点部署到其他计算机,代码就无法运行。

将其分解为两个步骤:

1)将文件保存在某个地方 – 这很常见:

 string saveFolder = @"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files string filePath = Path.Combine(saveFolder, FileUpload1.FileName); FileUpload1.SaveAs(filePath); 

现在,您可以在本地使用您的文件,并且可以完成真正的工作。

2)从文件中获取数据。 您的代码应该按原样运行,但您可以这样简单地编写连接字符串:

 string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath); 

然后,您可以考虑删除刚刚上传和导入的文件。

为了提供更具体的示例,我们可以将您的代码重构为两种方法:

  private void SaveFileToDatabase(string filePath) { String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True"; String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath); //Create Connection to Excel work book using (OleDbConnection excelConnection = new OleDbConnection(excelConnString)) { //Create OleDbCommand to fetch data from Excel using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection)) { excelConnection.Open(); using (OleDbDataReader dReader = cmd.ExecuteReader()) { using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection)) { //Give your Destination table name sqlBulk.DestinationTableName = "Excel_table"; sqlBulk.WriteToServer(dReader); } } } } } private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl) { string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName); fileUploadControl.SaveAs(filePath); return filePath; } 

您可以简单地调用SaveFileToDatabase(GetLocalFilePath(@"C:\temp\uploads", FileUpload1));

请考虑查看Excel连接字符串的其他扩展属性 。 他们有用!

您可能想要做的其他改进包括将Sql Database连接字符串放入config,并添加适当的exception处理。 请考虑此示例仅供演示!

不知道为什么文件路径不起作用,我有一些类似的代码可以正常工作。 但如果有两个“\”它可以工作,你可以随时做path = path.Replace(@"\", @"\\");

尝试使用
string filename = Path.GetFileName(FileUploadControl.FileName);

然后使用以下命令将文件保存在指定位置:FileUploadControl.PostedFile.SaveAs(strpath + filename);

您可以将OpenXml SDK用于* .xlsx文件。 它工作得非常快。 我为这个sdk做了简单的C#IDataReader实现。 看到这里 。 现在,您可以使用SqlBulkCopy轻松将excel文件导入sql server数据库。 它使用小内存,因为它通过SAX(Simple API for XML)方法读取(OpenXmlReader)

例:

 private static void DataReaderBulkCopySample() { using (var reader = new ExcelDataReader(@"test.xlsx")) { var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray(); DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols); using (var bulkCopy = new SqlBulkCopy(ConnectionString)) { // MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess, // optimizing memory usage by using the IDataReader streaming capabilities bulkCopy.EnableStreaming = true; bulkCopy.DestinationTableName = TableName; foreach (var col in cols) bulkCopy.ColumnMappings.Add(col, col); bulkCopy.WriteToServer(reader); } } } 
  public async Task PostFormDataAsync() //async is used for defining an asynchronous method { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var fileLocation = ""; string root = HttpContext.Current.Server.MapPath("~/App_Data"); MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root); //Helps in HTML file uploads to write data to File Stream try { // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it fileLocation = file.LocalFileName + filePath; //Complete file location } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus); return response; } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } public void ReadFromExcel() { try { DataTable sheet1 = new DataTable(); OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder(); csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0"; csbuilder.DataSource = fileLocation; csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES"); string selectSql = @"SELECT * FROM [Sheet1$]"; using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString)) using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection)) { connection.Open(); adapter.Fill(sheet1); } } catch (Exception e) { Console.WriteLine(e.Message); } } 
 A proposed solution will be: protected void Button1_Click(object sender, EventArgs e) { try { CreateXMLFile(); SqlConnection con = new SqlConnection(constring); con.Open(); SqlCommand cmd = new SqlCommand("bulk_in", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@account_det", sw_XmlString.ToString ()); int i= cmd.ExecuteNonQuery(); if(i>0) { Label1.Text = "File Upload successfully"; } else { Label1.Text = "File Upload unsuccessfully"; return; } con.Close(); } catch(SqlException ex) { Label1.Text = ex.Message.ToString(); } } public void CreateXMLFile() { try { M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); fileExtn = Path.GetExtension(M_Filepath); strGuid = System.Guid.NewGuid().ToString(); fNameArray = M_Filepath.Split('.'); fName = fNameArray[0]; xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-'); fileName = xlRptName.Trim() + fileExtn.Trim() ; FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName); strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ; if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX")) { Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX"; } FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName); lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName; if (strFileName == "DEMO.XLS") { strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'"; } if (strFileName == "DEMO.XLSX") { strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'"; } strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]"; OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn); mydata.TableMappings.Add("Table", "arul"); mydata.Fill(dsExcl); dsExcl.DataSetName = "DocumentElement"; intRowCnt = dsExcl.Tables[0].Rows.Count; intColCnt = dsExcl.Tables[0].Rows.Count; if(intRowCnt <1) { Label1.Text = "No records in Excel File"; return; } if (dsExcl==null) { } else if(dsExcl.Tables[0].Rows.Count >= 1000 ) { Label1.Text = "Excel data must be in less than 1000 "; } for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++) { if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"])) { strValid = ""; } else { strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString(); } if (strValid == "") { Label1.Text = "Name should not be empty"; return; } else { strValid = ""; } if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"])) { strValid = ""; } else { strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString(); } if (strValid == "") { Label1.Text = "Mobile_num should not be empty"; } else { strValid = ""; } if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"])) { strValid = ""; } else { strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString(); } if (strValid == "") { Label1.Text = "Account_number should not be empty"; } else { strValid = ""; } if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"])) { strValid = ""; } else { strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString(); } if (strValid == "") { Label1.Text = "Amount should not be empty"; } else { strValid = ""; } if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"])) { strValid = ""; } else { strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString(); } if (strValid == "") { Label1.Text = "date_a2 should not be empty"; } else { strValid = ""; } } } catch { } try { if(dsExcl.Tables[0].Rows.Count >0) { dr = dsExcl.Tables[0].Rows[0]; } dsExcl.Tables[0].TableName = "arul"; dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema); } catch { } }`enter code here` 
  protected void btnUpload_Click(object sender, EventArgs e) { if (Page.IsValid) { bool logval = true; if (logval == true) { String img_1 = fuUploadExcelName.PostedFile.FileName; String img_2 = System.IO.Path.GetFileName(img_1); string extn = System.IO.Path.GetExtension(img_1); string frstfilenamepart = ""; frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ; UploadExcelName.Value = frstfilenamepart + extn; fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value); string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value; GetExcelSheetForEmp(PathName, UploadExcelName.Value); } } } private void GetExcelSheetForEmp(string PathName, string UploadExcelName) { string excelFile = "EmpExcel/" + PathName; OleDbConnection objConn = null; System.Data.DataTable dt = null; try { DataSet dss = new DataSet(); String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName; objConn = new OleDbConnection(connString); objConn.Open(); dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (dt == null) { return; } String[] excelSheets = new String[dt.Rows.Count]; int i = 0; foreach (DataRow row in dt.Rows) { if (i == 0) { excelSheets[i] = row["TABLE_NAME"].ToString(); OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn); OleDbDataAdapter oleda = new OleDbDataAdapter(); oleda.SelectCommand = cmd; oleda.Fill(dss, "TABLE"); } i++; } grdByExcel.DataSource = dss.Tables[0].DefaultView; grdByExcel.DataBind(); } catch (Exception ex) { ViewState["Fuletypeidlist"] = "0"; grdByExcel.DataSource = null; grdByExcel.DataBind(); } finally { if (objConn != null) { objConn.Close(); objConn.Dispose(); } if (dt != null) { dt.Dispose(); } } }