0
下面的代碼在我第一次訪問文件以進行行計數時正常工作。但是,當我試圖打開相同的文件來讀取數據時,我在ExcelConnection.Open()上發生錯誤,它指出我沒有權限訪問該文件或者它已被使用。任何想到爲什麼該文件在第一次連接到它後沒有被釋放?通過OLDB連接到Excel時文件權限錯誤
public static DataSet GetExcelWorkSheet(string pathName, string fileName)
{
string fileExtention = System.IO.Path.GetExtension(fileName).ToLower();
OleDbConnection ExcelConnection = new OleDbConnection(fileExtention == ".xls" ?
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + @"\" + fileName + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;ReadOnly=true;\"" :
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + @"\" + fileName + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1;ReadOnly=true;\"");
OleDbCommand ExcelCommand = new OleDbCommand();
ExcelCommand.Connection = ExcelConnection;
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
// DataTable ExcelSheets = ExcelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataTable ExcelSheets = ExcelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string CheckSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
string SpreadSheetName;
int useMe = -1;
if (CheckSheetName.ToUpper() != "SHEET1$") // Ok, they have renamed things
{
if (CheckSheetName.Substring(0, 5).ToUpper() == "SHEET")
// if it does START with sheet then look for anything that
// DOES NOT start with sheet
{
for (int x = 0; x < ExcelSheets.Rows.Count; x++)
{
if (ExcelSheets.Rows[x]["TABLE_NAME"].ToString().Substring(0, 5).ToUpper() != "SHEET") // If is does not equal sheet then use it
{
useMe = x;
}
}
}
}
SpreadSheetName = string.Format("[{0}]", useMe == -1 ? CheckSheetName : ExcelSheets.Rows[useMe]["TABLE_NAME"].ToString());
try
{
DataSet ExcelDataSet = new DataSet();
ExcelCommand.CommandText = @"SELECT * FROM " + SpreadSheetName;
ExcelAdapter.Fill(ExcelDataSet);
return ExcelDataSet;
}
catch (Exception)
{
ExcelConnection.Close();
return new DataSet();
}
finally
{
// Clean up.
if (ExcelConnection != null)
{
ExcelConnection.Close();
ExcelConnection.Dispose();
}
if (ExcelSheets != null)
{
ExcelSheets.Dispose();
}
}
}
}
我已經在finally塊中做了。當我逐步完成初始化過程時,它會正確地運行finally並關閉連接和數據對象,並且它也有連接。 – Seth