在C#中使用OLEDB读取密码保护的excel文件 [英] Read password protected excel file using OLEDB in C#
本文介绍了在C#中使用OLEDB读取密码保护的excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\test.xls;扩展属性= \Excel 8.0; HDR = NO; ReadOnly = true; IMEX = 1\
来读取Excel文件。 为了读取受密码保护的文件,我尝试在连接字符串中添加密码字段,但无法读取文件。
我想知道,如果我事先知道密码,是否有任何方式读取密码保护的Excel文件。
解决方案
p>如果您使用查询来阅读excel文件,那么这些表格是否受到保护并不重要:它可以以任何方式工作。
private string ExcelConnection(string fileName)
{
return
@Provider = Microsoft.Jet.OLEDB.4.0; +
@Data Source =+ fileName +; +
@扩展属性=+ Convert.ToChar(34).ToString()+
@Excel 8.0+ Convert.ToChar(34).ToString()+;;
}
private DataTable readExcel(string fileName,string sql)
{
OleDbConnection conn = new OleDbConnection(ExcelConnection(fileName));
OleDbCommand cmd = new OleDbCommand(sql,conn);
OleDbDataAdapter adp = new OleDbDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
try
{
adp.FillSchema(dt,SchemaType.Source);
adp.Fill(dt);
}
catch
{
}
return dt;
}
In my c# application I am using OLEDB connection string "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\test.xls;Extended Properties=\"Excel 8.0;HDR=NO;ReadOnly=true;IMEX=1\"
" to read Excel files.
In order to read a password protected file I tried adding password field in connection string but was unable to read file.
I want to know is there any way to read password protected Excel files using OLEDB if I know its password beforehand.
解决方案
If you use a query to read the excel file, it doesn't matter if some of the sheets are protected: It works either way.
private string ExcelConnection(string fileName)
{
return
@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=" + fileName + ";" +
@"Extended Properties=" + Convert.ToChar(34).ToString() +
@"Excel 8.0" + Convert.ToChar(34).ToString() + ";";
}
private DataTable readExcel(string fileName, string sql)
{
OleDbConnection conn = new OleDbConnection(ExcelConnection(fileName));
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataAdapter adp = new OleDbDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
try
{
adp.FillSchema(dt, SchemaType.Source);
adp.Fill(dt);
}
catch
{
}
return dt;
}
这篇关于在C#中使用OLEDB读取密码保护的excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文