Excel文件 - 已由其他用户专门打开,

时间:2012-10-04 20:23:37

标签: c# excel excel-2007 oledbconnection oledbdataadapter

我正在使用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; 
            } 
        }

1 个答案:

答案 0 :(得分:0)

使用sheet1名称而不是工作簿名称