C# 将excel文件保存在应用程序文件夹中,并使用windows窗体和C将内容上载到SQL Server#
我正在开发一个简单的应用程序,它需要浏览excel文件并将其上载到SQL server,还需要将文件复制到应用程序文件夹。通过使用下面的代码,我能够在web上完成它。但winforms中的FileUpload工具没有其他选择。下面是我试图在windows窗体中复制的代码C# 将excel文件保存在应用程序文件夹中,并使用windows窗体和C将内容上载到SQL Server#,c#,sql-server,excel,C#,Sql Server,Excel,我正在开发一个简单的应用程序,它需要浏览excel文件并将其上载到SQL server,还需要将文件复制到应用程序文件夹。通过使用下面的代码,我能够在web上完成它。但winforms中的FileUpload工具没有其他选择。下面是我试图在windows窗体中复制的代码 protected void Upload(object sender, EventArgs e) { //Upload and save the file string excelPath = Server.M
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中的文件上载替换为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”中相关:该主题与复制文件相关,我的问题是如何复制excel文件并将其保存到SQL server数据库。