我正在尝试通过点击按钮从excel文件中读取数据,此文件在FileUpload1
控件的帮助下浏览,但在打开OleDbConnection
时我正在System.Data.OleDb.OleDbException
:“它已由其他用户专门打开,或者您需要获得查看和写入其数据的权限。”
下面的Web.config文件代码
<connectionStrings>
<add name ="Excel03ConString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>
<add name ="Excel07ConString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>
</connectionStrings>
我尝试的代码是:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string FilePath = Server.MapPath("~/Files/");
if (!Directory.Exists(FilePath))
{
//If Directory (Folder) does not exists. Create it.
Directory.CreateDirectory(FilePath);
}
FileUpload1.SaveAs(FilePath + Path.GetFileName(FileUpload1.FileName));
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
}
}
private void Import_To_Grid(string FilePath, string Extension, string isHDR)
{
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
.ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
.ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, isHDR);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
connExcel.Open();
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
//Bind Data to GridView
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
}
请提前帮助我帮助我。