E. Trauger E. Trauger -4 years ago 219
Java Question

Java Apache POI -- Creating an iterator to find a date

I am attempting to find the cell reference for a specific date in an Excel file. The Excel is set up so that the "Date" header is in A1, and dates are included across the same row in B1, C1, etc.

I attempted to create an iterator to go through these dates and compare them to an input date.
I omitted some code below for conciseness.

public static void main(String[] args) throws IOException, ParseException {
SimpleDateFormat formatter ;
formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = formatter.parse(args[0]);

// ............

// iterator to find date
int dateRef = 0; //logs column of date
Date tempDate = null;
// while loop to check the date contents of each cell
while (dateRef < 1000) { // random number inserted
tempDate = cell.getDateCellValue();
if (date == tempDate) {
break; //beaks if contents are equal
cell = results.getRow(0).getCell(dateRef); // else continue and iterate one cell

When I run this, the iterator keeps going right up to column 1000. I checked this with print statements. Even though the cell is landing on the correct date, it does not recognize the input date and the cell date value as the same, and therefore does not break.

I know this may not be the most efficient way of doing things, so if you have more suggestions, let me know about them. Thank you!

Answer Source

You should not use the == operator in this case. I would try with equals or compareTo in your case in order to find the proper date.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download