简体   繁体   English

使用C#打开一个受Excel保护的工作表

[英]opening an excel protected sheet using c#

I am trying to open an excel file using c# however visual studio is giving this OLEDB exception: "Could not decrypt file." 我正在尝试使用c#打开excel文件,但是Visual Studio给出了此OLEDB异常:“无法解密文件”。 When opening a non prtected excel file the code works fine. 当打开一个未保护的excel文件时,代码可以正常工作。

Hereunder is my code: 以下是我的代码:

string conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + s + ";Extended Properties='Excel 8.0;HDR=YES'";
        OleDbConnection objConn = new OleDbConnection(conn);
        objConn.Open();

        OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", objConn);
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        da.Fill(dt);

I found the following website which suggests a workaround for vb but I couldn't get it to work in C#. 我发现以下网站提出了解决vb的方法,但是我无法在C#中使用它。 VBA excel VBA Excel

Any help will be greatly appreciated. 任何帮助将不胜感激。

You could use an OpenSource library like OoXmlCrypto to decrypt the password protected file, otherwise you can still use the Microsoft Interop official library that support password : 您可以使用OoXmlCrypto之类的OpenSource库来解密受密码保护的文件,否则,您仍然可以使用支持密码的Microsoft Interop官方库:

using Microsoft.Office.Interop.Excel

WorkbookObject.Password = password;

Otherwise the simplest way in your case, you can add the password property to the connection string of your OLeDb provider : 否则,这是最简单的方法,您可以将password属性添加到OLeDb提供程序的连接字符串中:

string conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + s + ";Password=password;Extended Properties='Excel 8.0;HDR=YES'";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM