PoiUtils.java
14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package com.bsth.service.schedule.utils;
import com.bsth.entity.Energy;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* POI操作的until方法。
*/
public class PoiUtils {
private static ObjectMapper mapper = new ObjectMapper();
/**
* 使用poi读取cell中的值
* @param cell
* @return
*/
public static String getStringValueFromCell(Cell cell) {
SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
DecimalFormat decimalFormat = new DecimalFormat("#.#");
String cellValue = "";
if(cell == null) {
return cellValue;
}
else if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
cellValue = cell.getStringCellValue();
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
if(HSSFDateUtil.isCellDateFormatted(cell)) {
double d = cell.getNumericCellValue();
Date date = HSSFDateUtil.getJavaDate(d);
cellValue = sFormat.format(date);
}
else {
cellValue = decimalFormat.format((cell.getNumericCellValue()));
}
}
else if(cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cellValue = "";
}
else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cellValue = String.valueOf(cell.getBooleanCellValue());
}
else if(cell.getCellType() == Cell.CELL_TYPE_ERROR) {
cellValue = "";
}
else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
cellValue = cell.getCellFormula().toString();
}
return cellValue;
}
public static XSSFCell createStringXSSFCell(
XSSFWorkbook xssfWorkbook, XSSFRow xssfRow, short column, String value,
Color backgroundColor) {
XSSFCell xssfCell = createXSSFCell(
xssfWorkbook, xssfRow, column,
value, XSSFCell.CELL_TYPE_STRING,
HorizontalAlignment.CENTER, VerticalAlignment.CENTER,
BorderStyle.MEDIUM, new Color(0xdedede),
(short) 13, new Color(0x2765A7), "宋体",
backgroundColor, FillPatternType.SOLID_FOREGROUND
);
DataFormat dataFormat = xssfWorkbook.createDataFormat();
xssfCell.getCellStyle().setDataFormat(dataFormat.getFormat("@"));
return xssfCell;
}
public static XSSFCell createStringXSSFCell(
XSSFWorkbook xssfWorkbook, XSSFRow xssfRow, short column, String value) {
XSSFCell xssfCell = createXSSFCell(
xssfWorkbook, xssfRow, column,
value, XSSFCell.CELL_TYPE_STRING,
HorizontalAlignment.CENTER, VerticalAlignment.CENTER,
BorderStyle.MEDIUM, new Color(0xdedede),
(short) 13, new Color(0x2765A7), "宋体",
new Color(0xffffff), FillPatternType.SOLID_FOREGROUND
);
DataFormat dataFormat = xssfWorkbook.createDataFormat();
xssfCell.getCellStyle().setDataFormat(dataFormat.getFormat("@"));
return xssfCell;
}
public static XSSFCell createDoubleXSSFCell(
XSSFWorkbook xssfWorkbook, XSSFRow xssfRow, short column, Double value) {
XSSFCell xssfCell = createXSSFCell(
xssfWorkbook, xssfRow, column,
value, XSSFCell.CELL_TYPE_NUMERIC,
HorizontalAlignment.CENTER, VerticalAlignment.CENTER,
BorderStyle.MEDIUM, new Color(0xdedede),
(short) 13, new Color(0x2765A7), "宋体",
new Color(0xffffff), FillPatternType.SOLID_FOREGROUND
);
DataFormat dataFormat = xssfWorkbook.createDataFormat();
xssfCell.getCellStyle().setDataFormat(dataFormat.getFormat("0.00"));
return xssfCell;
}
public static XSSFCell createIntegerXSSFCell(
XSSFWorkbook xssfWorkbook, XSSFRow xssfRow, short column, Integer value) {
return createXSSFCell(
xssfWorkbook, xssfRow, column,
value, XSSFCell.CELL_TYPE_NUMERIC,
HorizontalAlignment.CENTER, VerticalAlignment.CENTER,
BorderStyle.MEDIUM, new Color(0xdedede),
(short) 13, new Color(0x2765A7), "宋体",
new Color(0xffffff), FillPatternType.SOLID_FOREGROUND
);
}
public static XSSFCell createBlankXSSFCell(
XSSFWorkbook xssfWorkbook, XSSFRow xssfRow, short column) {
return createXSSFCell(
xssfWorkbook, xssfRow, column,
null, XSSFCell.CELL_TYPE_BLANK,
HorizontalAlignment.CENTER, VerticalAlignment.CENTER,
BorderStyle.MEDIUM, new Color(0xdedede),
(short) 13, new Color(0x2765A7), "宋体",
new Color(0xffffff), FillPatternType.SOLID_FOREGROUND
);
}
public static XSSFCell setStringStyleXSSFCellStyle(XSSFWorkbook xssfWorkbook, XSSFCell xssfCell) {
DataFormat dataFormat = xssfWorkbook.createDataFormat();
xssfCell.getCellStyle().setDataFormat(dataFormat.getFormat("@"));
return xssfCell;
}
public static XSSFCell setIntegerStyleXSSFCellStyle(XSSFWorkbook xssfWorkbook, XSSFCell xssfCell) {
CreationHelper creationHelper = xssfWorkbook.getCreationHelper();
XSSFCellStyle xssfCellStyle = xssfCell.getCellStyle();
xssfCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("0"));
return xssfCell;
}
public static XSSFCell setDoubleStyleXSSFCellStyle(XSSFWorkbook xssfWorkbook, XSSFCell xssfCell) {
CreationHelper creationHelper = xssfWorkbook.getCreationHelper();
XSSFCellStyle xssfCellStyle = xssfCell.getCellStyle();
xssfCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("0.00"));
return xssfCell;
}
public static XSSFCell createXSSFCell(
XSSFWorkbook xssfWorkbook, XSSFRow xssfRow, short column,
Object value, int valueType,
HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment,
BorderStyle borderStyle, Color borderColor,
short fontSize, Color fontColor, String fontName,
Color backgroudColor, FillPatternType fillPatternType) {
CreationHelper creationHelper = xssfWorkbook.getCreationHelper();
// 1、创建单元格对象
XSSFCell cell = xssfRow.createCell(column);
// 2、设定样式
XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();
// 设定值
if (valueType == XSSFCell.CELL_TYPE_STRING) {
// cell.setCellValue(creationHelper.createRichTextString(
// WorkbookUtil.createSafeSheetName(String.valueOf(value))));
cell.setCellValue(creationHelper.createRichTextString(String.valueOf(value)));
} else if (valueType == XSSFCell.CELL_TYPE_NUMERIC) {
if (value instanceof Date) { // 日期
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-mm-dd"));
cell.setCellValue((Date) value);
} else if (value instanceof Double) {
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("0.00"));
cell.setCellValue((Double) value);
} else if (value instanceof Integer) {
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("0"));
cell.setCellValue(Double.valueOf(value.toString()));
} else {
throw new RuntimeException("只支持 Date Double Integer 单元格类型");
}
} else if (valueType == XSSFCell.CELL_TYPE_BLANK) {
cell.setCellType(Cell.CELL_TYPE_BLANK);
}
else {
throw new RuntimeException("暂时不支持字符串、日期、数字以为的类型");
}
// 对齐方式
cellStyle.setAlignment(horizontalAlignment);
cellStyle.setVerticalAlignment(verticalAlignment);
// 边框样式
cellStyle.setBorderTop(borderStyle);
cellStyle.setTopBorderColor(new XSSFColor(borderColor));
cellStyle.setBorderBottom(borderStyle);
cellStyle.setBottomBorderColor(new XSSFColor(borderColor));
cellStyle.setBorderLeft(borderStyle);
cellStyle.setLeftBorderColor(new XSSFColor(borderColor));
cellStyle.setBorderRight(borderStyle);
cellStyle.setRightBorderColor(new XSSFColor(borderColor));
// 字体颜色
XSSFFont font = xssfWorkbook.createFont();
font.setColor(new XSSFColor(fontColor));
font.setFontHeightInPoints(fontSize);
font.setFontName(fontName);
cellStyle.setFont(font);
// 单元背景色
cellStyle.setFillForegroundColor(new XSSFColor(backgroudColor));
cellStyle.setFillPattern(fillPatternType);
// TODO
cell.setCellStyle(cellStyle);
return cell;
}
/**
* 导入数据
* @param file 文件
* @param skipRows 跳过行数
* @param columns 对应的字段列信息
* @param cls 对象类型class
* @param <T> 对象类型
* @return
*/
public static <T> List<T> importFromExcel(File file, int skipRows, String[] columns, Class<T> cls) {
List<T> list = new ArrayList<>();
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
HSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getLastRowNum() + 1;
List<Map<String, Object>> data = new ArrayList<>();
for (int i = skipRows;i < rows;i++) {
HSSFRow row = sheet.getRow(i);
Map<String, Object> map = new HashMap<>();
int cols = row.getLastCellNum();
if (columns.length != cols) {
throw new IllegalArgumentException("异常的数据列数");
}
for (int j = 0;j < cols;j++) {
String column = columns[j];
if (column != null) {
map.put(columns[j], getCellValue(evaluator, row.getCell(j)));
}
}
data.add(map);
}
list = mapper.convertValue(data, mapper.getTypeFactory().constructParametrizedType(ArrayList.class, List.class, cls));
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
private static Object getCellValue(FormulaEvaluator evaluator, HSSFCell cell) {
Object value = null;
if (cell != null) {
CellValue cellValue = evaluator.evaluate(cell);
if(cellValue!=null){
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
value = cellValue.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
value = cell.getDateCellValue();
}
break;
case Cell.CELL_TYPE_STRING:
value = cellValue.getStringValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cellValue.getBooleanValue();
break;
case Cell.CELL_TYPE_BLANK:
case Cell.CELL_TYPE_ERROR:
value = "";
break;
default:
break;
}
}
}
return value;
}
public static void main(String[] args) {
/*for (Field field : Energy.class.getDeclaredFields()) {
System.out.print(String.format("\"%s\",",field.getName()));
}*/
String[] columns = new String[]{null,"energyStation",null,null,"unit","customer",null,"plate",null,"startDate","terminalDate","chargingMinutes","energy1","energy2","energy3","energy4","originEnergy","energyCost","serviceCost","totalCost"};
List<Energy> energies = importFromExcel(new File("C:\\Users\\Hill\\Downloads\\充电数据.xls"), 2, columns, Energy.class);
System.out.println(energies);
}
/**
* 导入数据
* @param file 文件
* @param skipRows 跳过行数
* @param columns 对应的字段列信息
* @param cls 对象类型class
* @param <T> 对象类型
* @return
*/
public static <T> List<T> importFromExcel2(File file, int skipRows, String[] columns, Class<T> cls) {
List<T> list = new ArrayList<>();
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
HSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getLastRowNum() + 1;
List<Map<String, Object>> data = new ArrayList<>();
for (int i = skipRows;i < rows;i++) {
HSSFRow row = sheet.getRow(i);
Map<String, Object> map = new HashMap<>();
int cols = columns.length;
for (int j = 0;j < cols;j++) {
String column = columns[j];
if (column != null) {
map.put(columns[j], getCellValue(evaluator, row.getCell(j)));
}
}
data.add(map);
}
list = mapper.convertValue(data, mapper.getTypeFactory().constructParametrizedType(ArrayList.class, List.class, cls));
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}