这是我打开Excel文件和读取数据的代码,一切正常,但我想要的是在读取Excel文件后关闭,我该怎么做?我尝试Dispose
对象,但没有帮助。
public static DataTable ExcelWorkbook(string workbookName)
{
string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", FILENAME);
string query = String.Format("select * from [{0}$]", workbookName);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataAdapter.Dispose();
DataTable myTable = dataSet.Tables[0];
if (myTable != null)
return myTable;
return null;
}
答案 0 :(得分:1)
你的代码看起来应该是这样的:
OleDbConnection connection;
OleDbDataAdapter clientsAdapter new OleDbDataAdapter();
DataSet myDataSet = new DataSet();
connectionString = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES""",FILENAME);
connection = new OleDbConnection(connectionString);
connection.Open();
clientsAdapter.SelectCommand = new OleDbCommand("SELECT * FROM [{0}$]", connection);
DataTable data = new DataTable("MyTable");
clientsAdapter.Fill(data);
myDataSet.Tables.Add(data);
connection.Close();
关闭连接后,excel文件将被解锁。
答案 1 :(得分:0)
您正在处理读取数据的数据适配器,而不是Excel文件本身的引用。
在代码的某处,您将打开工作簿。你需要打电话
workbook.Close();