How to write data into Excel file

Below is the code to write data into excel sheet:

Library class to write data into excel sheet
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;

public class WriteExcel {
 
 public void writeExcel(String sheetName, String cellvalue, int row, int col) throws Exception {
  
  String excelPath="D:\\Workspace_Eclipse\\ReadExcel\\TestData\\TestData.xlsx";
  
  File file= new File(excelPath);
  
  FileInputStream fis= new FileInputStream(file);
  
  XSSFWorkbook wb= new XSSFWorkbook(fis);
  
  XSSFSheet sheet= wb.getSheet(sheetName);
  
  sheet.getRow(row).createCell(col).setCellValue(cellvalue);
  
  FileOutputStream fos= new FileOutputStream(new File(excelPath));
  
  wb.write(fos);
  
  wb.close();
  
  fos.close();
 }
}

Sample Test Class
import org.testng.annotations.Test;
import com.writeExcel.WriteExcel;

public class WriteExcelTest {

 WriteExcel obj= new WriteExcel();
 
 @Test
 public void writeExcelTest() throws Exception {
  obj.writeExcel("Test", "Male", 0, 2);
 }
 
 @Test
 public void writeExcelTest1() throws Exception {
  obj.writeExcel("Test", "Female", 1, 2);
 }
 
}

Please refer below YouTube video on how to write data into excel sheet

No comments:

Post a Comment