简体   繁体   中英

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

How can I open an excel file that is protected by password using Selenium??

I am able to interact with any other excel that does not have a password and I now how to do it.

This is the code that I already have to access excel file without password:

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

You are refering to the apache-poi library (the one that you are using in your code snipped), which allows the manipulation of the excel files. Selenium, per say, has no functionality for this.


Maven: Apache-poi

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

or manualy download the jar file from here: https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad/5.0.0

Solution

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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