This following code works correctly the first time I access the file to do a line count. However, when I attempt to open the same file to read the data, I get an error thrown on ExcelConnection.Open() which states that I do not have permission to access the file or it is already being used. Any thought as to why the file isn’t being released after the first connection to it?
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();
}
}
}
}
You must close the connetion after the file has been read or the operation you have odne is completed….
ExcelConnection.Close();