3

我正在使用 C# 读取 excel 文件,下面是按预期工作的代码,除了每次运行应用程序时,我必须关闭 excel 文件,否则我会收到以下错误消息:

The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data..

我的问题是:有没有办法在我完成阅读后关闭 excel 文件?

public static  DataTable LoadExcelWorkbook(string workbookName)
        {
            OleDbConnection connection;

            string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", EXCELFILENAME);
            string query = String.Format("select * from [{0}$]", workbookName);

            using(OleDbConnection conn = new OleDbConnection(connectionString))
            {
                connection = new OleDbConnection(connectionString);
                connection.Open();

                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet);

                DataTable myTable = dataSet.Tables[0];

                dataAdapter.Dispose();
                connection.Close();
                dataSet.Dispose();            

                //CLOSE THE EXCEL FILE?????????

                if (myTable != null)
                    return myTable;

                return null; 
            } 
        }
4

1 回答 1

0

use sheet1 name instead of workbook name

于 2014-02-20T13:49:59.700 回答