如何检查excel文件是打开的,如果打开然后在C#中关闭 [英] How to check excel file is open and if open then close in C#

查看:1021
本文介绍了如何检查excel文件是打开的,如果打开然后在C#中关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助,我可以检查Excel文件是否打开哪一个我要浏览上传,我想要特定的Excel文件,如果打开然后自动保存并关闭该excel文件,因为我有一个错误,当我我将在数据表中上传excel数据。

以下错误即将来临



Hi, I need help how I can check that Excel file is open which one I am going to browse to upload, i want particular Excel file if opened then save automatically and close that excel file because I am having an error when I am going to upload excel data in Data table.
following error is coming

Quote:

Microsoft Access数据库引擎无法打开或写入文件''。它已经由另一个用户专门打开,或者您需要获得查看和写入其数据的权限

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文件哪一个我要上传数据,但我要检查是否打开然后关闭,此代码不起作用





What I have tried:

I was trying to close excel file which one i am going to upload data, but i want check if open then close, this code does not work

Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel.Workbook workbook;
                    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
                    object misValue = System.Reflection.Missing.Value;
                    workbook = Excel.Workbooks.Add(txtBrowse.Text);
                    workbook.Close(false, misValue, misValue);

推荐答案

检查它是否打开如

Check whether it is open like
try
{
   Stream s = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);

   s.Close();

   return true;
}
catch (Exception)
{
   return false;
}





关闭Excel,如: -



Close Excel like as:-

using Excel = Microsoft.Office.Interop.Excel;

# declare the application object
Excel.Application xl = new Excel.Application();

# open a file
Excel.Workbook wb = xl.Workbooks.Open("some_file.xlsx");

# do stuff ....

# close the file
wb.Close();

# close the application and release resources
xl.Quit();


protected virtual bool IsFileLocked(FileInfo file )

{

FileStream stream = null;



try

{

stream = file.Open(FileMode.Open,FileAccess.Read,FileShare.None);

}

catch(IOException ex)

{

//该文件不可用,因为它是:

//仍然被写入

//或由另一个线程处理

//或不存在(已经处理)

返回true;

}

终于

{

if(stream!= null)

stream.Close();

}



//文件未锁定

返回false;

}
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;

try
{
stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException ex)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}

//file is not locked
return false;
}


这篇关于如何检查excel文件是打开的,如果打开然后在C#中关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