Unreachable code in my 'for' loop - java

I am coding a program to format the contents of an excel file. Eclipse is saying that the line Cell cell = cellIterator.next(); is unreachable and I don't understand why. Where did I go wrong?
private String formatExcel(File excel)
{
this.statusLabel.setText("formatting...");
try
{
FileInputStream file = new FileInputStream(excel);
try
{
this.workbook = WorkbookFactory.create(file);
}
catch (InvalidFormatException ex)
{
file.close();
}
int excelType = 0;
if ((this.workbook instanceof HSSFWorkbook)) {
excelType = 1;
}
int sheetNum = 0;
try
{
sheetNum = Integer.parseInt(this.sheetNumber.getText());
}
catch (NumberFormatException e)
{
file.close();
}
if ((sheetNum < 1) || (sheetNum > this.workbook.getNumberOfSheets()))
{
file.close();
return "Please input a valid sheet number.";
}
Sheet sheet = this.workbook.getSheetAt(sheetNum - 1);
sheet.setZoom(17, 20);
Iterator<Row> rowIterator = sheet.iterator();
int startRow = Integer.MAX_VALUE;
Iterator<Cell> cellIterator;
for (; rowIterator.hasNext(); cellIterator.hasNext())
{
Row row = (Row)rowIterator.next();
cellIterator = row.cellIterator();
continue;
Cell cell = (Cell)cellIterator.next(); // <- this line is unreachable
switch (cell.getCellType())
{
case 4:
break;
case 0:
break;
case 1:
if (cell.getStringCellValue().trim().equalsIgnoreCase("Condition Code")) {
startRow = cell.getRowIndex();
}
if ((cell.getRowIndex() > startRow + 1) && (cell.getColumnIndex() > 0) && (cell.getColumnIndex() < 5)) {
if (excelType == 0) {
cell.setCellValue(formatCellXSSF(
cell.getStringCellValue(),
cell.getColumnIndex()));
} else {
cell.setCellValue(formatCellHSSF(
cell.getStringCellValue(),
cell.getColumnIndex()));
}
}
if (!cell.getStringCellValue().trim().equalsIgnoreCase("<<Test Data>>")) {
if (!cell.getStringCellValue().trim().equalsIgnoreCase("<<Screenshots>>")) {
break;
}
}
break;
}
}
sheet.autoSizeColumn(5);
file.close();
FileOutputStream out = new FileOutputStream(excel);
this.workbook.write(out);
out.close();
return "";
}
catch (FileNotFoundException ex)
{
return "Error. File is open. Please close it first.";
}
catch (IOException ex) {}
return "Cannot format file because it is open. Please close it first.";
}

You have an unconditionnal continue in your for loop. Next statements are never executed, no way.
for (; rowIterator.hasNext(); cellIterator.hasNext())
{
Row row = (Row)rowIterator.next();
cellIterator = row.cellIterator();
continue;
Cell cell = (Cell)cellIterator.next();

Related

Can't read a cell value from using Jexcel API

I am trying to read a .xls file by JExecel Api. I can read some column data by using cell.getContents() easily. But some column give me mysterious value 1, but column type looks like Date. So i check those column type and Find they are Number Type. So i cast those cell in NumberCell. But output looks still mysterious 1.
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook("StandardReport.xls");
Sheet sheet = workbook.getSheet(0);
Cell[] cellRow = sheet.getColumn(0);
for (int row = 4; row < cellRow.length; row++) {
String id = cellRow[row].getContents().trim();
if (id.isEmpty() == false) {
Cell cell1 = sheet.getCell(1, row);
Cell cell2 = sheet.getCell(2, row);
Cell cell3 = sheet.getCell(3, row);
System.out.println(cell1.getContents()+"");
System.out.println(cell2.getContents()+"");
System.out.println(cell3.getContents()+"");
if (cell3.getType() == CellType.NUMBER) {
NumberCell date=(NumberCell)cell3;
System.out.println(date.getContents()+"");
}
/*if (cell3.getType() == CellType.BOOLEAN) {
System.out.println("2");
}
if (cell3.getType() == CellType.BOOLEAN_FORMULA) {
System.out.println("3");
}
if (cell3.getType() == CellType.DATE_FORMULA) {
System.out.println("4");
}
if (cell3.getType() == CellType.EMPTY) {
System.out.println("5");
}
if (cell3.getType() == CellType.ERROR) {
System.out.println("6");
}
if (cell3.getType() == CellType.FORMULA_ERROR) {
System.out.println("7");
}
if (cell3.getType() == CellType.LABEL) {
System.out.println("8");
}
if (cell3.getType() == CellType.NUMBER) {
System.out.println("9");
}
if (cell3.getType() == CellType.NUMBER_FORMULA) {
System.out.println("11");
}
if (cell3.getType() == CellType.STRING_FORMULA) {
System.out.println("12");
}*/
}
}
} catch (IOException | BiffException ex) {
StaticAccess.showMessageDialog("Failed!!", ex);
}
Here is the file link of StandardReport.xls

How to increment my row counter variable in my while loop?

I am trying to read in each row that has data in the first cell into an ArrayList of Objects. My problem is that my code doesn't seem to be incrementing my counter past the first row. Am I missing something simple?
Code
try
{
wb = new XSSFWorkbook(new FileInputStream(fileName));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
XSSFSheet sheet = wb.getSheetAt(2);
ArrayList<Object> obj = new ArrayList<Object>();
int rowIndex = 0;
int cellIndex = 0;
XSSFRow row = sheet.getRow(rowIndex);
Iterator<Cell> rowItr = row.iterator();
while(rowIndex <= sheet.getLastRowNum())
{
if(row.getCell(0) == null)
{
continue;
}
else
{
while(rowItr.hasNext() && rowItr.next() != null)
{
XSSFCell cell = row.getCell(cellIndex);
if(cell == null)
{
continue;
}
else
{
obj.add(row.getCell(cellIndex).toString());
}
cellIndex++;
}
rowIndex++;
cellIndex = 0;
}
System.out.println(obj.toString());
}
rowIndex++;
}
}
Output
[ValuSmart Series 1120 Double Hung]
... I get this output 72 times since there are 72 rows in the sheet
Isolated Loop
ArrayList<Object> obj = new ArrayList<Object>();
int rowCounter = 16;
int x = 0;
while(rowCounter <= 21)
{
XSSFRow row = sheet.getRow(rowCounter);
Iterator<Cell> rowItr = row.iterator();
while(rowItr.hasNext() && rowItr.next() != null)
{
XSSFCell cell = row.getCell(x);
if(cell == null)
{
continue;
}
else
{
obj.add(row.getCell(x).toString());
}
x++;
}
rowCounter++;
x = 0;
}
System.out.println(obj.toString());
You're not select the next row anywhere, and your loops are confusing and switch between index- and iterator-based lookups. Try a simple enhanced for loop:
for (Row row : sheet) {
for (Cell cell : row) {
if (cell != null) {
obj.add(row.getCell(x).toString());
}
}
}
System.out.println(obj.toString());

Reading from Excel file failing (ORA-00947-not enough values)

Using the first method i am writing the query results to xls file and using second i am uploading to destination DB. It works fine with the Excel files created by the first method. If i edit any created excel file it fails to read some cells and throws error. Any body faced this issue. Any solution or suggesion.
TIA
public void exportData(Map<String, String> queries,Connection conn) {
Connection connection=conn;
try{
List<String> list1=new ArrayList<String>(queries.keySet());
for(int j=0;list1.size()>j;j++){
Workbook book1=new HSSFWorkbook();
Sheet Sheet1= book1.createSheet("sheet1");
PreparedStatement preparedStatement = connection.prepareStatement(queries.get(list1.get(j)));
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData rsmd=resultSet.getMetaData();
boolean isDataAvail = resultSet.next();
if(isDataAvail){
Row headerRow = Sheet1.createRow(0);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
Cell cell1 = headerRow.createCell(i-1);
cell1.setCellValue(rsmd.getColumnName(i));
}
int row=1;
do {
Row row1 = Sheet1.createRow(row);
for (int i = 1; i <=rsmd.getColumnCount(); i++) {
Cell cell2 = row1.createCell(i-1);
String s=rsmd.getColumnTypeName(i);
if(s.equalsIgnoreCase("NUMBER")){
if(resultSet.getString(i)==null)
cell2.setAsActiveCell();
else{
cell2.setCellValue(resultSet.getDouble(i));
}
}else if(s.equalsIgnoreCase("VARCHAR2")||s.equalsIgnoreCase("VARCHAR")){
if(resultSet.getString(i)==null)
cell2.setAsActiveCell();
else
cell2.setCellValue(resultSet.getString(i));
}else if(s.equalsIgnoreCase("DATE")){
if(resultSet.getDate(i)==null)
cell2.setAsActiveCell();
else{
cell2.setCellValue((Date)resultSet.getTimestamp(i));
CellStyle style = book1.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
cell2.setCellStyle(style);
}
}else{
cell2.setCellValue(resultSet.getString(i));
}
} row++;
}while (resultSet.next());
String fname1=folder+list1.get(j)+".xls";
FileOutputStream output;
output=new FileOutputStream(new File(fname1));
book1.write(output);
output.close();
listOfDataTables.add(list1.get(j));
fileNum++;
query++;
logger.info("F.no."+fileNum+"."+list1.get(j)+"--File created successfully");
}
else{
query++;
logger.info("No data found for table"+"("+query+") :"+list1.get(j));
}
resultSet.close();
}
}
catch (Exception exception) {
logger.info("*****ERROR*****"+exception);
logger.log(Level.SEVERE, exception.getMessage(), exception);
exception.getLocalizedMessage();
exception.printStackTrace();
status="ERROR";
}
finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
logger.info("*****ERROR*****"+e);
e.printStackTrace();
}
}
}
}
public int dataTransfer(String fileName,Connection connection) {
int no=0;
String fName=folder+fileName+".xls";
try {
Statement preparedStatement =connection.createStatement();
FileInputStream inputFile = new FileInputStream(fName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(inputFile);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
String insertQuery="";
String columnQuery="";
if(rowIterator.hasNext()){
columnQuery="insert into "+fileName+"(";
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
columnQuery=columnQuery+cell.getStringCellValue()+",";
no++;
}
columnQuery=columnQuery.substring(0, columnQuery.length()-1);
columnQuery=columnQuery+") values (";
}
int rowCounter=0;
int set=0;
while (rowIterator.hasNext() && set<=no)
{
insertQuery=columnQuery;
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(cell)){
double temp=cell.getNumericCellValue();
Date date = HSSFDateUtil.getJavaDate(temp);
String dateFmt = cell.getCellStyle().getDataFormatString();
String strValue = new CellDateFormatter(dateFmt).format(date);
strValue="to_date("+"'"+strValue+"'"+",'mm/dd/yyyy hh24:mi')";
insertQuery=insertQuery+strValue+",";
}else{
insertQuery=insertQuery+cell.getNumericCellValue()+",";
}
}
else if(cell.getCellType()==Cell.CELL_TYPE_STRING)
insertQuery=insertQuery+"'"+cell.getStringCellValue()+"',";
else if(cell.getCellType()==2){
insertQuery=insertQuery+cell.getDateCellValue()+",";
}
else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
insertQuery=insertQuery+"null,";
}
insertQuery=insertQuery.substring(0, insertQuery.length()-1);
insertQuery=insertQuery+")";
preparedStatement.addBatch(insertQuery);System.out.println(insertQuery);
rowCounter++;
}
preparedStatement.executeBatch();
inputFile.close();
listOfProcessedTables.add(fileName);
preparedStatement.close();
return rowCounter;
}
catch (Exception exception) {
logger.info("*****ERROR*****"+exception);
exception.printStackTrace();
logger.log(Level.SEVERE, exception.getMessage(), exception);
StatusCount++;
return 0;
}
}

unable to get out the Loop

