dataprovider excel file reading how skip first row - java

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; }

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.

Stream an arraylist into a fixed two dimensional array and print?

I've been successful at reading an XLS worksheet to an ArrayList. Now the tricky part is that I'm trying to map this to a fixed two dimensional array. ArrayList(i) --> Array(x)(y) Where i = 1705 and x = 155 and y = 11 respectively.
Edit: Maybe I wasn't clear on the questions part as stated.
I'm trying to copy the elements of the below mentioned Excel (Book1.xls) to a two dimensional array. So far I've been succesful into copying ti into an arraylist: "singleRows". But I'm having trouble moving them to the two dimensional array: "myReplicate".
I want to use the elements of this array to create SQL insert statements.
Hope I haven't missed anything in specifying the requirement.
package excelread3;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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;
public class ExcelRead3
{
public static void main(String[] args) throws IOException
{
FileInputStream file = new FileInputStream(new File("C:\\Users\\CReaper\\Documents\\docs\\Opice\\Book1.xls"));
HSSFWorkbook wb = new HSSFWorkbook(file);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow firstRow = sheet.getRow(0);
int rowcount = sheet.getPhysicalNumberOfRows();
int colcount = firstRow.getLastCellNum();
Iterator<Row> rowIterator = sheet.iterator();
ArrayList<Object> singleRows = new ArrayList<Object>();
ArrayList<Object> list = new ArrayList<Object>();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Iterator <Cell> cellIterator = row.cellIterator();
for( int i =1 ; i < colcount ; i++ )
{
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//System.out.print(cell.getStringCellValue() + "\t\t");
singleRows.add(cell.getStringCellValue());
}
}
list.add(singleRows);
}
// System.out.println(rowcount + "\n");
// System.out.println(colcount + "\n");
Stream<Object> stringStream;
stringStream = singleRows.stream();
String[][] myReplicate = new String[rowcount][colcount];
myReplicate = stringStream.toArray(new String[stringStream.size()]);
for (int i = 0; i < rowcount; i++)
{
for(int j = 0; j < colcount; j++)
{
System.out.printf("%5d ", myReplicate[i][j]);
}
System.out.println();
}
file.close();
}
}
I'm trying to convert the ArrayList to a Stream before filling the array elements.
Just checked across for mapping an excel to a two dimensional array.
And found this:
String[][] excelData = new String[numRows][numCols];
for (int i=0; i<numRows; i++)
{
HSSFRow row = mySheet.getRow(i);
for (int j=0; j<numCols; j++)
{
HSSFCell cell = row.getCell(j);
String value = cell.getStringCellValue();
excelData[i][j] = value;
System.out.println(Arrays.deepToString(excelData));
}
System.out.println();
}
}
System.out.println();
}
This helped me further my requirement.
Thanks for the attention spared for this.

reading excel rows properly

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
}

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.

Delete Excel rows programmatically using Java

