c# - Check Excel has password and prevent Prompt C#
问题描述
I have looked on the internet and on this site as to how to check if file has a password. The problem is how to prevent Excel prompting you for a correct password. I see there's HasPassword but it seems to me that property is only useable when the sheet has been opened.
try {
oWrkBk = oApp.Workbooks.Open(sFile, Password: "");
}
catch { /* has password */
But the problem is, the Excel open a prompt window which I don't want. If I can't open it, I'll skip it and close the Excel window down.
解决方案
除非OleDb
不可能,否则您将能够使用它来确定文件是否具有基于是否引发异常的密码。
要显示的示例代码:
//using System.Data.OleDb;
private static void OpenMyExcel()
{
string filePath = "C:\\users\\me\\Desktop\\Book1.xlsx";
OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0\"");
try
{
connection.Open();
//Do stuff
}
catch(Exception e)
{
//has a password
}
}
可以改为简单的检查方法(对于业余代码抱歉):
//using System.Data.OleDb;
private static bool HaveAPass(string filePath)
{
OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0\"");
try
{
connection.Open();
connection.Close(); //if it reaches this point, there is no password
return false;
}
catch(Exception e)
{
//has a password
return true;
}
}
推荐阅读
- serial-port - 如何使用 capl 中的 RS232Send 在串行控制台中执行命令?
- javascript - TypeError:无法读取未定义的属性“前缀”
- python - 可变位置和打印值
- c# - 从 Grid 中的另一个值动态填充 Grid 中的 Grid 中的 aspx 页面
- r - 将文本大小映射到 ggplot 中的数据的策略
- node.js - express-jwt - 错误:应该设置秘密
- reactjs - reactjs中如何为手机号码创建二维码?
- wpf - 管理 DateTimerPicker 控件 WPF 中的更改
- python - 保存和加载 lightgbm 数据集
- php - 有没有办法根据要求扩展到类