Advertisement
tr00per92

TreeMap + ExtractDataFromXLSX

May 15th, 2014
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. import java.io.FileInputStream;
  2. import java.util.Locale;
  3. import java.util.TreeMap;
  4.  
  5. import org.apache.poi.xssf.usermodel.XSSFCell;
  6. import org.apache.poi.xssf.usermodel.XSSFRow;
  7. import org.apache.poi.xssf.usermodel.XSSFSheet;
  8. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  9.  
  10. public class ExtractDataFromXLSX {
  11.  
  12.     public static void main(String[] args) {
  13.         Locale.setDefault(Locale.ROOT);
  14.         try (FileInputStream input = new FileInputStream("Incomes-Report.xlsx")) {
  15.             XSSFWorkbook wb = new XSSFWorkbook(input);
  16.             XSSFSheet sheet = wb.getSheet("Incomes");
  17.             TreeMap<String, Double> allOffices = new TreeMap<String, Double>();
  18.             double totalIncome = 0;
  19.            
  20.             XSSFRow currentRow = sheet.getRow(1);
  21.             while (currentRow != null) {
  22.                 XSSFCell officeCell = currentRow.getCell(0);
  23.                 String currentOffice = officeCell.getStringCellValue();
  24.                 XSSFCell incomeCell = currentRow.getCell(5);
  25.                 double currentIncome = incomeCell.getNumericCellValue();           
  26.                 totalIncome += currentIncome;
  27.                 if (allOffices.containsKey(currentOffice)) {
  28.                     currentIncome += allOffices.get(currentOffice);
  29.                 }
  30.                 allOffices.put(currentOffice, currentIncome);
  31.                 currentRow = sheet.getRow(1 + currentRow.getRowNum());
  32.             }
  33.             for (String office: allOffices.keySet()) {         
  34.                 double income = allOffices.get(office);  
  35.                 System.out.printf("%s -> %.2f", office, income);  
  36.                 System.out.println();
  37.             }
  38.             System.out.println("Grand Total -> " + totalIncome);
  39.            
  40.         } catch (Exception e) {
  41.             e.printStackTrace();
  42.         }
  43.     }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement