reading excel rows properly - java

I am trying to read multiple rows of data from .xlsx file. The output in console shows the all values one below another.
Issue is they are not being displayed in the table like manner as they are displayed in source excel sheet.
My excel file is .xlsx, so I am coding with XSSF POI api.
It contains two columns(Name and Score) with 5 rows total.
Console output looks like this
Name
Score
TOM
1
DICK
2
HARRY
3
JERRY
4
I want it to print like this:
Name Score
TOM 1
DICK 2
HARRY 3
JERRY 4
code:
package gmailExcel;
import java.io.FileInputStream;
import java.io.IOException;
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 ReadXl {
public static void main(String[] args) throws IOException {
// Locate xl file.
FileInputStream fis = new FileInputStream
("File location on local host");
// Load file, workbook and sheet.
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet("sheetName");
// Declare row and cell variable.
XSSFRow row;
XSSFCell cells;
// Get row and column count.
int rowCount = ws.getLastRowNum();
int colCount = ws.getRow(0).getLastCellNum();
// Iterate over rows and columns.
for(int r = 0; r < rowCount; r++) {
row = ws.getRow(r);
for(int c = 0; c < colCount; c++) {
cells = row.getCell(c);
// Output the values from Excel sheet.
String cellval = cells.toString();
System.out.println(cellval);
}
}
}
}

The issue is in your nested for-loop. In each iteration, you are printing the value with a newline after it. What you want to do is to print the newline only after you've printed the cell in the second column I presume.
This can be accomplished by printing the newline outside the nested loop like this:
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < colCount; c++) {
cells = row.getCell(c);
String cellval = cells.toString();
System.out.print(" | " + cellval); //New line IS NOT printed
}
System.out.println(" |"); //New line IS printed
}

Related

Cannot invoke "org.apache.poi.ss.usermodel.Cell.getStringCellValue()" because the return value of org.apache.poi.ss.usermodel.Row.getCell(int) is null

