Code :
public String[][] getExcelData(String excellocation, String sheetName) {
try {
String dataSets[][] = null;
FileInputStream file = new FileInputStream(new File(excellocation));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheet(sheetName);
// count number of active rows
int totalRow = sheet.getLastRowNum();
// count number of active columns in row
int totalColumn = sheet.getRow(0).getLastCellNum();
// Create array of rows and column
dataSets = new String[totalRow][totalColumn];
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
DataFormatter formatter = new DataFormatter();
int i = 0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
int j = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getStringCellValue().contains("TestCases")) {
break;
}
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
dataSets[i][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_STRING:
dataSets[i][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
}
}
System.out.println("");
}
file.close();
return dataSets;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
String excellocation = "C:\\Users\\Sivaranjani Gopal\\Desktop\\siva.xlsx";
String sheetName = "testdata";
ExcelReaderpg excel = new ExcelReaderpg();
Object[][] data = excel.getExcelData(excellocation, sheetName);
}
Note :
1.My Query is the value of i is always said to be 0. so dataset[0][1] for 1st row
for second row it should be dataset [1][0] [1][1] and so on.
why does i value remain the same and i get the desired output.
Can some one explain the value of i and j implementation in the array
In my program I want to find the row number in the excel sheet matching the string I have passed as argument . It works fine for first and second row but problem is with the next rows. My code to find row number is as below :
public int findrownum(String sName, String value, int cNum) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
boolean check = true;
int i=0;
while (check){
XSSFRow rowH = ws.getRow(i);
XSSFCell cell = rowH.getCell(cNum);
String cellvalue = cellToString(cell);
if (cellvalue.equals(value)){
check = false;
}
else {
i = i+1;
}
}
return i;
}
}
I want to read third row that is the string with name registration from the excel
Sl No test case name result timestamp
1 login Pass 03/03/2014 12:11:43 PM
2 Registration
Please let me know what changes needs to be done in the code .
Thanks
I used the similar logic as mentioned by #eric in JUNIT now i am able to find the row number .But now its giving error while i try to read the data using this row number . My code to read data is as below . Please let me know what changes needs to be done public String dataread(String sName, int rNum, String cName) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
XSSFRow rowH = ws.getRow(rNum-1);
int totalRows = ws.getLastRowNum();
int i =0;
for(i=0;i<=totalRows;i++)
{
XSSFCell cell = rowH.getCell(i);
String value = cellToString(cell);
if (value.equals(cName)){
System.out.println(i);
break;
}
}
XSSFRow row = ws.getRow(rNum);
XSSFCell cell = row.getCell(i);
String value = cellToString(cell) return value;
}
In general From this Documentation you can use the getHeight() to get in which your cursor instead of writing up your own loop. Obviously this would reduce the execution time as well. Also the code which you have written could have caused the exception,as there is no more physical rows.
ws.getRow(i); can cause a fatal error if i>height of the last row
Hope the following code helps. The assumption is the data in the cell is string data. Also this is with apache poi api.
public static String getcellValue(int testRowNo, int colNo)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
cellValue = workSheet.getRow(testRowNo).getCell(colNo).getStringCellValue();
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return cellValue;
}
public static int getrowNumber(String sheetName, String cellData)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
int testRowNo = 0;
for(int rowNo =1; rowNo<=totalRows; rowNo++)
{
row = workSheet.getRow(rowNo);
testRowNo = testRowNo +1;
if(row.getCell(0).getStringCellValue().equalsIgnoreCase(cellData))
{
break;
}
}
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return testRowNo;
}
Is there any possiblity to get all types(numeric,date,string etc) as String only.I couldn't find such methods.
sheet.getCell(rowIndex,colIndex) like this ?
InputStream ExcelFileToRead = new FileInputStream(file1);
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
String[] Excelarray=new String[26];
int count=0;
Map<String, String> data = new HashMap<String, String>();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+",");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+",");
}
else
{
}
}
System.out.println("----Closed");
}
Someone else already supplied a generic implementation that does what you are looking to do. POI doesn't have anything directly but it's easy enough to make a helper method/class.
Yes, It is possible to get all the values in the form of string.
Previously I had used DataFormatter to get the string value but while working with the large files I found it does not work so well.
Here is the required code: -
for (Row row : sheet) {
DataFormatter dataFormatter = new DataFormatter();
for (Cell cell : row) {
String cellValue = getStringCellValue(cell);
}
}
private static String getStringCellValue(Cell cell) {
try {
switch (cell.getCellType()) {
case FORMULA:
try {
return NumberToTextConverter.toText(cell.getNumericCellValue());
} catch (NumberFormatException e) {
return cell.getStringCellValue();
}
case NUMERIC:
return NumberToTextConverter.toText(cell.getNumericCellValue());
case STRING:
String cellValue = cell.getStringCellValue().trim();
String pattern = "\\^\\$?-?([1-9][0-9]{0,2}(,\\d{3})*(\\.\\d{0,2})?|[1-9]\\d*(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^-?\\$?([1-9]\\d{0,2}(,\\d{3})*(\\.\\d{0,2})?|[1-9]\\d*(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^\\(\\$?([1-9]\\d{0,2}(,\\d{3})*(\\.\\d{0,2})?|[1-9]\\d*(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))\\)$";
if (((Pattern.compile(pattern)).matcher(cellValue)).find()) {
return cellValue.replaceAll("[^\\d.]", "");
}
return cellValue.trim();
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case ERROR:
return null;
default:
return cell.getStringCellValue();
}
} catch (Exception e) {
if (e.getLocalizedMessage() != null && ConfigReader.isDisplayWarnLog())
return "";
}
return "";
}
It works well. Thank You.
Issues:-
The dataprovider is directly going to exception block
How to return value of cell from data provider to #Test method in order to achieve parameterisation
#DataProvider (name = "DP1")
public void getData() throws IOException {
try
{
FileInputStream file = new FileInputStream(new File("C:\\Users\\kk\\workspace\\K\\TestNG_Tutorial\\src\\Book1.xls"));
System.out.println(file);
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
java.util.Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//System.out.println("Row is" +row);
java.util.Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Test(dataProvider = "DP1")
public void LoginTest() {
driver.findElement(By.id("username")).sendKeys("A");
}
how to get last row of excel in POI and append blank row and write the next record after the blank row
Below is my code snippet
public class ResultSetToExcel {
private HSSFWorkbook workbook;
private HSSFSheet sheet;
private HSSFFont boldFont;
private HSSFDataFormat format;
private ResultSet resultSet;
private FormatType[] formatTypes;
public ResultSetToExcel(ResultSet resultSet, FormatType[] formatTypes, String sheetName) {
workbook = new HSSFWorkbook();
this.resultSet = resultSet;
sheet = workbook.createSheet(sheetName);
boldFont = workbook.createFont();
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
format = workbook.createDataFormat();
this.formatTypes = formatTypes;
}
public ResultSetToExcel(ResultSet resultSet, String sheetName) {
this(resultSet, null, sheetName);
}
private FormatType getFormatType(Class _class) {
if (_class == Integer.class || _class == Long.class) {
return FormatType.INTEGER;
} else if (_class == Float.class || _class == Double.class) {
return FormatType.FLOAT;
} else if (_class == Timestamp.class || _class == java.sql.Date.class) {
return FormatType.DATE;
} else {
return FormatType.TEXT;
}
}
public void generate(OutputStream outputStream) throws Exception {
try {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
if (formatTypes != null && formatTypes.length != resultSetMetaData.getColumnCount()) {
throw new IllegalStateException("Number of types is not identical to number of resultset columns. "
+ "Number of types: " + formatTypes.length + ". Number of columns: "
+ resultSetMetaData.getColumnCount());
}
int currentRow = 0;
HSSFRow row = sheet.createRow(currentRow);
int numCols = resultSetMetaData.getColumnCount();
boolean isAutoDecideFormatTypes;
if (isAutoDecideFormatTypes = (formatTypes == null)) {
formatTypes = new FormatType[numCols];
}
for (int i = 0; i < numCols; i++) {
String title = resultSetMetaData.getColumnName(i + 1);
writeCell(row, i, title, FormatType.TEXT, boldFont);
if (isAutoDecideFormatTypes) {
Class _class = Class.forName(resultSetMetaData.getColumnClassName(i + 1));
formatTypes[i] = getFormatType(_class);
}
}
currentRow++; // Write report rows
while (resultSet.next()) {
row = sheet.createRow(currentRow++);
for (int i = 0; i < numCols; i++) {
Object value = resultSet.getObject(i + 1);
writeCell(row, i, value, formatTypes[i]);
}
}
// Autosize columns
for (int i = 0; i < numCols; i++) {
sheet.autoSizeColumn((short) i);
}
workbook.write(outputStream);
} finally {
outputStream.close();
}
}
public void generate(File file) throws Exception {
generate(new FileOutputStream(file));
}
private void writeCell(HSSFRow row, int col, Object value, FormatType formatType) throws NestableException {
writeCell(row, col, value, formatType, null, null);
}
private void writeCell(HSSFRow row, int col, Object value, FormatType formatType, HSSFFont font)
throws NestableException {
writeCell(row, col, value, formatType, null, font);
}
private void writeCell(HSSFRow row, int col, Object value, FormatType formatType, Short bgColor, HSSFFont font)
throws NestableException {
HSSFCell cell = HSSFCellUtil.createCell(row, col, null);
if (value == null) {
return;
}
if (font != null) {
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
cell.setCellStyle(style);
}
switch (formatType) {
case TEXT:
cell.setCellValue(value.toString());
break;
case INTEGER:
cell.setCellValue(((Number) value).intValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat(("#,##0")));
break;
case FLOAT:
cell.setCellValue(((Number) value).doubleValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat(("#,##0.00")));
break;
case DATE:
cell.setCellValue((Timestamp) value);
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat(("m/d/yy")));
break;
case MONEY:
cell.setCellValue(((Number) value).intValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, format
.getFormat("($#,##0.00);($#,##0.00)"));
break;
case PERCENTAGE:
cell.setCellValue(((Number) value).doubleValue());
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT, HSSFDataFormat
.getBuiltinFormat("0.00%"));
}
if (bgColor != null) {
HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.FILL_FOREGROUND_COLOR, bgColor);
HSSFCellUtil
.setCellStyleProperty(cell, workbook, HSSFCellUtil.FILL_PATTERN, HSSFCellStyle.SOLID_FOREGROUND);
}
}
public enum FormatType {
TEXT, INTEGER, FLOAT, DATE, MONEY, PERCENTAGE
}
}
And class implementing the above code
ResultSetToExcel resultSetToExcel = new ResultSetToExcel(iResultSet, csv_file_name);
int fileCount = 1;
while (true) {
boolean done = resultSetToExcel.generate(new File(csv_file_path+ csv_file_name));
if (done) break;
csv_file_name = csv_file_name + "_" + fileCount + ".xls";
fileCount++;
}
Edit:
I used below snippet
InputStream myxls = new FileInputStream("test.xls");
Workbook book = new HSSFWorkbook(myxls);
Sheet sheet = book.getSheetAt(0);
System.out.println(sheet.getLastRowNum());
But I get this error
java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes
The key bit is the exception is the number 0:
java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes
POI went to read the 512 byte header that should be at the start of the file, but found 0 bytes in the file - your file is empty.
Make sure you're passing in the correct filename to load. (You mention struts in your tag, you might not be in the directory you expected to be when running...)
Also, I'd suggest a slight improvement to your code. You have a file, and you're using the common interfaces, so you should change how you load the workbook. Instead of your current:
InputStream myxls = new FileInputStream("test.xls");
Workbook book = new HSSFWorkbook(myxls);
You'd be much better off with
Workbook book = WorkbookFactory.create(new File("test.xls"));
Loading directly from a file, rather than going via an InputStream, will give better performance and a lower memory footprint. By using the WorkbookFactory, your code can work for both XLS and XLSX files.