excel导入导出使用poi自定义注解
最近在做一个数据导入导出的模块 在网上找了一些例子 在这里整理一下 这里就不再贴原作者的地址
(以下代码来自网上非原创 稍作简单修改)
首先引入pom.xml依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency>
使用自定义注解
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target( { java.lang.annotation.ElementType.FIELD }) public @interface ExcelVOAttribute { /** * 导出到Excel中的名字. */ public abstract String name(); /** * 配置列的名称,对应A,B,C,D.... */ public abstract String column(); /** * 提示信息 */ public abstract String prompt() default ""; /** * 设置只能选择不能输入的列内容. */ public abstract String[] combo() default {}; /** * 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写. */ public abstract boolean isExport() default true; }
- 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
- 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
Excel 工具类
import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.poi.hssf.usermodel.DVConstraint;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFDataValidation;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.ss.util.CellRangeAddressList;import com.sj.stages.common.excel.annotation.ExcelVOAttribute; public class ExcelUtil<T> { Class<T> clazz; public ExcelUtil(Class<T> clazz) { this.clazz = clazz; } public List<T> importExcel(String sheetName, InputStream input) { int maxCol = 0; List<T> list = new ArrayList<T>(); try { HSSFWorkbook workbook = new HSSFWorkbook(input); HSSFSheet sheet = workbook.getSheet(sheetName); if (!sheetName.trim().equals("")) { sheet = workbook.getSheet(sheetName); } if (sheet == null) { sheet = workbook.getSheetAt(0); } int rows = sheet.getPhysicalNumberOfRows(); if (rows > 0) { List<Field> allFields = getMappedFiled(clazz, null); Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>(); for (Field field : allFields) { if (field.isAnnotationPresent(ExcelVOAttribute.class)) { ExcelVOAttribute attr = field .getAnnotation(ExcelVOAttribute.class); int col = getExcelCol(attr.column()); maxCol = Math.max(col, maxCol); field.setAccessible(true); fieldsMap.put(col, field); } } for (int i = 1; i < rows; i++) { HSSFRow row = sheet.getRow(i); int cellNum = maxCol; T entity = null; for (int j = 0; j < cellNum; j++) { HSSFCell cell = row.getCell(j); if (cell == null) { continue; } int cellType = cell.getCellType(); String c = ""; if (cellType == HSSFCell.CELL_TYPE_NUMERIC) { c = String.valueOf(cell.getNumericCellValue()); } else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) { c = String.valueOf(cell.getBooleanCellValue()); } else { c = cell.getStringCellValue(); } if (c == null || c.equals("")) { continue; } entity = (entity == null ? clazz.newInstance() : entity); Field field = fieldsMap.get(j); if (field==null) { continue; } Class<?> fieldType = field.getType(); if (String.class == fieldType) { field.set(entity, String.valueOf(c)); } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) { field.set(entity, Integer.parseInt(c)); } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) { field.set(entity, Long.valueOf(c)); } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) { field.set(entity, Float.valueOf(c)); } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) { field.set(entity, Short.valueOf(c)); } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) { field.set(entity, Double.valueOf(c)); } else if (Character.TYPE == fieldType) { if ((c != null) && (c.length() > 0)) { field.set(entity, Character .valueOf(c.charAt(0))); } } } if (entity != null) { list.add(entity); } } } } catch (IOException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } return list; } /** * 对list数据源将其里面的数据导入到excel表单 * * @param sheetName * 工作表的名称 * @param output * java输出流 */ public boolean exportExcel(List<T> lists[], String sheetNames[], OutputStream output) { if (lists.length != sheetNames.length) { System.out.println("数组长度不一致"); return false; } HSSFWorkbook workbook = new HSSFWorkbook(); for (int ii = 0; ii < lists.length; ii++) { List<T> list = lists[ii]; String sheetName = sheetNames[ii]; List<Field> fields = getMappedFiled(clazz, null); HSSFSheet sheet = workbook.createSheet(); workbook.setSheetName(ii, sheetName); HSSFRow row; HSSFCell cell; HSSFCellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); style.setFillBackgroundColor(HSSFColor.GREY_40_PERCENT.index); row = sheet.createRow(0); for (int i = 0; i < fields.size(); i++) { Field field = fields.get(i); ExcelVOAttribute attr = field .getAnnotation(ExcelVOAttribute.class); int col = getExcelCol(attr.column()); cell = row.createCell(col); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(attr.name()); if (!attr.prompt().trim().equals("")) { setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, col, col); } if (attr.combo().length > 0) { setHSSFValidation(sheet, attr.combo(), 1, 100, col, col); } cell.setCellStyle(style); } int startNo = 0; int endNo = list.size(); for (int i = startNo; i < endNo; i++) { row = sheet.createRow(i + 1 - startNo); T vo = (T) list.get(i); for (int j = 0; j < fields.size(); j++) { Field field = fields.get(j); field.setAccessible(true); ExcelVOAttribute attr = field .getAnnotation(ExcelVOAttribute.class); try { if (attr.isExport()) { cell = row.createCell(getExcelCol(attr.column())); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo))); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } try { output.flush(); workbook.write(output); output.close(); return true; } catch (IOException e) { e.printStackTrace(); System.out.println("Output is closed "); return false; } } /** * 对list数据源将其里面的数据导入到excel表单 * * @param sheetName * 工作表的名称 * @param sheetSize * 每个sheet中数据的行数,此数值必须小于65536 * @param output * java输出流 */ @SuppressWarnings("unchecked") public boolean exportExcel(List<T> list, String sheetName, OutputStream output) { List<T> ilist = new ArrayList<>(); for (T t : list) { ilist.add(t); } List<T>[] lists = new ArrayList[1]; lists[0] = ilist; String[] sheetNames = new String[1]; sheetNames[0] = sheetName; return exportExcel(lists, sheetNames, output); } /** * 将EXCEL中A,B,C,D,E列映射成0,1,2,3 * * @param col */ public static int getExcelCol(String col) { col = col.toUpperCase(); int count = -1; char[] cs = col.toCharArray(); for (int i = 0; i < cs.length; i++) { count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i); } return count; } /** * 设置单元格上提示 * * @param sheet * 要设置的sheet. * @param promptTitle * 标题 * @param promptContent * 内容 * @param firstRow * 开始行 * @param endRow * 结束行 * @param firstCol * 开始列 * @param endCol * 结束列 * @return 设置好的sheet. */ public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) { DVConstraint constraint = DVConstraint .createCustomFormulaConstraint("DD1"); CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); HSSFDataValidation data_validation_view = new HSSFDataValidation( regions, constraint); data_validation_view.createPromptBox(promptTitle, promptContent); sheet.addValidationData(data_validation_view); return sheet; } /** * 设置某些列的值只能输入预制的数据,显示下拉框. * * @param sheet * 要设置的sheet. * @param textlist * 下拉框显示的内容 * @param firstRow * 开始行 * @param endRow * 结束行 * @param firstCol * 开始列 * @param endCol * 结束列 * @return 设置好的sheet. */ public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) { DVConstraint constraint = DVConstraint .createExplicitListConstraint(textlist); CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); HSSFDataValidation data_validation_list = new HSSFDataValidation( regions, constraint); sheet.addValidationData(data_validation_list); return sheet; } /** * 得到实体类所有通过注解映射了数据表的字段 * * @param map * @return */ @SuppressWarnings("rawtypes") private List<Field> getMappedFiled(Class clazz, List<Field> fields) { if (fields == null) { fields = new ArrayList<Field>(); } Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(ExcelVOAttribute.class)) { fields.add(field); } } if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) { getMappedFiled(clazz.getSuperclass(), fields); } return fields; } }
- 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
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 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
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
完成以上步骤一个简单的excel导入导出工具就可以开箱即用了
这里我们以一个学生为例
import com.sj.stages.common.excel.annotation.ExcelVOAttribute;public class StudentVO { @ExcelVOAttribute(name = "序号", column = "A") private int id; @ExcelVOAttribute(name = "姓名", column = "B", isExport = true) private String name; @ExcelVOAttribute(name = "年龄", column = "C", prompt = "年龄保密哦!", isExport = false) private int age; @ExcelVOAttribute(name = "班级", column = "D", combo = { "五期提高班", "六期提高班", "七期提高班" }) private String clazz; @ExcelVOAttribute(name = "公司", column = "F") private String company; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
一个简单的测试 作为结束
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.util.ArrayList;import java.util.List;import org.apache.log4j.Logger;import org.junit.Test;public class ExcelUtilTest { private Logger logger = Logger.getLogger(ExcelUtilTest.class); @Test public void exportExcel(){ List<StudentVO> list = new ArrayList<StudentVO>(); StudentVO vo = new StudentVO(); vo.setId(1); vo.setName("李坤"); vo.setAge(26); vo.setClazz("五期提高班"); vo.setCompany("天融信"); list.add(vo); StudentVO vo2 = new StudentVO(); vo2.setId(2); vo2.setName("曹贵生"); vo2.setClazz("五期提高班"); vo2.setCompany("中银"); list.add(vo2); StudentVO vo3 = new StudentVO(); vo3.setId(3); vo3.setName("柳波"); vo3.setClazz("五期提高班"); list.add(vo3); FileOutputStream out = null; try { out = new FileOutputStream("d:\\success3.xls"); } catch (FileNotFoundException e) { e.printStackTrace(); } ExcelUtil<StudentVO> util = new ExcelUtil<StudentVO>(StudentVO.class); util.exportExcel(list, "学生信息", out); logger.info("----执行完毕----------"); } @Test public void importExcel(){ FileInputStream fis = null; try { fis = new FileInputStream("d:\\success3.xls"); ExcelUtil<StudentVO> util = new ExcelUtil<StudentVO>( StudentVO.class); List<StudentVO> list = util.importExcel("学生信息0", fis); logger.info(list); } catch (FileNotFoundException e) { e.printStackTrace(); } }}