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.text.SimpleDateFormat;
21
22 import org.apache.poi.hssf.usermodel.HSSFCell;
23
24 /***
25 * CellMapper implementation that creates a <code>java.lang.String</code>
26 * for each cell.
27 *
28 * @author David Gageot
29 */
30 public class StringCellMapper implements CellMapper {
31 private static final int TEXT_CELL_FORMAT = 49;
32 private static final int OPENOFFICE_TEXT_CELL_FORMAT = 165;
33 private static final int OPENOFFICE_DATE_CELL_FORMAT = 167;
34
35 private SimpleDateFormat dateFormat ;
36
37 public Object mapCell (HSSFCell cell, int rowNum, int columnNum) throws IOException {
38 if (null == cell) {
39 return "";
40 }
41
42 switch (cell.getCellType()) {
43 case HSSFCell.CELL_TYPE_BLANK :
44 return "";
45 case HSSFCell.CELL_TYPE_ERROR :
46 return "Error<" + cell.getErrorCellValue() + ">";
47 case HSSFCell.CELL_TYPE_BOOLEAN :
48 return booleanToString (cell);
49 case HSSFCell.CELL_TYPE_NUMERIC :
50 return numericToString (cell);
51 case HSSFCell.CELL_TYPE_FORMULA :
52 return formulaToString (cell);
53 case HSSFCell.CELL_TYPE_STRING :
54 default :
55 return richTextToString (cell);
56 }
57 }
58
59 private String booleanToString (HSSFCell cell) {
60 return cell.getBooleanCellValue() ? "VRAI" : "FAUX";
61 }
62
63 private String richTextToString (HSSFCell cell) {
64 return cell.getRichStringCellValue().getString();
65 }
66
67 private String numericToString (HSSFCell cell) {
68 double numericValue = cell.getNumericCellValue();
69
70 if (Double.isNaN (numericValue)) {
71 return "";
72 }
73
74 if (isDateFormat (cell)) {
75 if (null == dateFormat) {
76 dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
77 }
78
79 return dateFormat.format (cell.getDateCellValue());
80 }
81
82
83
84
85
86 if (isTextFormat (cell) && (((int) numericValue) == numericValue)) {
87 return Integer.toString ((int) numericValue);
88 } else {
89 return Double.toString (numericValue);
90 }
91 }
92
93 private String formulaToString (HSSFCell cell) {
94 if (isTextFormat (cell)) {
95 return richTextToString (cell);
96 } else {
97 return numericToString (cell);
98 }
99 }
100
101 private static boolean isTextFormat (HSSFCell cell) {
102 short cellFormat = cell.getCellStyle().getDataFormat();
103
104 return ((TEXT_CELL_FORMAT == cellFormat) || (OPENOFFICE_TEXT_CELL_FORMAT == cellFormat));
105 }
106
107 private static boolean isDateFormat (HSSFCell cell) {
108 short cellFormat = cell.getCellStyle().getDataFormat();
109
110 return (OPENOFFICE_DATE_CELL_FORMAT == cellFormat);
111 }
112 }