簡體   English   中英

如何使用 Selenium WebDriver 打開受密碼保護的 excel 文件

[英]How to open an excel file protected with password using Selenium WebDriver

如何使用 Selenium 打開受密碼保護的 excel 文件?

我可以與沒有密碼的任何其他 excel 進行交互,我現在該怎么做。

這是我已經必須在沒有密碼的情況下訪問 excel 文件的代碼:

    File src = new File("C:/Users/.../.../.../Credentials Automation.xlsx");
    FileInputStream fis = new FileInputStream(src);
    XSSFWorkbook wb = new XSSFWorkbook(fis);
    XSSFSheet sheet1 = wb.getSheetAt(0);
    XSSFSheet sheet2 = wb.getSheetAt(1);

您指的是 apache-poi 庫(您在代碼片段中使用的庫),它允許操作 excel 文件。 Selenium,據說,沒有這個功能。


Maven:Apache-poi

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.0.0</version>
</dependency>

或從此處手動下載 jar 文件: https://mvnrepository.com/artifact/org.apache.poi/poi-scr/50.

解決方案

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;

import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;

public class AppTest {

    @Test
    public void openProtectedExcelFile() throws IOException, GeneralSecurityException {

        String excelFilePath = "E:/Credentials Automation.xlsx";
        POIFSFileSystem fileSystem = new POIFSFileSystem(new File(excelFilePath));
        EncryptionInfo encryptionInfo = new EncryptionInfo(fileSystem);
        Decryptor decryptor = Decryptor.getInstance(encryptionInfo);
        decryptor.verifyPassword("selenium"); //pass the password in here
        InputStream dataStream = decryptor.getDataStream(fileSystem);

        XSSFWorkbook wb = new XSSFWorkbook(dataStream);
        XSSFSheet sheet1 = wb.getSheetAt(0);
        XSSFSheet sheet2 = wb.getSheetAt(1);

        XSSFRow row1 = sheet1.getRow(0);
        System.out.println(row1.getCell(0));
        wb.close();
        
    }
}

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM