1.

How To Write Data In Excel File

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 -

  1. 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). 
  2. By default excel cell format is general, make it text.
  3. Close that excel file before the execution of the script.
  4. 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 
  5. In your editor Select Project
  6. Right-click on the project
  7. Go to build path
  8. Go to 'Configure build path;
  9. Click on the 'lib' tab and, 
  10. add POI external JAR files.
  11. 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());   }   }  }


Discussion

No Comment Found