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.ArrayList;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.TreeMap;
24
25 import org.apache.poi.hssf.usermodel.HSSFCell;
26 import org.gageot.excel.beans.BeanSetter;
27 import org.gageot.excel.beans.BeanSetterImpl;
28 import org.springframework.beans.BeansException;
29 import org.springframework.beans.factory.BeanCreationException;
30
31 /***
32 * CallbackHandler implementation that creates a bean of the given class
33 * for each row, representing all columns as bean properties.
34 *
35 * @author David Gageot
36 * @see ExcelTemplate#read(String,CellCallbackHandler)
37 * @see BeanSetter
38 */
39 public class BeanCellCallbackHandler implements CellCallbackHandler {
40 private final Class clazz;
41 private final List beans;
42 private final BeanSetter beanSetter;
43 private Map keys;
44 private CellMapper cellMapper;
45
46 public BeanCellCallbackHandler (Class aClass) {
47 clazz = aClass;
48 beans = new ArrayList();
49 cellMapper = new ObjectCellMapper();
50 keys = new TreeMap();
51 beanSetter = new BeanSetterImpl();
52 }
53
54 public List getBeans() {
55 return beans;
56 }
57
58 public void processCell (HSSFCell cell, int rowNum, int columnNum) throws IOException, BeansException {
59 if (0 == rowNum) {
60 keys.put (new Integer (columnNum), ((String) cellMapper.mapCell (cell, rowNum, columnNum)));
61 } else {
62 Object bean;
63 if (beans.size() < rowNum) {
64 bean = createBean (clazz);
65 beans.add (bean);
66 } else {
67 bean = beans.get (rowNum - 1);
68 }
69
70 String propertyName = ((String) keys.get (new Integer (columnNum)));
71 Object cellValue = cellMapper.mapCell (cell, rowNum, columnNum);
72
73 beanSetter.setProperty (bean, propertyName, cellValue);
74 }
75 }
76
77 /***
78 * Create a bean for a given class.
79 * Default strategy is to create an empty bean calling its empty
80 * constructor. This method can be overridden for a different strategy.
81 * @param clazz the class of the bean to create
82 */
83 protected Object createBean (Class aClazz) throws BeansException {
84 try {
85 return aClazz.newInstance();
86 } catch (InstantiationException e) {
87 throw new BeanCreationException ("Impossible to create bean", e);
88 } catch (IllegalAccessException e) {
89 throw new BeanCreationException ("Impossible to create bean", e);
90 }
91 }
92 }