I am accessing my Excel sheet data and I am able to get my output but along with that am getting an error:
Cannot invoke "org.apache.poi.ss.usermodel.Cell.getStringCellValue()" because the return value of org.apache.poi.ss.usermodel.Row.getCell(int) is null
I get this error on this line of code:
if(r.getCell(column).getStringCellValue().equalsIgnoreCase("Login ID")
This is my whole code:
package Exceltwo.guruExcel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
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 excelDataProvider {
//Identify Testcases column by scanning the entire 1st row
//once column is identified then scan entire testcase column to identify purchase testcase row
//after you grab purchase testcase row = pull all the data of that row and feed into test
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("C:\\Users\\mimo\\Desktop\\workbookexample.xlsx");
XSSFWorkbook workbook=new XSSFWorkbook(fis);
int sheets = workbook.getNumberOfSheets();
for (int i = 0; i < sheets; i++)
{
if (workbook.getSheetName(i).equalsIgnoreCase("Sheet1"))
{
XSSFSheet sheet = workbook.getSheetAt(i);
//Identify Testcases column by scanning the entire 1st row
Iterator<Row> rows = sheet.iterator(); // sheet is collection of rows
Row firstrow = rows.next();
Iterator<Cell> ce = firstrow.cellIterator(); // row is collection of cells
int k = 0;
int column = 0;
while (ce.hasNext())
{
Cell value = ce.next();
if (value.getStringCellValue().equalsIgnoreCase("Testcase"))
{
column = k;
}
k++;
}
System.out.println(column);
// once column is identified then scan entire testcase column to identify purchase testcase row
while (rows.hasNext())
{
Row r = rows.next();
if (r.getCell(column).getStringCellValue().equalsIgnoreCase("Login ID"))
{
// after you grab purchase testcase row = pull all the data of that row and feed into test
Iterator<Cell> cv = r.cellIterator();
while (cv.hasNext())
{
Cell c = cv.next();
System.out.println(c);
}
}
}
}
}
// TODO Auto-generated method stub
}
Excel Screenshot
Console Screenshot
As pointed out in the comments r.getCell(column) can return null.
Another option (besides checking for null) is to use CellUtil.getCell(r, column) which will not return null, as it will create the cell if it doesn't exist.
See https://poi.apache.org/apidocs/dev/org/apache/poi/ss/util/CellUtil.html#getCell-org.apache.poi.ss.usermodel.Row-int-
**Add one more if block for checking whether the cell is null or not then it will execute without any error...**
while(rows.hasNext())
{
Row r=rows.next();
if(r.getCell(column)!=null)
{
if(r.getCell(column).getStringCellValue().equalsIgnoreCase("Login ID"))
{
Iterator<Cell> cv=r.cellIterator();
while(cv.hasNext())
{
Cell c = cv.next();
System.out.println(c);
}
}
}
}
Change this
while (cv.hasNext())
to this
while (cv.hasNext() == true)
It because, there is no available value after the next / down cells of the given cell.

dataprovider excel file reading how skip first row

Heading
how to skip first row , if i make i=1 in for loop giving null null for
first row values
how to skip first row , if i make i=1 in for loop giving null null for
first row values
how to skip first row , if i make i=1 in for loop giving null null for
first row values
package excel2;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProvider2 {
XSSFSheet sheet;
int row ;
int col;
#Test(dataProvider = "excel")
public void tc_01(String Srno, String name,String add) {
System.out.println("name :" + Srno + "\t palce :" + name + " add :
"+add);
}
/**
* #author pritesh
* #return
* #throws IOException
*/
#DataProvider(name = "excel")
public Object[][] abc() throws IOException {
FileInputStream fl = new
FileInputStream("C:\\Users\\pritesh\\Desktop\\x22.xlsx");
XSSFWorkbook book = new XSSFWorkbook(fl);
sheet = book.getSheetAt(0);
row = sheet.getLastRowNum()+1;
col = sheet.getRow(0).getLastCellNum();
Object[][] obj = new Object[row][col];
for (int i = 1; i <row; i++) {
XSSFRow rw = sheet.getRow(i);
for (int j = 0; j <col; j++) {
obj[i][j] = rw.getCell(j).getStringCellValue();
}
}
return obj;
}
}
all the row except first row of excel sheet should be read and show in
console
all the row except first row of excel sheet should be read and show in
console
all the row except first row of excel sheet should be read and show in
console
all the row except first row of excel sheet should be read and show in
console
Try to add the below line after first for the loop
if (i=0){ continue; }

Excel formula on the current value/cell POI

I'm working on POI application in order to manipulate excel file.
In fact the user is giving a formula and files and I am applying the formula on a output file.The formula have to modify the value of the column on the cell.
For example on the columns B, I want to apply on all my column a formula.
The user is giving to me LEFT(x,2), and I have to apply this to all the columns.
(x is defining all the columns)
But when I am applying the formula I got the formula as a String. I try to pass the cell value at the formula but of course it is not working...
I think I should copy all my data into a another excel file, work on it and copy paste them in the output file or their is another way ?
Regards,
Code:
for (int i = 0; i < cell[0].length; i++){ //Checking the header
for (int j = 0; j < ruleArray.length; j++){ //Checking the Header of the array with the rule to apply
if (cell[0][i].toString().equals(ruleArray[j][0])){ //Comparing
String testF = ruleArray[j][1];
if (testF.contains("X") || testF.contains("x")){ //Replacing X with value for the formula
for (int k = 0; k < cell.length; k++){
indexT = cell[0][i].getColumnIndex();
indexC = cell[k][i].getRowIndex()+1;
String colLetter = CellReference.convertNumToColString(indexT);
formula = testF.replace("x", colLetter+indexC);
cell[k][i].setCellType(CellType.FORMULA);
cell[k][i].setCellFormula(formula);
}
}
}
}
}
I am not rewrite your code but you can take a help from this. Create a excel file with column City and Formula and then run this code. I have attached some snapshot of excel file. I thin kit will help you. LEFT(X,2) only parse first two char from a string
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class TestProblem
{
public static void main(String[] args) throws IOException {
InputStream inp = null;
inp = new FileInputStream("E:\\Projects\\PoiAdvanceExample\\stackProblem.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
int rowsCount = sheet.getLastRowNum();
int columnCount = sheet.getRow(0).getLastCellNum();
String[][] inputData = new String[rowsCount+1][columnCount];
for (int i = 0; i <= rowsCount; i++) {
Row row = sheet.getRow(i);
int colCounts = row.getLastCellNum();
for (int j = 0; j < colCounts; j++) {
Cell cell = row.getCell(j);
if(cell.getCellType() == CellType.NUMERIC) {
inputData[i][j] = Double.toString(cell.getNumericCellValue());
}
if(cell.getCellType() == CellType.FORMULA) {
inputData[i][j] = cell.getCellFormula();
}
if(cell.getCellType() == CellType.STRING) {
inputData[i][j] = cell.getStringCellValue();
}
}
}
writeData(inputData);
}
private static void writeData(String[][] inputData) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
int r = 0;
for (String[] dataRow : inputData) {
Row row = sheet.createRow(r++);
int column = 0;
for (String dataCell : dataRow) {
Cell cell = row.createCell(column++);
if (r == 1 || column == 1) cell.setCellValue(dataCell);
else if (column == 2) {
CellReference cellReference = new CellReference(cell);
String thisR = cellReference.getCellRefParts()[1];
cell.setCellFormula("LEFT(A" + thisR + ",2)");
}
}
}
FileOutputStream fileOut = new FileOutputStream("stackProblem.xlsx");
workbook.write(fileOut);
workbook.close();
}
}
Excel file before run will be like this.
Excel file after run this code will be like this.

How to remove the index out of bound error in my program?

I have tried various ways of removing the index out of bound error by changing the upper limits of the array.But the error persists. Where am I going wrong?
Screenshot of my excel sheet
My program reads values(all rows) in the first column of excel sheet and finds the maximum value. Then based on the maximum value,criteria are formulated and the values are classified as Low,Medium,High and written back into a new excel sheet.
import java.io.FileInputStream;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import java.io.*;
import java.util.*;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.Label;
import jxl.write.WriteException;
public class Bus3{
List<String> numbusarray = new ArrayList<String>();
List<String> numcommutersarray = new ArrayList<String>();
List<String> numcommercialarray = new ArrayList<String>();
static WritableWorkbook workbook;
static WritableSheet wSheet;
public void readExcel() throws BiffException, IOException, WriteException//method to read contents form excel
{
String FilePath = "Bus1.xls";
Scanner sc = new Scanner(System.in);
int max=0;
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet("Bus1");// TO get the access to the sheet
int totalNoOfRows = sh.getRows();// To get the number of rows present in sheet
int totalNoOfCols = sh.getColumns();// To get the number of columns present in sheet
System.out.println(totalNoOfRows);
//adding excel contents from every column to arraylist
for (int row = 1; row <totalNoOfRows; row++)
{
numbusarray.add(sh.getCell(2, row).getContents());
}
for (int row = 1; row <totalNoOfRows; row++)
{
numcommutersarray.add(sh.getCell(3, row).getContents());
}
for (int row = 1; row <totalNoOfRows; row++)
{
numcommercialarray.add(sh.getCell(4, row).getContents());
}
//to find maximum of numbusarray
max=Integer.parseInt(numbusarray.get(0));
for (int row = 1; row < totalNoOfRows-1; row++)
{
if(!(numbusarray.get(row)).isEmpty())
{
int intNumber=Integer.parseInt(numbusarray.get(row));
if(intNumber>max)
{
max=intNumber;
//System.out.println(max);
}
}
}
System.out.println(max);
WritableWorkbook workbook = Workbook.createWorkbook(new File("sampletestfile.xls"));
WritableSheet wSheet = workbook.getSheet(0);
int increment=max/3;
int a=increment;
int b=a+increment;
int c=b+increment;
for (int row = 0; row < totalNoOfRows-1; row++)
{
if(!(numbusarray.get(row)).isEmpty())
{
int compare=Integer.parseInt(numbusarray.get(row));
if(compare<=a)
{Label label= new Label(0, row, "Low");//column,row,strngdata
wSheet.addCell(label);}
else if((compare>a)&&(compare<=b))
{Label label= new Label(0, row, "Medium");//column,row,strngdata
wSheet.addCell(label);}
else
{Label label= new Label(0, row, "High");//column,row,strngdata
wSheet.addCell(label);}
}
}
/*Iterator itr=numbusarray.iterator(); //to print arraylist demo
while(itr.hasNext()){
System.out.println(itr.next());
}*/
}//end of method to read contents from excel
//to close file
public static void closeFile()
{
try {
// Closing the writable work book
workbook.write();
workbook.close();
// Closing the original work book
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[]) throws BiffException, IOException, WriteException //main class
{
Bus3 DT = new Bus3();
DT.readExcel();
Bus3.closeFile();
}//end of main class
}
It is because your sh Sheet.class object doesn't have cells with column = 4.
This should fix it:
for (int row = 1; row < totalNoOfRows; row++) {
numbusarray.add(sh.getCell(1, row).getContents());
}
for (int row = 1; row < totalNoOfRows; row++) {
numcommutersarray.add(sh.getCell(2, row).getContents());
}
for (int row = 1; row < totalNoOfRows; row++) {
numcommercialarray.add(sh.getCell(3, row).getContents());
}
LAST EDIT:
for (int row = 1; row < totalNoOfRows; row++) {
numbusarray.add(sh.getCell(1, row).getContents());
}
for (int row = 1; row < totalNoOfRows; row++) {
numcommutersarray.add(sh.getCell(2, row).getContents());
}
for (int row = 1; row < totalNoOfRows; row++) {
numcommercialarray.add(sh.getCell(3, row).getContents());
}
// to find maximum of numbusarray
max = 0;
for (int row = 1; row < totalNoOfRows; row++) {
if (!(numbusarray.get(row - 1)).isEmpty()) {
int intNumber = Integer.parseInt(numbusarray.get(row - 1));
if (intNumber > max) {
max = intNumber;
System.out.println("max: " + max);
}
}
}
System.out.println(max);
workbook = Workbook.createWorkbook(new File("sampletestfile.xls"));
WritableSheet wSheet = workbook.createSheet("name", 0);
It does not look like a very complex problem.
Index out of bounds means that you are trying to access a position in the array that does not exists.
Watch your numbusarray variable, probably row is being set to an invalid index.
Good afternoon, for me what worked was to create a new xls file, and copy the data from the old to the new one. and the errors stopped.

values are populating with 2 only

I'm a newbie to java & I'm trying to read numeric data from a text file & I want to write each number in a separate cell in an Excel spreadsheet.
Input data is as below:(abc.txt)
3008,45,14,277,10,6371,223,208,116,3036,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,‌​0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2 2893,114,16,108,30,5066,245,223,102,4340,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0‌​,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2
I want each value in a different cell. I'm using Apache POI for using excel sheets. This is what I'm able to code till now
package com.example.practise;
import java.io.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
//import org.apache.poi.ss.usermodel.Creationhelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
public class MultivariateDT {
public static void main(String[] args) throws IOException{
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:/Users/419803/Desktop/abc.txt"));
FileOutputStream out = new FileOutputStream("C:/Users/419803/Desktop/workbook.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("new sheet");
Row row = null;
Cell cell = null;
String line = null;
String delimiter = ",";
while ((line = bufferedReader.readLine()) != null)
{
String[] temp=null;
String str = " ";
temp = line.split(delimiter);
for(int i =0; i < temp.length ; i++)
{
str = temp[i] + str;
int rownum;
for (rownum =0; rownum < 100; rownum++)
{
row = sheet1.createRow(rownum);
for (int cellnum =0; cellnum <temp.length; cellnum ++)
{
cell = row.createCell(cellnum);
cell.setCellValue(temp[i]);
}
}
}
System.out.println();
}
wb.write(out);
out.close();
}
}
No.of rows & cells that have to be created are correct, but data in excel file is wrong.
In excel file only showing 2,2,2,2 so on.
Can any one please help me??
I think you have too many for-loops with which you are iterating too much, i.e. first you loop over all items in the line, for these you create 100 rows and in each row you iterate overa all items in the line again, creating rows, bug in setCellValue() you are using temp[i], not temp[cellnum], so you are first creating 100 rows with temp[0], then 100 rows with all temp[1], ...
It depends on how the resulting spreadsheet should look like, but I would try to adjust the for-loops accordingly, e.g. for one row per line you would remove the outer too for-loops, for 100 rows per line you would remove the single outer for-loop.

Categories