Apache Poi Read and Write Excel
Apache Poi Read and Write Excel
Apache Poi Read and Write Excel
Complete Example: Here we are trying to read data from excel file
package excelExportAndFileIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
File file =
new File(filePath+"\\"+fileName);
//Find the file extension by spliting file name in substring and getting only extension
name
if(fileExtensionName.equals(".xlsx")){
else if(fileExtensionName.equals(".xls")){
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
System.out.println();
//Main function is calling readExcel function to read data from excel file
objExcelFile.readExcel(filePath,"ExportExcel.xlsx","ExcelGuru99Demo");
Note: We are not using the TestNG framework here. Run the class as Java
Application
Write data on Excel file
Complete Example: Here we are trying to write data from excel file by adding
new row in excel file
package excelExportAndFileIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
File file =
new File(filePath+"\\"+fileName);
//Find the file extension by spliting file name in substing and getting only extension
name
if(fileExtensionName.equals(".xlsx")){
else if(fileExtensionName.equals(".xls")){
cell.setCellValue(dataToWrite[j]);
inputStream.close();
guru99Workbook.write(outputStream);
outputStream.close();
//Create an array with the data in the same order in which you expect to be filled in
excel file
//Write the file using file name , sheet name and the data to be filled
objExcelFile.writeExcel(System.getProperty("user.dir")
+"\\src\\excelExportAndFileIO","ExportExcel.xlsx","ExcelGuru99Demo",valueToWrite);