【问题标题】:Read password protected excel file using OLEDB in C#在 C# 中使用 OLEDB 读取受密码保护的 excel 文件
【发布时间】:2010-11-24 06:31:08
【问题描述】:

在我的 c# 应用程序中,我使用 OLEDB 连接字符串“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\test.xls;Extended Properties=\"Excel 8.0;HDR=NO;ReadOnly=true;IMEX=1\"”来读取 Excel 文件。 为了读取受密码保护的文件,我尝试在连接字符串中添加密码字段,但无法读取文件。 我想知道如果我事先知道它的密码,是否有任何方法可以使用 OLEDB 读取受密码保护的 Excel 文件。

【问题讨论】:

    标签: c# excel oledb


    【解决方案1】:

    如果您使用查询来读取 excel 文件,则某些工作表是否受到保护无关紧要:无论哪种方式都可以。

        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;
        }
    

    【讨论】:

      【解决方案2】:

      这里是different ways to connect to an Excel file,包括 OLEDB。据此,您无法使用标准方法打开受密码保护的文件。您必须使用解决方法。

      如果 Excel 工作簿受以下保护 密码,您无法打开它 数据访问,即使通过提供 正确的连接密码 细绳。如果你尝试,你会收到 以下错误消息:“不能 解密文件。

      This is the solution,虽然不是在 C# 中,但您可以根据自己的目的轻松调整它。

      如果您自己不知道密码,另一种方法是在没有密码的情况下重新写入文件。您可以使用this handy project 并将以下例程添加到其中:

      public void SaveFile()
      
              {
                  this.excelWorkbook.SaveAs(
                      this.excelWorkbook.FullName,
                      vk_format,
                      "",
                      vk_write_res_password,
                      vk_read_only,
                      null,
                      Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                      null,
                      vk_add_to_mru,
                      null,null,vk_local);
              }
      

      Full detail here.

      【讨论】:

        【解决方案3】:

        我反复研究后,终于找到了两件事。
        1.使用OLEDB,无法读取受密码保护的excel文件。
        2.Interop虽然不管有没有密码保护都可以读取excel文件,但性能不如OLEDB。

        所以,我通过组合创建以下代码
        1. OLEDB,性能非常好,
        2.互操作,可以读取每个excel文件。

        public DataTable ReadPasswordProtectedExcel(string ExcelFilePath, string Password)
        {
            String TempExcelFilePath = string.Empty;            
            DataTable _DataTable = new DataTable();
        
            #region Get ExcelFile and Remove Password
            {
                String TempExcelFileName = string.Empty;
                String DirectoryPath = string.Empty;
                Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
                excelapp.Visible = false;
        
                Microsoft.Office.Interop.Excel.Workbook newWorkbook = excelapp.Workbooks.Open(ExcelFilePath, 0,
                                                    true, 5, Password, "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
                                                    false, 0, true, false, false);
        
                TempExcelFileName = string.Format("{0}_{1}", "__", Path.GetFileName(ExcelFilePath)); // __xxx.xlsx
                TempExcelFilePath = String.Format("{0}/{1}", Path.GetDirectoryName(ExcelFilePath), TempExcelFileName);
        
                /// Create new excel file and remove password.
                newWorkbook.SaveAs(TempExcelFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, "", "",
                false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        
                newWorkbook.Close(true, "", false);
        
                excelapp.Quit();
                Marshal.ReleaseComObject(excelapp);
            }
            #endregion
        
            #region Get data from excel file by using OLEDB
            {
                _DataTable = ReadExcelFileInOLEDB(TempExcelFilePath);
                ///Delete excel file
                File.Delete(TempExcelFilePath);
            }
            #endregion
        
            return _DataTable;
        }
        
        public DataTable ReadExcelFileInOLEDB(string _ExcelFilePath)
        {
            string ConnectionString = string.Empty;
            string SheetName = string.Empty;           
            DataTable _DataTable = null;
            DataSet _DataSet = null;
        
            try
            {
                ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=0;'", _ExcelFilePath);
                using (OleDbConnection _OleDbConnection = new OleDbConnection(ConnectionString))
                {
                    _OleDbConnection.Open();
                    _DataTable = _OleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        
                    if (_DataTable == null)
                        return null;
        
                    SheetName = _DataTable.Rows[0]["TABLE_NAME"].ToString();
                    ConnectionString = string.Format("SELECT * FROM [{0}]", SheetName);
        
                    using (OleDbCommand _OleDbCommand = new OleDbCommand(ConnectionString, _OleDbConnection))
                    {
                        using (OleDbDataAdapter _OleDbDataAdapter = new OleDbDataAdapter())
                        {
                            _OleDbDataAdapter.SelectCommand = _OleDbCommand;
        
                            _DataSet = new DataSet();
                            _OleDbDataAdapter.Fill(_DataSet, "PrintInfo");
                            return _DataSet.Tables["PrintInfo"];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        

        最后如果你想在从excel中检索数据时删除空行,请检查this link和下面的代码

        SELECT * FROM NAMED_RANGE WHERE [YourColumnTitle] IS NOT NULL 
        

        【讨论】:

          【解决方案4】:

          您可以使用OoXmlCrypto stream 访问 Office 2007 加密文件。开源,包括修改后的 ExcelPackage。

          示例代码:

          using (OfficeCryptoStream stream = OfficeCryptoStream.Open("a.xlsx", "password"))
          {
              // Do stuff (e.g. create System.IO.Packaging.Package or 
              // ExcelPackage from the stream, make changes and save)
          
              // Change the password (optional)
              stream.Password = "newPassword";
          
              // Encrypt and save the file
              stream.Save();
          }
          

          【讨论】:

          • 如果文件是加密的,那么是否适用?
          猜你喜欢
          • 1970-01-01
          • 2018-12-18
          • 1970-01-01
          • 1970-01-01
          • 2020-06-18
          • 2011-02-06
          • 1970-01-01
          • 2011-01-01
          • 2013-11-09
          相关资源
          最近更新 更多