阅读后关闭Excel文件

问题描述:

这是我用于打开Excel文件并读取数据的代码,一切正常,但是我想在读取Excel文件后关闭它,我该怎么做?我尝试Dispose该对象,但没有帮助.

Here is my code for opening the Excel file and reading the data, everything is working fine but what I would like is to close once the Excel file is read, how would i do that? I try Dispose the object but did not help.

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;
        }

您的代码应如下所示:

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文件将被解锁.

After the connection is closed, the excel file will be unlocked.