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.xls 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.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell; public class writeDataToExcelFile{ public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("C:\\testdata.xls")); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet 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.xls")); 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.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell;
FileInputStream file = new FileInputStream(new File("C:\\testdata.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet 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.xls"));
workbook.write(outFile);
outFile.close();
0 Comments
What would you like to add in my list? I look forward to reading your comments below.