将其分解为两个步骤:
1) 将文件保存在某处 - 很常见:
string saveFolder = @"C:\temp\uploads"; //在你的机器上选择一个文件夹来存放上传的文件
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 数据库连接字符串放入配置中,并添加适当的异常处理。请考虑此示例仅用于演示!