简体   繁体   English

如何使用OLEDB读取受密码保护的Excel工作表

[英]How to read a password protected Excel worksheet with OLEDB

I have set a password on my excel sheet. 我已经在Excel工作表中设置了密码。 To unlock the worksheet, I modified my OLEDB connection string, but it didn't work. 为了解锁工作表,我修改了OLEDB连接字符串,但是没有用。 I got an error that "the source contains no dataRows", which means that it couldn't read the data from the excel file. 我收到一个错误消息“源不包含dataRows”,这意味着它无法从excel文件中读取数据。

Before it was fine. 之前还好。 What might be my problem? 我可能是什么问题?

This is my code: 这是我的代码:

public DataTable getExcelData(string fileName, string sheetName, ComboBox[] User_ComboBox)
{
    this.m_comboBox = User_ComboBox;

  // connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 12.0 XML;HDR=No;IMEX=1'";
   connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Password=xyz;Extended Properties='Excel 8.0;HDR=YES'";

    string errorMessage = "";
    DataTable dt = new DataTable();

    try
    {
        string query = "SELECT * FROM [" + sheetName + "]";
        OleDbConnection con = new OleDbConnection(connectionString);
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, con);
        dataAdapter.Fill(dt);
    }
    catch (Exception exp)
    {
        // errorCode = ErrorDefinition.ERROR_OLEDBERROR;
        errorMessage = exp.Message;
    }
    return dt;
}

Instead of using an OleDbConnection you might consider using an Excel reading library like EPPlus to read the excel file. 您可以考虑使用像EPPlus这样的Excel读取库来读取Excel文件,而不是使用OleDbConnection EPPlus supports reading password protected excel files. EPPlus支持读取受密码保护的Excel文件。

You would need to implement some code to build the actual DataTable , but that should be simple enough. 您将需要实现一些代码来构建实际的DataTable ,但这应该足够简单。 Just google it if you need to. 只需在Google上搜索即可。

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

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