ExcelParser.java (2741B)
1 package population; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.util.List; 6 import java.util.ArrayList; 7 import java.util.HashMap; 8 import java.util.Iterator; 9 import org.apache.poi.ss.usermodel.*; 10 import org.apache.poi.xssf.usermodel.*; 11 12 public class ExcelParser { 13 private final String EST_SHEET = "ESTIMATES"; 14 private final String TARGET_TYPE = "Country/Area"; 15 private final int TARGET_TYPE_CELL = 5; 16 private final int COUNTRIES_ROW = 43; 17 private List<Country> countries; 18 19 ExcelParser(String path) throws Exception { 20 XSSFWorkbook wbook; 21 XSSFSheet sheet; 22 XSSFRow row; 23 FileInputStream fis; 24 Iterator<Row> rit; 25 String cv = ""; 26 int rownum; 27 28 countries = new ArrayList<Country>(); 29 fis = new FileInputStream(new File(path)); 30 wbook = new XSSFWorkbook(fis); 31 sheet = wbook.getSheet(EST_SHEET); 32 rit = sheet.iterator(); 33 34 while (rit.hasNext()) { 35 row = (XSSFRow)rit.next(); 36 rownum = row.getRowNum(); 37 cv = row.getCell(TARGET_TYPE_CELL).getStringCellValue(); 38 if (rownum >= COUNTRIES_ROW && cv.equals(TARGET_TYPE)) 39 countries.add(read_country(row)); 40 } 41 wbook.close(); 42 fis.close(); 43 } 44 45 private Country read_country(XSSFRow row) throws Exception { 46 final int MIN_CELLNUM = 7; 47 Iterator<Cell> cit; 48 Cell cell; 49 Integer year = Country.STARTING_YEAR; 50 String[] fields = new String[MIN_CELLNUM]; 51 HashMap<Integer, Integer> population = new HashMap<Integer, Integer>(); 52 Integer n; 53 int i = 0; 54 55 cit = row.cellIterator(); 56 if (row.getLastCellNum() < MIN_CELLNUM) { 57 throw new Exception("file must have at least " + 58 MIN_CELLNUM + " columns"); 59 } 60 while (cit.hasNext()) { 61 cell = cit.next(); 62 if (i < MIN_CELLNUM) { 63 switch (cell.getCellType()) { 64 case STRING: 65 fields[i++] = cell.getStringCellValue(); 66 break; 67 case NUMERIC: 68 n = dtoi(cell.getNumericCellValue()); 69 fields[i++] = Integer.toString(n); 70 break; 71 case BOOLEAN: 72 fields[i++] = String.valueOf( 73 cell.getBooleanCellValue()); 74 break; 75 case BLANK: 76 fields[i++] = "0"; 77 break; 78 case ERROR: /* FALLTHROUGH */ 79 case FORMULA: 80 case _NONE: 81 default: 82 fields[i++] = ""; 83 break; 84 } 85 } else if (cell.getCellType() == CellType.NUMERIC) 86 /* 87 * Population numbers need to be multiplied by 88 * 1000 in order to convert them properly to 89 * Integer. 90 */ 91 population.put(year++, 92 dtoi(cell.getNumericCellValue() * 1000)); 93 } 94 95 return new Country(fields[0], fields[1], fields[2], fields[3], 96 fields[4], fields[5], fields[6], population); 97 } 98 99 private Integer dtoi(double n) { 100 return Integer.valueOf(Double.valueOf(n).intValue()); 101 } 102 103 public List<Country> get_countries() { 104 return countries; 105 } 106 }