|
Answer» To read and write an excel file, the Apache POI LIBRARY is capable to read write both xls and XLSX file format of excel. Below are the steps to write to excel sheet - - Create an xlsx file and save it at the desired location( d:testdata.xlsx). Add some data to read by selenium and rename sheet (ex. mysheet).
- By default excel cell format is general, make it text.
- Close that excel file before the execution of the script.
- You need to download POI jars and unzip it. POI jars allow to create, modify, and display MS Office files using Java programs. Go to the official website of Apache POI download section http://poi.apache.org/download.html
- In your editor Select Project
- Right-click on the project
- Go to build path
- Go to 'Configure build path;
- Click on the 'lib' tab and,
- add POI external JAR files.
- Below is the code to write excel file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
public class WriteExcel {
public STATIC void main(String []args){
try {
// To specify the file path which you want to create or write
File src=new File("./test/testdata.xlsx");
// To LOAD the file
FileInputStream fis=new FileInputStream(src);
// To load the workbook
XSSFWorkbook wb=new XSSFWorkbook(fis);
// To get the sheet to modify or create
XSSFSheet sh1= wb.getSheetAt(0);
// here createCell will create column and setCellvalue will set the value
sh1.getRow(0).createCell(2).setCellValue("2.31.0");
sh1.getRow(1).createCell(2).setCellValue("3.5");
sh1.getRow(2).createCell(2).setCellValue("4.66");
// to specify where you want to save file
FileOutputStream fout=new FileOutputStream(new File("location of file/filename.xlsx"));
// finally write content
wb.write(fout);
// close the file
fout.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|