将excel文件保存在应用程序文件夹中,并使用Windows窗体和C#将内容上传到SQL Server

我正在研究一个简单的应用程序,它需要浏览一个excel文件,并将其上传到SQL服务器,并将该文件复制到应用程序文件夹。 通过使用下面的代码,我可以在网上做到这一点。 但是Winform中没有其他的FileUpload工具。 下面是我试图在Windows窗体中复制的代码。

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(); dtExcelData.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Salary",typeof(decimal)) }); using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con)) { oda.Fill(dtExcelData); } excel_con.Close(); string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(consString)) { using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con)) { //Set the database table name sqlBulkCopy.DestinationTableName = "dbo.tblPersons"; sqlBulkCopy.ColumnMappings.Add("Id", "PersonId"); sqlBulkCopy.ColumnMappings.Add("Name", "Name"); sqlBulkCopy.ColumnMappings.Add("Salary", "Salary"); con.Open(); sqlBulkCopy.WriteToServer(dtExcelData); con.Close(); } } } } 

WinForm中FileUpload的replace是OpenFileDialog:

 string excelPath = ""; using(OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = "Excel(.xls)|*.xls|Excel(.xlsx)|*.xlsx|All Files (*.*)|*.*"; ofd.Multiselect = false; var result = ofd.ShowDialog(); if (result == DialogResult.OK) { excelPath = ofd.FileName; } } //... continue with your sql code 

上传到sql server的代码依然是一样的,你也可以在winform中使用它。 从上面的示例中,“excelPath”在我的示例“ofd.FileName”