Finding last column cell values. if cell value is "Not Valid" or "Not Applicable", delete the entire row.
The code I have written so far is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
public class Column
{
public static void main(String[] args) throws InvalidFormatException, FileNotFoundException, IOException
{
try
{
Workbook wb = WorkbookFactory.create(new FileInputStream("C:/Users/Excel1.xlsx"));
Sheet sheet = wb.getSheet("Retail-All");
Workbook wb2 = new HSSFWorkbook();
wb2 = wb;
Row row;
row = sheet.getRow(0);
int getLastCell=row.getLastCellNum()-1;
int lastIndex = sheet.getLastRowNum();
for (int i=0; i<=lastIndex; i++)
{
row=sheet.getRow(i);
if(row.getCell(getLastCell)!=null && (row.getCell(getLastCell).toString().equalsIgnoreCase("Not valid) || row.getCell(getLastCell).toString().equalsIgnoreCase("Not Applicable")))
{
sheet.removeRow(row);
//sheet.shiftRows(i, lastIndex, -1);
}
}
FileOutputStream fileOut = new FileOutputStream("C:/Users/shiftRows.xlsx");
wb2.write(fileOut);
fileOut.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
With the above code, using row.setZeroHeight(true); method I can able to hide the rows.
With the above code, using sheet.removeRow(row); method I can able to empty all the cells in that particular row.
I found some code in net, but none of them are deleting the rows permanently.My requirement is to delete the rows permanently. How to code to meet my requirement?
Perhaps using a VBA macro would be more helpful in this situation? VBA macros can be embedded into your spreadsheet, so running them could be a lot easier.
Here is a good place to get started with VBA:
http://msdn.microsoft.com/en-us/library/office/ee814737(v=office.14).aspx
Try this one...
SVTableModel model = new SVTableModel(sheet);
int lastIndex = model.getRowCount();
for (int i=1; i<=lastIndex; i++)
{
row=sheet.getRow(i);
if((row.getCell(getLastCell)!=null) && (row.getCell(getLastCell).toString().equalsIgnoreCase("Not valid") || row.getCell(getLastCell).toString().equalsIgnoreCase("Not Applicable")))
{
row.setZeroHeight(true);
sheet.removeRow(row);
}
Instead of sheet.removeRow(row); you can use the shiftRows(int startRow, int endRow, int n) instruction, that seems you have tried, that shifts rows between startRow and endRow n number of rows.
In your case it will be
// ... code before ...
for (int i=0; i<=lastIndex; i++)
{
row=sheet.getRow(i);
if(row.getCell(getLastCell)!=null && (row.getCell(getLastCell).toString().equalsIgnoreCase("Not valid") || row.getCell(getLastCell).toString().equalsIgnoreCase("Not Applicable")))
{
// This should shift up by 1 row all the rows below
sheet.shiftRows(i+1, lastIndex, -1);
i--; // Since you move row at i+1 to i you have to recompute the i-th row
}
}
// ... code after ...
Check org.apache.poi.hssf.usermodel.HSSFSheet Documentation for more information
Please try the below code. My last cell value is Mismatched ot
Matched. Set as per ur excel.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DeleteAllRecord {
public static void main(String[] args) {
try{
File src= new File("testdata\\OSBC.xlsx");
FileInputStream fis= new FileInputStream(src);
XSSFWorkbook workbook= new XSSFWorkbook(fis);
XSSFSheet data= workbook.getSheet("TestData");
int length=data.getLastRowNum();
XSSFSheet data1;
Row row1;
for(int i=1;i<=length;i++){
String testCaseNo=data.getRow(i).getCell(4).toString();
System.out.println("The Testcase no "+testCaseNo);
data1= workbook.getSheet(testCaseNo);
row1 = data1.getRow(2);
int getLastCell=row1.getLastCellNum()-1;
System.out.println("The last cell is "+getLastCell);
int lastIndex = data1.getLastRowNum();
System.out.println("The last row is "+lastIndex);
String str1= row1.getCell(getLastCell).toString();
System.out.println("The valu1 is "+ str1);
for (int j=0; j<lastIndex-1; j++)
{
String str=data1.getRow(j+2).getCell(getLastCell).toString();
row1=data1.getRow(j+2);
System.out.println("print " + (j+2) +str);
if(row1.getCell(getLastCell)!=null &&
(row1.getCell(getLastCell).toString().equalsIgnoreCase("MATCHED")||
row1.getCell(getLastCell).toString().equalsIgnoreCase("MISMATCHED")||
row1.getCell(getLastCell).toString().equalsIgnoreCase(""))){
data1.removeRow(row1);
System.out.println("print " + (j+2)+ " " +str);
}
else{
System.out.println("Null");
}
}
FileOutputStream fileOut = new FileOutputStream("testdata\\delete.xlsx");
workbook.write(fileOut);
fileOut.close();
System.out.println("File deleted");
}
}
catch(Exception e){
System.out.println("No Data Exists to delete");
}
}
}

Categories