Reading and Writing Data From Excel using Apache POI jar

Download Apache POI jar

View and Download input.xlsx
package com.excel.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadingExcel {

 public static void main(String[] args) throws Exception, IOException {
  File file = new File("./TestData/input.xlsx");
  FileInputStream fis = new FileInputStream(file);
  XSSFWorkbook wb = new XSSFWorkbook(fis);
  
  XSSFSheet sht = wb.getSheetAt(0);
  
  String data00 = sht.getRow(0).getCell(0).getStringCellValue();
  
  System.out.println(data00);
  
  System.out.println("No of Rows: " + sht.getLastRowNum());
  System.out.println("No of Columns: " + sht.getRow(0).getLastCellNum());
  String data="";
  for (int i = 0; i <= sht.getLastRowNum(); i++) {
   for (int j = 0; j < sht.getRow(i).getLastCellNum(); j++) {
    if(i!=0 && (j==2||j==3)){
     data=String.valueOf(sht.getRow(i).getCell(j).getNumericCellValue());
    } else{
     data=sht.getRow(i).getCell(j).getStringCellValue();
    }
    
    System.out.print(data +"\t");
   }
   System.out.println();
  }
  sht.getRow(0).createCell(6).setCellValue("Result");
  fis.close();
  FileOutputStream fos = new FileOutputStream(file);
  wb.write(fos);
  
  fos.close();
  wb.close();
 }
}

1 comment:

  1. This is the best explanation I have seen so far on the web. I was looking for a simple yet informative about this topic finally your site helped me a lot to gain knowledge.
    software testing selenium training
    selenium testing training in chennai

    ReplyDelete