My excel sheet contains 5 row and 2 columns.I want to add one more column in that excel.But when i am using WorkbookFactory,it is showing error.I imported poi-3.8.jar and poi-ooxml-3.5-beta5.jar.It is giving error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
WorkbookFactory cannot be resolved.Please help me what to do.
try this
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExample {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(1).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(2).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
Row row = sheet.getRow(0);
row.createCell(3).setCellValue("Value 2");
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
See the Apache POI Components and Dependencies page for details. You're missing some of the jars, hence the compile error.
If you want to work with both HSSF (.xls) and XSSF (.xlsx), which I guess you do as you're talking about WorkbookFactory, you'll need to include both the main POI jar and the POI-OOXML jar, plus all of their dependencies. With those jars on your classpath, you'll be sorted
Also, you might want to think about using something like Apache Maven or Apache Ivy to handle your dependencies for you, that way you can avoid missing jar problems like this
Are you using Maven?
In case yes, then please refer to the last comment at the following link:
http://apache-poi.1045710.n5.nabble.com/Where-is-WorkbookFactory-td2307412.html
I'm Uploading my program for your reference. After some effort I've overcome this issue.
Jars details: dom4j-1.6.1.jar, poi-3.9.jar,poi-ooxml-3.9.jar, poi-ooxml-schemas-3.11.jar, xmlbeans-2.6.0.jar
Make sure you have at least above mentioned or new. I'm including details of import so that you don't need to bang you head. Hope you find it use
***Pojo: Employee.java***
public class Employee {
private int id;
private String firstName;
private String lastName;
public Employee(){}
public Employee(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
***Write Class: ApachePOIExcelWrite.java***
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ApachePOIExcelWrite {
public static void main(String[] args)
{
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
data.put("2", new Object[] {1, "Amit", "Shukla"});
data.put("3", new Object[] {2, "Lokesh", "Gupta"});
data.put("4", new Object[] {3, "John", "Adwards"});
data.put("5", new Object[] {4, "Brian", "Schultz"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("/home/ohelig/eclipse/New Microsoft Office Excel Worksheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Write Successfully.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
***Update Class: UpdateExcel.java***
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateExcel {
public static void main(String[] args) {
XSSFWorkbook workbook=null;
XSSFSheet sheet;
try{
FileInputStream file = new FileInputStream(new File("/home/ohelig/eclipse/New Excel Worksheet.xlsx"));
//Create Workbook instance holding reference to .xlsx file
workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
//Most of people make mistake by making new sheet by looking in tutorial
sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
Employee ess = new Employee(6,"Yanish","Pradhananga");
//Get the count in sheet
int rowCount = sheet.getLastRowNum()+1;
Row empRow = sheet.createRow(rowCount);
System.out.println();
Cell c1 = empRow.createCell(0);
c1.setCellValue(ess.getId());
Cell c2 = empRow.createCell(1);
c2.setCellValue(ess.getFirstName());
Cell c3 = empRow.createCell(2);
c3.setCellValue(ess.getLastName());
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new
File("/home/ohelig/eclipse/New Excel Worksheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Update Successfully");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Related
The Selenium Webdriver, TestNG version & used libraries are given below.
Selenium version : selenium-server-standalone-3.41.59.jar
TestNG version : 7.4.0
Tried to login with Excel sheet data provider.But no class found error getting.
Added Apache POI excel related dependenices
Added Libraries(Please see the screenshot)
Here is my code.
The Selenium Webdriver, TestNG version & used libraries are given below.
Selenium version : selenium-server-standalone-3.41.59.jar TestNG version : 7.4.0
package ui;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class MultiUserLogin {
public static WebDriver driver;
public WebDriverWait wait;
String appURL1 = "https://www.google.com";
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.gecko.driver","E:/Geckdriver/geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider="LoginData")
public void VerifyValidLogin(String Username, String Password,String Company) {
driver.navigate().to(appURL1);
driver.findElement(By.id("userId")).sendKeys(Username);
driver.findElement(By.id("password")).sendKeys(Password);
driver.findElement(By.id("company")).sendKeys(Company);
driver.findElement(By.linkText("Login")).click();
}
#DataProvider(name="LoginData")
public Object[][] LoginData() throws Exception {
Object[][] testObjArray = ExcelUtils.getTableArray("E:\\TestNG\\TestData\\TestData.xlsx","Sheet1");
return (testObjArray);
}
}
package ui;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {
String[][] tabArray = null;
try {
FileInputStream ExcelFile = new FileInputStream(FilePath);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int startRow = 1;
int startCol = 1;
int ci,cj;
int totalRows = ExcelWSheet.getLastRowNum();
// function as well to get Column count
int totalCols = 2;
tabArray=new String[totalRows][totalCols];
ci=0;
for (int i=startRow;i<=totalRows;i++, ci++) {
cj=0;
for (int j=startCol;j<=totalCols;j++, cj++){
tabArray[ci][cj]=getCellData(i,j);
System.out.println(tabArray[ci][cj]);
}
}
}
catch (FileNotFoundException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
catch (IOException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
return(tabArray);
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
CellType dataType= Cell.getCellType();
if (dataType == CellType.STRING) {
return "";
}else{
String CellData = Cell.getStringCellValue();
return CellData;
}
}catch (Exception e){
System.out.println(e.getMessage());
throw (e);
}
}
}
I am using Apache POI API to read Excel file and check the quantity of products available or not. I am successfully reading excel file using below code but I am unable to read the specific cell (Quantity Column) to check weather asked product is available or not
package practice;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ReadingExcel {
private static String brand = "Nike";
private static String shoeName = "Roshe One";
private static String colour = "Black";
private static String size = "9.0";
private static String quantity;
public static void main(String [] args){
try {
FileInputStream excelFile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Project\\assets\\Shoe_Store_Storeroom.xlsx"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t\t");
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is my excel file
using opencsv 4.1 i do this
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
...
try (InputStream excelFile = new FileInputStream(new File(fileName));
Workbook wb = new XSSFWorkbook(excelFile);) {
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
Sheet xssfSheet = wb.getSheetAt(numSheet);
xssfSheet.forEach(row -> {
Cell cell = row.getCell(0);
if (cell != null) {
if(StringUtils.isNumeric(cell.getStringCellValue())){
// Use here cell.getStringCellValue()
}
}
});
}
}
Use below for loop:
for(int r=sh.getFirstRowNum()+1; r<=sh.getLastRowNum(); r++){ //iterating through all the rows of excel
Row currentRow = sh.getRow(r); //get r'th row
Cell quantityCell = currentRow.getCell(4); //assuming your quantity cell will always be at position 4; if that is not the case check for the header value first
String currentCellValue = quantityCell.getStringCellValue();
if(currentCellValue.equalsIgnoreCase(<value you want to campare with>))
//<do your further actions here>
else
//do your further actions here
}
I Was Executing Test Scripts Though Excel Sheet Using Keyword Driven Data Framework.
While Executing Am Geting Error as :
java.lang.RuntimeException: java.lang.IllegalStateException: Cannot
get a STRING value from a NUMERIC cell
My Selenium Code is
package DemoData;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import DataConfig.ExcelDataConfig;
public class ReadArrayData
{
WebDriver driver;
#Test(dataProvider="Tipreports")
public void Dataprovider(String username, String password) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://xxxxxxxxxxxxxxxx/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.findElement(By.id("txt_username")).sendKeys(username);
driver.findElement(By.id("txt_pin")).sendKeys(password);
driver.findElement(By.xpath("//*[#id='btn_click']")).click();
Thread.sleep(5000);
//driver.getCurrentUrl();
Assert.assertTrue(driver.getCurrentUrl().contains("http://xxxxxxxxxxxxx/Algorithm_Run.aspx"),"User Not able to Login - Invalid Credentials");
}
#AfterMethod
public void Close()
{
driver.quit();
}
#DataProvider(name="Tipreports")
public Object[][] passdata()
{
ExcelDataConfig config = new ExcelDataConfig("E:\\Workspace\\KeywordFramework\\TestData\\Dataprovider.xlsx");
int rows = config.getRowCount(0);
Object[][] data = new Object[rows][2];
for(int i=0;i<rows;i++)
{
data[i][0]=config.getData(0, i, 0);
data[i][1]=config.getData(0, i, 1);
}
return data;
}
}
Here is My Excel Data Config Code :
package DataConfig;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDataConfig
{
XSSFWorkbook wb;
XSSFSheet Sheet1;
public ExcelDataConfig(String excelpath)
{
try
{
File src = new File(excelpath);
FileInputStream fis = new FileInputStream(src);
wb= new XSSFWorkbook(fis);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column)
{
Sheet1 = wb.getSheetAt(sheetnumber);
String data =Sheet1.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetindex)
{
int row = wb.getSheetAt(sheetindex).getLastRowNum();
row = row+1;
return row;
}
}
Can you please help me to sort out this, Why am getting this error? I have declared 2 Columns and 4 Rows using for loop. But am getting cannot Get The error as cannot get the string value from Numeic Cell.
Try this:
String data;
if(cell.getCellType()==CellType.STRING)
data = cell.getStringCellValue();
else if(cell.getCellType()==CellType.NUMERIC)
data = String.valueOf(cell.getNumericCellValue());
else ...
It is a better way to retrieve the cell content as text.
Thanks to #AxelRichter, the manual show a more complete example to retrieve cell content: https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents
//try this:
DataFormatter objDefaultFormat = new DataFormatter();
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
String cellValueStr = objDefaultFormat.formatCellValue( cell , formulaEvaluator );
DataFormatter contains methods for formatting the value stored in an Cell. This can be useful when you need to get data exactly as it appears in Excel.
Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.
Thanks to #AxelRichter:
DataFormatter formatter = new DataFormatter();
String text = formatter.formatCellValue(cell);
I've created this code and The PoiReadExcelFile class will read in the 'poi-test.xls' file into an HSSFWorkbook object. The 'POI Worksheet' will then be read into an HSSFWorksheet object, and then the values within the A1, B1, C1, and D1 cells will be read and displayed to standard output.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class PoiReadExcelFile {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("poi-
test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("POI Worksheet");
HSSFRow row1 = worksheet.getRow(0);
HSSFCell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
HSSFCell cellB1 = row1.getCell((short) 1);
String b1Val = cellB1.getStringCellValue();
HSSFCell cellC1 = row1.getCell((short) 2);
boolean c1Val = cellC1.getBooleanCellValue();
HSSFCell cellD1 = row1.getCell((short) 3);
Date d1Val = cellD1.getDateCellValue();
System.out.println("A1: " + a1Val);
System.out.println("B1: " + b1Val);
System.out.println("C1: " + c1Val);
System.out.println("D1: " + d1Val);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When i ran this code i got this:
Usage: BiffDrawingToXml [options] inputWorkbook
Options:
-exclude-workbook exclude workbook-level records
-sheet-indexes output sheets with specified indexes
-sheet-namek output sheets with specified name
What's the problem?
Please run the class file using right click run option. The above message while come when the only JAR file is getting run.
I am new to Java POI and i am trying to overwrite an excel file using Java POI.Let me make it clear, i don't want to open a new .xls file every time time i build the code however the code i wrote does it that way.The purpose for this is to, i will build the chart on excel and read the values for the chart from the database and write it to the excel file by using Java POI.Here is my code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("oldu");
HSSFSheet secondSheet = workbook.createSheet("oldu2");
HSSFRow rowA = firstSheet.createRow(6);
HSSFCell cellA = rowA.createCell(3);
cellA.setCellValue(new HSSFRichTextString("100"));
cellA.setCellValue(100);
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("200"));
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("CreateExcelDemo.xls"));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Always use the same filename and when you run the program it will overwrite the file.
EDIT
If you want to modify an existing excel file then have a look HERE and scroll down to the section on "Reading or Modifying an existing file".
The problem is Apache POI doesn't support all features of Excel file format, including charts. So can not generate a chart with POI and when opening an existing Excel file with POI and modifying it, some of the current "objects" in the Excel file could be lost, as POI can't handle it and when writing, writes only the new information generated and existing one that can handle.
This is assumed by Apache as one of the flaws of POI.
We done similar processing of existing Excel file, filling new data onto it, but the existing Excel file contains only formatting styles and they are preserved using POI, but I think charts are very problematic. Trying ti filling data to update an existing chart is not possible with POI.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class UserInput {
public static Map getUserInput() throws InvalidFormatException, IOException {
String userName = System.getProperty("user.name");
String path = "";
int indexofColumn = 10;
Map inputFromExcel = new HashMap();
InputStream inp = new FileInputStream(path);
int ctr = 4;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
inputFromExcel.put("NBKID",cell.toString()) ;
row = sheet.getRow(ctr+1);
cell = row.getCell(indexofColumn);
inputFromExcel.put("Password", cell.toString());
row = sheet.getRow(ctr+2);
cell = row.getCell(indexofColumn);
inputFromExcel.put("NBKIDEmail",cell.toString());
row = sheet.getRow(ctr+3);
cell = row.getCell(indexofColumn);
inputFromExcel.put("sourceExcel" ,cell.toString());
} catch(Exception e) {
}
return inputFromExcel;
}
}
import java.util;
public class Main {
public static void main(String[] args) {
List<String> partyIdList = new ArrayList<String>();
List<String> phNoList = new ArrayList<String>();
String userName = System.getProperty("user.name");
String path = "";
try {
Map data = new HashMap(UserInput.getUserInput());
partyIdList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),0);
phNoList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),1);
WriteExcel.writeFile1(partyIdList, path,0,1);
WriteExcel.writeFile1(phNoList,path,1,0);
} catch (Exception e) {
throw new RuntimeException("Error while read excel Sheet" + e);
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static List getContentFromExcelSheet(String path ,int indexofColumn) throws InvalidFormatException, IOException {
//System.out.println(path);
List<String> ItemList = new ArrayList();
InputStream inp = new FileInputStream(path);
int ctr = 0;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
ItemList.add(cell.toString());
// System.out.println(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
inp.close();
return ItemList;
}
}