We can also write data to excel file using Apache POI library.
Here is the very basic program to explain How to write data to excel file using Apache POI library.
Use below code to write data to excel file:
Here is the very basic program to explain How to write data to excel file using Apache POI library.
Create a testdata.xlsx file in the C drive with following details:
Search Text |
hello selenium |
abhishek yadav qa |
Use below code to write data to excel file:
Java Source code:
package com.helloselenium.selenium.test; import java.io.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class writeDataToExcelFile{ public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("C:\\testdata.xlsx")); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); Cell searchText3 = sheet.getRow(0).getCell(0); searchText3.setCellValue("Test Search Keyword"); file.close(); FileOutputStream outFile =new FileOutputStream(new File("C:\\testdata-result.xlsx")); workbook.write(outFile); outFile.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Output:
Test Search Keyword |
hello selenium |
abhishek yadav qa |
Detailed explanation for the above program is as follows:
Following code is the required packages for JAVA IO to make integration with excel file.
import java.io.*;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
FileInputStream file = new FileInputStream(new File("C:\\testdata.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Cell searchText3 = sheet.getRow(0).getCell(0);
searchText3.setCellValue("test search keyword");
Use the following code is to close the excel file.
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\testdata-result.xlsx"));
workbook.write(outFile);
outFile.close();
3 Comments
am getting null pointer exception at Cell searchText3 = sheet.getRow(0).getCell(0);
ReplyDelete@Selenium2015, Are you still getting this exception?
DeleteHi, I am getting same Null point exception.
DeleteWhat would you like to add in my list? I look forward to reading your comments below.