Closing Excel file after reading

浪子不回头ぞ 提交于 2019-12-11 10:53:02

问题


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

回答1:


Your code should look sth like that:

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();

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




回答2:


You are disposing the data adapter that read the data, not the reference to the Excel file itself.

Somewhere in your code, you will have opened the workbook. You need to call

workbook.Close();

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbookclass.close(v=office.14).aspx



来源:https://stackoverflow.com/questions/12591622/closing-excel-file-after-reading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!