1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.gageot.excel.core;
18
19 import java.io.IOException;
20 import java.util.Map;
21
22 import org.apache.poi.hssf.usermodel.HSSFRow;
23 import org.springframework.core.CollectionFactory;
24
25 /***
26 * RowMapper implementation that creates a <code>java.util.Map</code>
27 * for each row, representing all columns as key-value pairs: one
28 * entry for each column, with the column name as key.
29 *
30 * <p>The Map implementation to use can be customized through overriding
31 * <code>createColumnMap</code>.
32 *
33 * <p>The CellMapper implementation to use can be customized through overriding
34 * <code>createCellMapper</code>.
35 *
36 * @author David Gageot
37 * @see ExcelTemplate#readList(String)
38 */
39 public class ColumnMapRowMapper implements RowMapper {
40 private String[] keys;
41
42 public ColumnMapRowMapper (String[] aKeys) {
43 this.keys = aKeys;
44 }
45
46 public Object mapRow (HSSFRow row, int rowNum) throws IOException {
47 Map map = createColumnMap (row.getLastCellNum());
48
49 CellMapper cellMapper = createCellMapper (rowNum);
50
51 short lastColumnNum = row.getLastCellNum();
52 for (short columnNum = 0; columnNum < lastColumnNum; columnNum++) {
53 if (columnNum < keys.length) {
54 map.put (keys[columnNum], cellMapper.mapCell (
55 row.getCell (columnNum), rowNum, columnNum));
56 }
57 }
58
59 return map;
60 }
61
62 /***
63 * Create a Map instance to be used as column map.
64 * <p>By default, a linked case-insensitive Map will be created if possible,
65 * else a plain HashMap (see Spring's CollectionFactory).
66 * @param columnCount the column count, to be used as initial
67 * capacity for the Map
68 * @return the new Map instance
69 * @see org.springframework.core.CollectionFactory#createLinkedCaseInsensitiveMapIfPossible
70 */
71 protected Map createColumnMap (int columnCount) {
72 return CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(columnCount);
73 }
74
75 /***
76 * Create a CellMapper instance to be used to map cells content.
77 * <p>By default, a <code>java.lang.String</code> for each cell.
78 * @param rowNum the number of the current row
79 * @return the new CellMapper instance
80 * @see StringCellMapper
81 */
82 protected CellMapper createCellMapper (int rowNum) {
83 return new StringCellMapper();
84 }
85 }