Writing Data in Excel File using Apache POI in Selenium WebDriver?

Apache POI is a Java API used to manipulate Microsoft Office documents such as Excel spreadsheets, Word documents, and PowerPoint presentations. 

In the context of Selenium, Apache POI can be used to read and write data from and to Excel files, which is useful for data-driven testing. 

For Example, you can use Apache POI to read test data from an Excel file and pass it as input to your Selenium test cases. 

Similarly, you can write test results to an Excel file using Apache POI. Overall, Apache POI can enhance the functionality and efficiency of your Selenium test automation framework by providing easy access to Excel data.

Here is an example of how to write data to an Excel file using the Apache POI library:

import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWriter {
    public static void main(String[] args) throws IOException {
        // File path
        String filePath = "path/to/excel/file.xlsx";
        // Create a new workbook
        Workbook workbook = new XSSFWorkbook();
        // Create a new sheet
        Sheet sheet = workbook.createSheet("Sheet1");
        // Create a new row
        Row row = sheet.createRow(0);
        // Create a new cell
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello World!");
        // Open the file
        FileOutputStream file = new FileOutputStream(filePath);
        // Write the workbook to the file
        // Close the file

  • In this example, the XSSFWorkbook class is used to create a new workbook object. 
  • Then, the createSheet() method is used to create a new sheet in the workbook, and the createRow() method is used to create a new row in the sheet. 
  • Then, the createCell() method is used to create a new cell in the row, and the setCellValue() method is used to set the value of the cell.

Finally, the FileOutputStream class is used to open the file and the write() method is used to write the workbook to the file.

It's important to note that the above example is for writing to an Excel file in the xlsx format. If you are working with an Excel file in the xls format, you can use the HSSFWorkbook class instead of the XSSFWorkbook class to create a new workbook object.

Also, you should always close the file after writing to it, to free up resources and avoid potential data corruption issues.

You should also make sure that the path to the excel file is correct and the file exists in the specified location, if the file doesn't exist it will create a new one.

Post a Comment

Post a Comment (0)

Previous Post Next Post