I have been working with Apache POI and using my this code:
private void remove() {
HSSFWorkbook wb = null;
HSSFSheet sheet = null;
try {
FileInputStream is = new FileInputStream("C:/juni.xls");
wb = new HSSFWorkbook(is);
sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().contains("POST")) {
row_count_post_1 = row.getRowNum();
DashBoard.txt.setText("Processed the STRING \"POST\" on Row#" + row_count_post_1);
HSSFRow removingRow = sheet.getRow(row_count_post_1);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
int lastIndex = sheet.getLastRowNum();
sheet.shiftRows(row_count_post_1 + 1, lastIndex, -1);
} else {
break;
}////////////want to break from here;
}
}
}
} catch (Exception e) {
//do catch for no exception
}
}
The problem is that I want to get out of the loop when my if statement stops working. All is working fine if i don't use my else. Actually if a this code fails to locate a string it should stop but in my case the else suddenly works with my if and only one iteration will take place in this case.
Please tell me what I'm doing wrong please i just need the hints not the overall help. Thanks in advance
You question is unclear but explore that :
private void remove(){
HSSFWorkbook wb = null;
HSSFSheet sheet=null;
try {
FileInputStream is = new FileInputStream("C:/juni.xls");
wb = new HSSFWorkbook(is);
sheet = wb.getSheetAt(0);
//Tagging the loops
OuterLoop : for (Row row: sheet) {
InnerLoop : for (Cell cell: row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().contains("POST")) {
row_count_post_1 = row.getRowNum();
DashBoard.txt.setText("Processed the STRING \"POST\" on Row#" + row_count_post_1);
HSSFRow removingRow = sheet.getRow(row_count_post_1);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
int lastIndex = sheet.getLastRowNum();
sheet.shiftRows(row_count_post_1 + 1, lastIndex, -1);
} else {
break InnerLoop; // OR break OuterLoop;
} ////////////want to break from here;
}
}
}
} catch (Exception e) {
//do catch for no exception
}
}
You can use break with a label for the outer loop.
Please take a look on #jon-skeet's answer Or this example from the javadoc
Since there is no code after the finishing of the first loop you want to break from, just return.
} else {
return;
}
Although labels and break-to-label is valid syntax, I would refrain from such flow control. According to Dijkstra, a number of bugs in the code is proportional to the number of goto statements (and this break is a version of it). I just want to say: be careful with it. If you must have similar flow control, try to implement it using flags.
First of all please use Iterator for your loops (See Ref : http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/)
Second: You may have to do like this to stop your loop.
private void remove() {
HSSFWorkbook wb = null;
HSSFSheet sheet = null;
try {
FileInputStream is = new FileInputStream("C:/juni.xls");
wb = new HSSFWorkbook(is);
sheet = wb.getSheetAt(0);
for (Row row : sheet) {
boolean stop = false;
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().contains("POST")) {
row_count_post_1 = row.getRowNum();
DashBoard.txt.setText("Processed the STRING \"POST\" on Row#" + row_count_post_1);
HSSFRow removingRow = sheet.getRow(row_count_post_1);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
int lastIndex = sheet.getLastRowNum();
sheet.shiftRows(row_count_post_1 + 1, lastIndex, -1);
} else {
stop = true;
break;
}
}
if (stop) {
break;
}
}
}
} catch (Exception e) {
//do catch for no exception
}
}

Cell.getNumericCellValue returns null value when reading Excel file

Following is the code to print the sum of the cells in the same row in a loop. When I run, the first loop works fine and I get the value of the sum but during the second loop, it throws the null pointer exception at line double z= cell.getNumericCellValue(); after printing the value of z.
try{
FileInputStream file = new FileInputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
// HSSFCell cell = null;
Row r = sheet.getRow(0);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
double summ=1.0;
for(int i =1 ; i<=sheet.getLastRowNum(); i++){
for(int j=1; j<r.getLastCellNum();j++)
{
cell = sheet.getRow(i).getCell(j);
// if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType())
// {
double z= cell.getNumericCellValue();
System.out.println(z);
summ=summ+z;
// }
}
System.out.println(summ);
Cell mycell1=r.createCell(3);
mycell1.setCellValue(summ);
summ=0.0;
}
file.close();
FileOutputStream outFile =new FileOutputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
workbook.write(outFile);
outFile.close();
}catch (IOException e) {
e.printStackTrace();
}
}
Note: The excel file can be like:
Name sub1 Sub2
m 2 3
n 5 6
j 4 9
try this
try{
FileInputStream file = null;
try {
file = new FileInputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
double summ = 1.0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
int i = 0;
double z = 0.0;
while (cellIterator.hasNext()) {
cell = sheet.getRow(i).getCell(j);
if (i == 0) {
System.out.println(cell.getStringCellValue());
} else {
z = cell.getNumericCellValue();
}
System.out.println(z);
summ = summ + z;
i++;
// }
}
System.out.println(summ);
Cell mycell1 = r.createCell(3);
mycell1.setCellValue(summ);
summ = 0.0;
}
file.close();
FileOutputStream outFile = new FileOutputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
file.close();
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}

Categories

Resources