So I am trying to read an excel sheet using Java code. Below is the code:
package com.SfHawk.Utility;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExcelApiTest {
public FileInputStream fis = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
public ExcelApiTest(String xlFilePath) throws Exception
{
fis = new FileInputStream(xlFilePath);
workbook = new XSSFWorkbook(fis);
fis.close();
}
public String getCellData(String sheetName, String colName, int rowNum)
{
try
{
int col_Num = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
for(int i = 0; i < row.getLastCellNum(); i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num = i;
}
row = sheet.getRow(rowNum - 1);
cell = row.getCell(col_Num);
if(cell.getCellType() == CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
{
String cellValue = String.valueOf(cell.getNumericCellValue());
if(HSSFDateUtil.isCellDateFormatted(cell))
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
Date date = cell.getDateCellValue();
cellValue = df.format(date);
}
return cellValue;
}else if(cell.getCellType() == CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e)
{
e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist in Excel";
}
}
}
Above code is giving me an error saying:
Incompatible operand types int and CellType
Initially I used cell.getCellTypeEnum() method instead of cell.getCellType(). But cell.getCellTypeEnum() gave me error saying, The method getCellTypeEnum() is undefined for the type XSSFCell
How can i fix this issue?
Thanks in advance.
Related
This my input in cell A4 there is a date. How can i get this in my java program as it is . My DateUtil.isCellDateFormated(Cell) not working .
i have used DataFormatter it is giving me no of days.
public String getDataValueAsString(Cell cell){
String value = null;
CellType type = cell.getCellTypeEnum();
DataFormatter dataFormat = new DataFormatter();
CreationHelper ch = null;
switch(type){
case BLANK:
value = "";
break;
case BOOLEAN:
value = String.valueOf(cell.getBooleanCellValue());
break;
case ERROR:
value = dataFormat.formatCellValue(cell);
break;
case FORMULA:
FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
value = dataFormat.formatCellValue(cell, evaluator);
break;
case NUMERIC:
if(DateUtil.isCellDateFormatted(cell)){
System.out.println("Cell is date formatted : ");
ch = cell.getSheet().getWorkbook().getCreationHelper();
short formatIndex = ch.createDataFormat().getFormat(cell.getCellStyle().getDataFormatString());
System.out.println("format index : "+formatIndex);
String format = cell.getCellStyle().getDataFormatString();
System.out.println("format : "+format);
}else{
//value = String.valueOf(cell.getNumericCellValue());
value = dataFormat.formatCellValue(cell);
}
break;
case STRING:
value = cell.getStringCellValue();
break;
default:
value = dataFormat.formatCellValue(cell);
}
return value;
}
It seems that you can try to use Cell.html#getDateCellValue() method.
Some quick example:
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.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
public class ExternalCaller {
public static final String MM_DD_YYYY = "MM/dd/yyyy";
public static void main(String... args) throws IOException {
FileInputStream file = new FileInputStream(new File("D:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int cellType = cell.getCellType();
try {
determineValue(cellType, cell);
} catch (UnsupportedOperationException ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void determineValue(int cellType, Cell cell) {
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC:
determineDate(cell);
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
default:
throw new UnsupportedOperationException("This type of cell should be additionally implemented");
}
}
private static void determineDate(Cell cell) {
short dataFormat = cell.getCellStyle().getDataFormat();
if (14 == dataFormat) {
Date dateCellValue = cell.getDateCellValue();
System.out.println(new SimpleDateFormat(MM_DD_YYYY).format(dateCellValue));
} else {
System.out.println(new DataFormatter().formatCellValue(cell));
}
}
}
The output for the cell
will be:
123.0546
Killme
78%
11/22/1995
This type of cell should be additionally implemented
1190
Please let me know if it works for you, otherwise I will remove the answer.
Testcase:
package Test;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Page.LoginPage;
import Utility.TestDataProvider;
import Utility.TestUtil;
//Testcase to perform login
public class LoginTest {
LoginPage page=new LoginPage();
#Test(dataProvider="ExcelDataProvider",dataProviderClass=TestDataProvider.class)
public void Logintest(String username,String password){
//page.login("user#phptravels.com","demouser");
page.login(username,password);
}
#AfterTest
public void TearDown(){
TestUtil.quit();
}
}
DataProvider:
package Utility;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestDataProvider {
static ExcelReader reader=new ExcelReader();
#DataProvider(name="ExcelDataProvider")
public static Object[][] ExcelDataProvider()
{
Object [][] rest = reader.readDataExcel("UserLogin");
return rest;
}
}
ExcelReader:
package Utility;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
static String fileName="Testdata";
public Object[][] readDataExcel(String TableName){
String filePath="F:\\TravelSite\\TravelSiteAutomation\\Testdata.xlsx";
File file =new File(filePath);
try{
FileInputStream stream=new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(stream);
XSSFSheet sheet=(XSSFSheet) workbook.getSheet("UnitTest");
List<XSSFTable> tables = sheet.getTables();
for(XSSFTable table:tables){
String name=table.getName();
if(name.equals(TableName)){
int ci=0,cj=0;
int rowNum=sheet.getLastRowNum()-sheet.getFirstRowNum();
//System.out.println(rowNum);
String[][] dataArray=new String[rowNum][100];
for(int i = 1; i < rowNum+1; i++) {
Row row = sheet.getRow(i);
//Create a loop to print cell values in a row
int colNum=row.getLastCellNum();
// System.out.println(colNum);
for(int j = 0; j <colNum; j++) {
//Print excel data in console
Cell cell=row.getCell(j);
DataFormatter formatter = new DataFormatter();
String var_name = formatter.formatCellValue(cell);
System.out.print(var_name+" || ");
dataArray[ci][cj]=var_name;
}
System.out.println();
}
workbook.close();
return dataArray;
}
}
Log.info("Table name is incorrect");
return null;
}
catch(Exception e)
{
Log.debug(e.getMessage());
return null;
}
}
}
so when i try to run the testcase i get an error
org.testng.TestNGException:
Data Provider public static java.lang.Object[][]
Utility.TestDataProvider.ExcelDataProvider() must return either
Object[][] or Iterator[], not class [[Ljava.lang.Object;
Nothing seems to resolve it,POI version 3.15, TestNGversion 6.10
The problem is with the ExcelReader class. Please find below the fixed version of the same which should solve the problem
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.ArrayList;
import java.util.List;
public class ExcelReader {
public static String[][] readDataExcel(String TableName) {
String filePath = "src/test/resources/Testdata.xlsx";
try {
Workbook workbook = new XSSFWorkbook(filePath);
XSSFSheet sheet = (XSSFSheet) workbook.getSheet("UnitTest");
List<XSSFTable> tables = sheet.getTables();
for (XSSFTable table : tables) {
String name = table.getName();
if (! name.equals(TableName)) {
continue;
}
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
System.out.println(rowCount);
int columnCount = - 1;
List<List<String>> data = new ArrayList<>();
for (int i = 1; i < rowCount + 1; i++) {
Row row = sheet.getRow(i);
int colNum = row.getLastCellNum();
if (columnCount == - 1) {
columnCount = colNum;
}
List<String> rowData = new ArrayList<>();
for (int j = 0; j < colNum; j++) {
Cell cell = row.getCell(j);
DataFormatter formatter = new DataFormatter();
String var_name = formatter.formatCellValue(cell);
if (var_name != null && ! var_name.trim().isEmpty()) {
rowData.add(var_name);
}
}
if (! rowData.isEmpty()) {
data.add(rowData);
}
}
workbook.close();
String[][] dataArray = new String[rowCount-1][columnCount];
int rowIndex = 0;
for (List<String> row : data) {
int colIndex = 0;
for (String rowData : row) {
dataArray[rowIndex][colIndex++] = rowData;
}
rowIndex++;
}
return dataArray;
}
System.err.println("Table name is incorrect");
return new String[][] {{}};
} catch (Exception e) {
e.printStackTrace();
return new String[][] {{}};
}
}
}
The code below is to read a large excel file. I got an "Cannot get a text value from a numeric cell at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch" error. How do I fix this. Column 1 is Numerical Value, Column 2 is String Value.
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;
public class ReadExcel {
public static void main(String[] args) throws Exception {
String filename = "C:/Documents and Settings/oemiola/My Documents/Defects_Input.xls";
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector<String> cellStoreVector=new Vector<String>();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
String cellvalue = myCell.getStringCellValue();
cellStoreVector.addElement(cellvalue);
}
String firstcolumnValue = null;
String secondcolumnValue = null;
int i = 0;
firstcolumnValue = cellStoreVector.get(i).toString();
secondcolumnValue = cellStoreVector.get(i+1).toString();
insertQuery(firstcolumnValue,secondcolumnValue);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
}
private static void insertQuery(String firstcolumnvalue,String secondcolumnvalue) {
System.out.println(firstcolumnvalue + " " +secondcolumnvalue);
}
}
Use Cell#getCellType to determine whether there is a number or a string in the cell. If it's numeric, then use getNumericCellValue instead of getStringCellValue.
I am using poi-3.8-20120326.jar and Excel 2007, trying to collect all the cell value in one list.
I am using formula for date increment operation. For example: =(i2+3) for k2 cell.
While evaluating this formula through my java code returns #VALUE! (i2 is a date cell.)
Without source it's hard to guess what's wrong, but I think that are two things that you may forget.
1) FormulaEvaluator
2) DataFormatter
Take a look at example.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class CellReader {
private Workbook workbook;
private DataFormatter formatter;
private FormulaEvaluator evaluator;
private void openWorkbook(String file) throws FileNotFoundException,
IOException, InvalidFormatException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
workbook = WorkbookFactory.create(fis);
evaluator = workbook.getCreationHelper().createFormulaEvaluator();
formatter = new DataFormatter(true);
} finally {
if (fis != null) {
fis.close();
}
}
}
private void printXLSX() {
Sheet sheet = null;
Row row = null;
Cell cell = null;
int lastRowNum;
int lastCellNum;
sheet = workbook.getSheetAt(0);
lastRowNum = sheet.getLastRowNum();
for (int j = 0; j <= lastRowNum; j++) {
row = sheet.getRow(j);
if (row == null) {
continue;
}
lastCellNum = row.getLastCellNum();
for (int k = 0; k <= lastCellNum; k++) {
cell = row.getCell(k);
if (cell == null) {
continue;
}
if (cell.getCellType() != Cell.CELL_TYPE_FORMULA) {
System.out.println(formatter.formatCellValue(cell));
} else {
System.out.println(formatter.formatCellValue(cell,evaluator));
}
}
}
}
public static void main(String[] args) {
CellReader converter = null;
try {
converter = new CellReader();
converter.openWorkbook("a.xlsx");
converter.printXLSX();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I am currently working on a project for my computer science class, and I was trying to figure out how to retrieve and print certain values from a file in excel. Such as, how would I go about printing the integer in column J, row 6?
Better yet, is there a way for me to return the row number of a string in column 1? Such as, if I had a string "Phone" in column 1, could I use a command to return the row number of the first instance of "phone"?
I have looked at other questions, none of which sufficiently answered my own.
Here you go refer to this class file for iterating over an excel file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
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;
public class Test {
private static final String FILE_NAME = "/users/developer/Documents/myFile.xlsx";
public void employeesUpload() {
String fName = "";
String lName = "";
String phoneNumber = "";
String email = "";
String gender = "";
String employeeCode = "";
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
int rowIndex = 0;
DataFormatter formatter = new DataFormatter();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
if (rowIndex > 0) {
Iterator<Cell> cellIterator = currentRow.iterator();
employeeCode = fName = lName = phoneNumber = email = gender = "";
int cellIndex = 0;
while (cellIndex <= 5) {
Cell currentCell = currentRow.getCell(cellIndex);
if (cellIndex == 4) {
employeeCode = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 1) {
fName = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 2) {
lName = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 0) {
email = formatter.formatCellValue(currentCell);
email = email.trim().toLowerCase();
}
if (cellIndex == 3) {
phoneNumber = formatter.formatCellValue(currentCell).trim();
}
cellIndex++;
}
Cell resultCell = currentRow.getCell(7);
if (resultCell == null) {
resultCell = currentRow.createCell(7);
}
Cell employementIdCell = currentRow.getCell(8);
if (employementIdCell == null) {
employementIdCell = currentRow.createCell(8);
}
if (true) {
resultCell.setCellType(Cell.CELL_TYPE_STRING);
employementIdCell.setCellValue("Success");
resultCell.setCellValue(email);
} else {
resultCell.setCellType(Cell.CELL_TYPE_STRING);
resultCell.setCellValue("Error");
}
}
rowIndex++;
}
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws ParseException, UnsupportedEncodingException {
Test employeesBulkUpload = new Test();
employeesBulkUpload.employeesUpload();
}
}
Hope this helps :)
user https://github.com/jueyue/easypoi this jar
use annotion to easy read excel
public class ExcelImportNewDateTest {
#Test
public void importTest() {
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
long start = new Date().getTime();
List<NewDateEntity> list = ExcelImportUtil.importExcel(
new File(FileUtilTest.getWebRootPath("import/ExcelNewDateTest.xlsx")), NewDateEntity.class, params);
System.out.println(new Date().getTime() - start);
Assert.assertEquals(list.size(), 100);
System.out.println(list.size());
System.out.println(ReflectionToStringBuilder.toString(list.get(1)));
}
}