Reading an excel and calculate total using Java/Apache POI

1.4k Views Asked by At

Scenario:

I am working on an application which would open an excel file, iterate the rows of a worksheet and calculate the total of numeric values of each row.

Question:

Consider the following 2 cases:

enter image description here

enter image description here

If the output for the first case is:

A -> 15.0 pages.
B -> 15.0 pages.
T -> 15.0 pages.

Why is it that the output in the second case is:

Tanmay -> 15.0 pages.
Abhishek -> 15.0 pages.
Bijoy -> 15.0 pages.

Shouldn't it be as below?

Abhishek -> 15.0 pages.
Bijoy -> 15.0 pages.
Tanmay -> 15.0 pages.

Code:

package miscellaneous;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * Created by Sandeep on 8/6/15.
 */
public class TestHarness {

    @SuppressWarnings({ "unchecked" })
    public static void main(String[] args) {
        Map<String, Double> stringDoubleMap = new HashMap<String, Double>();
        stringDoubleMap = readExcelFile();

        for (Map.Entry<String, Double> entry : stringDoubleMap.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue() + " pages.");
        }
    }

    @SuppressWarnings("rawtypes")
    private static Map readExcelFile() {

        InputStream fileInputStream = null;
        HSSFWorkbook hssfWorkbook = null;
        HSSFSheet sheet;
        HSSFRow row;
        HSSFCell cell;
        Iterator rowIterator, cellIterator;
        String employeeName=null;
        String sheetName=null;
        double total=0;
        Map<String, Double> empMonthlyProdStat = new HashMap<String, Double>();

       try {
           fileInputStream = new FileInputStream("D:\\Sandeep\\TestExcelWorkbook.xls");
           hssfWorkbook = new HSSFWorkbook(fileInputStream);
           sheet = hssfWorkbook.getSheetAt(0);
           sheetName = sheet.getSheetName();
           rowIterator = sheet.rowIterator();

           while (rowIterator.hasNext()) {
               row = (HSSFRow) rowIterator.next();
               cellIterator = row.cellIterator();
               while (cellIterator.hasNext()) {
                   cell = (HSSFCell) cellIterator.next();

                   if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                       employeeName = cell.getStringCellValue();
                   } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                       total = total + cell.getNumericCellValue();
                   } else {// Handle Boolean, Formula, Errors
                   }
               }
               empMonthlyProdStat.put(employeeName, total);
               total = 0;
           }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                hssfWorkbook.close();
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(sheetName + "\n" + "------------");
        return empMonthlyProdStat;
    }

}
1

There are 1 best solutions below

2
On BEST ANSWER

The ordering is off because HashMap doesn't return entries in their insertion order. Try LinkedHashMap instead.

From the documentation:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)