开发者

How to skip a few password protected excel files when processing a large number of excel workbooks in c#

Is it possible to skip password protected Excel files in c#?

I dont know the passwords to those files, and because all these files are supposed to be processed automatically, the program needs to be able to skip all the files that ask password, as the prompt asking for user input for开发者_如何学JAVA the password will interrupt the program.

This is my code for opening the Excel file:

Excel.Workbook workbook = app.Workbooks.Open(fullFileName, ReadOnly: false, Password: "");


you can use EPPlus, with it it's relativly easy, only problem is to know is exception raised because protection or something else, here is the code :

public bool IsXlsxPasswordProtected(string fileName)
{
  bool encrypted = false;
  FileStream fs = new FileStream(fileName, FileMode.Open);
  ExcelPackage pack = new ExcelPackage();
  try
  {
    pack.Load(fs);
  }
  catch (Exception ex)
  {
    /// maybe there is better way to know if exception is because file is protected 
    /// with password, idealy EPP should raise dedicated exception type 
    /// e.g. PasswordProtectedException
    if (ex.InnerException != null && ex.InnerException is FileFormatException)
      encrypted = true;
    else
      throw;
  }
  return encrypted;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