From 74bae8de71ee177f33e8f36c50c400156947cba2 Mon Sep 17 00:00:00 2001 From: wangbing Date: Mon, 11 Nov 2019 18:00:49 +0800 Subject: [PATCH] 0000 --- .../wb/excel/api/{Excel.java => WExcel.java} | 92 +-- ...escription.java => ColumnDescription.java} | 2 +- .../{HeaderName.java => ColumnName.java} | 2 +- .../annotation/{Type.java => ColumnType.java} | 2 +- .../excel/api/annotation/ExcelCollection.java | 2 +- .../wb/excel/api/annotation/ExcelVerify.java | 2 +- .../com/wb/excel/api/annotation/Ignore.java | 16 + .../wb/excel/api/annotation/ParentFirst.java | 2 +- .../wb/excel/api/annotation/SheetName.java | 17 + .../com/wb/excel/api/datatable/DataExcel.java | 60 -- .../wb/excel/api/datatable/ExcelImport.java | 601 ------------------ .../wb/excel/api/datatable/ImportParams.java | 62 -- .../api/datatable/{Cell.java => WCell.java} | 6 +- .../datatable/{Column.java => WColumn.java} | 17 +- .../api/datatable/{DataRow.java => WRow.java} | 2 +- .../datatable/{DataTable.java => WSheet.java} | 422 ++++++------ .../wb/excel/api/entity/DataVerifyResult.java | 2 +- .../api/entity/ExcelCollectionEntity.java | 4 +- .../com/wb/excel/api/entity/ExcelEntity.java | 2 +- .../excel/api/entity/ExcelImportEntity.java | 2 +- .../excel/api/entity/ExcelImportResult.java | 2 +- .../excel/api/entity/ExcelVerifyEntity.java | 2 +- .../wb/excel/api/enumeration/DataType.java | 80 +-- .../com/wb/excel/api/util/BaseVerifyUtil.java | 2 +- .../java/com/wb/excel/api/util/ClassUtil.java | 7 + .../com/wb/excel/api/util/StringUtils.java | 2 +- .../com/wb/excel/api/util/VerifyDataUtil.java | 2 +- src/test/java/ExampleTest.java | 28 +- src/test/java/User.java | 59 +- 29 files changed, 369 insertions(+), 1132 deletions(-) rename src/main/java/com/wb/excel/api/{Excel.java => WExcel.java} (77%) rename src/main/java/com/wb/excel/api/annotation/{HeaderDescription.java => ColumnDescription.java} (86%) rename src/main/java/com/wb/excel/api/annotation/{HeaderName.java => ColumnName.java} (94%) rename src/main/java/com/wb/excel/api/annotation/{Type.java => ColumnType.java} (91%) create mode 100644 src/main/java/com/wb/excel/api/annotation/Ignore.java create mode 100644 src/main/java/com/wb/excel/api/annotation/SheetName.java delete mode 100644 src/main/java/com/wb/excel/api/datatable/DataExcel.java delete mode 100644 src/main/java/com/wb/excel/api/datatable/ExcelImport.java delete mode 100644 src/main/java/com/wb/excel/api/datatable/ImportParams.java rename src/main/java/com/wb/excel/api/datatable/{Cell.java => WCell.java} (90%) rename src/main/java/com/wb/excel/api/datatable/{Column.java => WColumn.java} (88%) rename src/main/java/com/wb/excel/api/datatable/{DataRow.java => WRow.java} (70%) rename src/main/java/com/wb/excel/api/datatable/{DataTable.java => WSheet.java} (71%) diff --git a/src/main/java/com/wb/excel/api/Excel.java b/src/main/java/com/wb/excel/api/WExcel.java similarity index 77% rename from src/main/java/com/wb/excel/api/Excel.java rename to src/main/java/com/wb/excel/api/WExcel.java index 8976295..e86c56a 100644 --- a/src/main/java/com/wb/excel/api/Excel.java +++ b/src/main/java/com/wb/excel/api/WExcel.java @@ -1,9 +1,9 @@ package com.wb.excel.api; -import com.wb.excel.api.annotation.HeaderDescription; -import com.wb.excel.api.datatable.Cell; -import com.wb.excel.api.datatable.Column; -import com.wb.excel.api.datatable.DataTable; +import com.wb.excel.api.annotation.ColumnDescription; +import com.wb.excel.api.datatable.WCell; +import com.wb.excel.api.datatable.WColumn; +import com.wb.excel.api.datatable.WSheet; import com.wb.excel.api.enumeration.DataType; import com.wb.excel.api.enumeration.Status; import com.wb.excel.api.style.*; @@ -27,7 +27,7 @@ import java.util.Set; * @author * @since 0.1.0 */ -public class Excel { +public class WExcel { /** * Excel表格 */ @@ -107,46 +107,35 @@ public class Excel { /** * 默认无参构造方法. */ - public Excel() { + public WExcel() { init(); } /** * 将一个DataTable转换为Excel对象,不显示检查结果和错误消息栏.
* 通常用于导出报表. - * {@link Excel#Excel(boolean flag, DataTable... dataTable)} + * {@link WExcel#WExcel(boolean flag, WSheet... dataTable)} * * @param tables 要导出的DataTable集合 */ - public Excel(DataTable... tables) { + public WExcel(WSheet... tables) { workbook = this.initExcel(false, tables); } - /** - * 将一个DataTable转换为Excel对象. - * - * @param table DataTable - * @param flag 是否需要添加检查结果和错误消息栏(true,会添加;false,不会添加) - */ - @Deprecated - public Excel(DataTable table, boolean flag) { - workbook = this.initExcel(flag, table); - } - /** * 将若干DataTable转换为Excel对象. * * @param flag 是否需要添加检查结果和错误消息栏(true,会添加;false,不会添加) * @param tables DataTable列表 */ - public Excel(boolean flag, DataTable... tables) { + public WExcel(boolean flag, WSheet... tables) { workbook = this.initExcel(flag, tables); } - public XSSFWorkbook initExcel(boolean flag, DataTable... tables) { + public XSSFWorkbook initExcel(boolean flag, WSheet... tables) { init(); Set nameSet = new HashSet<>(tables.length); - for (DataTable table : tables) { + for (WSheet table : tables) { String name = table.getName(); int index = 1; while (nameSet.contains(name)) { @@ -165,7 +154,7 @@ public class Excel { if (flag) { // 检查结果栏 org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(0); - String columnName = DataTable.CHECK_STATUS_NAME; + String columnName = WSheet.CHECK_STATUS_NAME; firstCell.setCellStyle(headCellStyle); firstCell.setCellValue(new XSSFRichTextString(columnName)); sheet.setColumnWidth(0, (4 + 8) * 256); @@ -173,8 +162,8 @@ public class Excel { // 数据栏 int hiddenNumber = 0; for (int j = 0; j < table.getColumnIndex(); j++) { - Column column = table.getColumns()[j]; - if (column.isHidden()) { + WColumn WColumn = table.getWColumns()[j]; + if (WColumn.isHidden()) { hiddenNumber++; continue; } @@ -183,9 +172,9 @@ public class Excel { k++; } org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(k); - String columnName = column.getName(); + String columnName = WColumn.getName(); XSSFRichTextString textString; - if (column.isRequired()) { + if (WColumn.isRequired()) { textString = new XSSFRichTextString("*" + columnName); textString.applyFont(0, 1, redFont); textString.applyFont(1, textString.length(), normalFont); @@ -194,18 +183,18 @@ public class Excel { textString.applyFont(normalFont); } StringBuilder sb = new StringBuilder(); - sb.append(column.getDescription()).append("\n"); - if (column.getDataType() != DataType.STRING) { + sb.append(WColumn.getDescription()).append("\n"); + if (WColumn.getDataType() != DataType.STRING) { // 如果数据类型不是字符串类型,添加特殊数据类型的说明信息。 Field[] fields = DataType.class.getDeclaredFields(); for (Field field : fields) { - if (field.getName().equals(column.getDataType().name())) { - if (field.isAnnotationPresent(HeaderDescription.class)) { + if (field.getName().equals(WColumn.getDataType().name())) { + if (field.isAnnotationPresent(ColumnDescription.class)) { // 获取声明字段上的Description信息。 - HeaderDescription headerDescription = field.getAnnotation(HeaderDescription.class); - if (headerDescription.value() != null) { - sb.append(headerDescription.value()); + ColumnDescription columnDescription = field.getAnnotation(ColumnDescription.class); + if (columnDescription.value() != null) { + sb.append(columnDescription.value()); } } } @@ -221,13 +210,13 @@ public class Excel { } firstCell.setCellValue(textString); firstCell.setCellStyle(headCellStyle); - sheet.setColumnWidth(k, (4 + column.getCellWidth()) * 256); + sheet.setColumnWidth(k, (4 + WColumn.getCellWidth()) * 256); } // 错误消息栏 if (flag) { org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(table.getColumnIndex() + 1 - hiddenNumber); - String columnName = DataTable.CHECK_STATUS_RESULT; + String columnName = WSheet.CHECK_STATUS_RESULT; firstCell.setCellStyle(headCellStyle); firstCell.setCellValue(new XSSFRichTextString(columnName)); sheet.setColumnWidth(table.getColumnIndex() + 1, (4 + 10) * 256); @@ -257,8 +246,8 @@ public class Excel { int j = 0; hiddenNumber = 0; for (; j < table.getColumnIndex(); j++) { - Column column = table.getColumns()[j]; - if (column.isHidden()) { + WColumn WColumn = table.getWColumns()[j]; + if (WColumn.isHidden()) { hiddenNumber++; continue; } @@ -268,24 +257,23 @@ public class Excel { } org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(k); - Cell cell = table.getCell(i, j); - if (null == cell) { + WCell WCell = table.getCell(i, j); + if (null == WCell) { continue; } - String value = cell.getValue(); + String value = WCell.getValue(); xssfCell.setCellValue(value); // 如果该列是数字类型,则靠右 - if (table.getColumns()[j].getDataType() == DataType.DECIMAL - || table.getColumns()[j].getDataType() == DataType.NUMBER - || table.getColumns()[j].getDataType() == DataType.LONG) { - if (flag && !cell.getStatus().equals(Status.PASS)) { + if (table.getWColumns()[j].getDataType() == DataType.DECIMAL + || table.getWColumns()[j].getDataType() == DataType.NUMBER) { + if (flag && !WCell.getStatus().equals(Status.PASS)) { xssfCell.setCellStyle(errorNumberCellStyle); } else { xssfCell.setCellStyle(normalNumberCellStyle); } } else { - if (flag && !cell.getStatus().equals(Status.PASS)) { + if (flag && !WCell.getStatus().equals(Status.PASS)) { xssfCell.setCellStyle(errorCellStyle); } else { xssfCell.setCellStyle(normalCellStyle); @@ -303,18 +291,6 @@ public class Excel { return workbook; } - /** - * 将一个DataTable转换为Excel对象 - * - * @param table DataTable - * @param flag 是否需要添加检查结果和错误消息栏 - * @return Excel的Workbook对象 - */ - @Deprecated - public XSSFWorkbook initExcel(DataTable table, boolean flag) { - return initExcel(flag, table); - } - /** * 得到已生成好的Excel文件的字节流信息 * diff --git a/src/main/java/com/wb/excel/api/annotation/HeaderDescription.java b/src/main/java/com/wb/excel/api/annotation/ColumnDescription.java similarity index 86% rename from src/main/java/com/wb/excel/api/annotation/HeaderDescription.java rename to src/main/java/com/wb/excel/api/annotation/ColumnDescription.java index b6dc28b..63dab9d 100644 --- a/src/main/java/com/wb/excel/api/annotation/HeaderDescription.java +++ b/src/main/java/com/wb/excel/api/annotation/ColumnDescription.java @@ -11,7 +11,7 @@ import java.lang.annotation.*; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface HeaderDescription { +public @interface ColumnDescription { String value() default ""; } diff --git a/src/main/java/com/wb/excel/api/annotation/HeaderName.java b/src/main/java/com/wb/excel/api/annotation/ColumnName.java similarity index 94% rename from src/main/java/com/wb/excel/api/annotation/HeaderName.java rename to src/main/java/com/wb/excel/api/annotation/ColumnName.java index a4b0c1a..abdc4fb 100644 --- a/src/main/java/com/wb/excel/api/annotation/HeaderName.java +++ b/src/main/java/com/wb/excel/api/annotation/ColumnName.java @@ -12,7 +12,7 @@ import java.lang.annotation.*; @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface HeaderName { +public @interface ColumnName { String value(); /** diff --git a/src/main/java/com/wb/excel/api/annotation/Type.java b/src/main/java/com/wb/excel/api/annotation/ColumnType.java similarity index 91% rename from src/main/java/com/wb/excel/api/annotation/Type.java rename to src/main/java/com/wb/excel/api/annotation/ColumnType.java index 43fa41d..5c41e79 100644 --- a/src/main/java/com/wb/excel/api/annotation/Type.java +++ b/src/main/java/com/wb/excel/api/annotation/ColumnType.java @@ -14,6 +14,6 @@ import java.lang.annotation.*; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface Type { +public @interface ColumnType { public DataType value() default DataType.STRING; } diff --git a/src/main/java/com/wb/excel/api/annotation/ExcelCollection.java b/src/main/java/com/wb/excel/api/annotation/ExcelCollection.java index 7ae4a05..4aa697b 100644 --- a/src/main/java/com/wb/excel/api/annotation/ExcelCollection.java +++ b/src/main/java/com/wb/excel/api/annotation/ExcelCollection.java @@ -11,7 +11,7 @@ import java.util.ArrayList; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription: 导入导出接合
+ *  ColumnDescription: 导入导出接合
  * ***************************************************************
  * 
*/ diff --git a/src/main/java/com/wb/excel/api/annotation/ExcelVerify.java b/src/main/java/com/wb/excel/api/annotation/ExcelVerify.java index f4a8468..c625916 100644 --- a/src/main/java/com/wb/excel/api/annotation/ExcelVerify.java +++ b/src/main/java/com/wb/excel/api/annotation/ExcelVerify.java @@ -21,7 +21,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Excel 导入校验 + * WExcel 导入校验 * * @author JueYue * @date 2014年6月23日 下午10:46:26 diff --git a/src/main/java/com/wb/excel/api/annotation/Ignore.java b/src/main/java/com/wb/excel/api/annotation/Ignore.java new file mode 100644 index 0000000..afac939 --- /dev/null +++ b/src/main/java/com/wb/excel/api/annotation/Ignore.java @@ -0,0 +1,16 @@ +package com.wb.excel.api.annotation; + +import java.lang.annotation.*; + +/** + * 是否忽略表字段 + * + * @author 金洋 + * @since 2.1.0 + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Ignore { + boolean value() default true; +} diff --git a/src/main/java/com/wb/excel/api/annotation/ParentFirst.java b/src/main/java/com/wb/excel/api/annotation/ParentFirst.java index a5347ee..8bcf2b8 100644 --- a/src/main/java/com/wb/excel/api/annotation/ParentFirst.java +++ b/src/main/java/com/wb/excel/api/annotation/ParentFirst.java @@ -3,7 +3,7 @@ package com.wb.excel.api.annotation; import java.lang.annotation.*; /** - * Created on 2015/5/28. + * 是否关注父类的字段 * * @author 金洋 * @since 2.1.0 diff --git a/src/main/java/com/wb/excel/api/annotation/SheetName.java b/src/main/java/com/wb/excel/api/annotation/SheetName.java new file mode 100644 index 0000000..c113196 --- /dev/null +++ b/src/main/java/com/wb/excel/api/annotation/SheetName.java @@ -0,0 +1,17 @@ +package com.wb.excel.api.annotation; + +import java.lang.annotation.*; + +/** + * 为字段、方法或类注解名称。
+ * Created on 2014/9/24. + * + * @author + * @version v1.0.0.0 + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface SheetName { + String value(); +} diff --git a/src/main/java/com/wb/excel/api/datatable/DataExcel.java b/src/main/java/com/wb/excel/api/datatable/DataExcel.java deleted file mode 100644 index 3295859..0000000 --- a/src/main/java/com/wb/excel/api/datatable/DataExcel.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.wb.excel.api.datatable; - - -import com.wb.excel.api.entity.ExcelImportResult; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * *************************************************************** - *

- *

- * Copyright (c) 2014 –
- *  HeaderDescription:
- * ***************************************************************
- * 
- */ -public class DataExcel { -// static Logger LOGGER = Logger.getLogger(DataExcel.class); - - /** - * @param file - * @param pojoClass - * @param - * @return - */ - public static ExcelImportResult importExcel(File file, Class pojoClass, ImportParams importParams) { - FileInputStream in = null; - try { - in = new FileInputStream(file); - return new ExcelImport().importExcelByIs(in, pojoClass, importParams); - } catch (Exception e) { -// LOGGER.error(e.getMessage(), e); - } finally { - try { - in.close(); - } catch (IOException e) { -// LOGGER.error(e.getMessage(), e); - } - } - return null; - } - - - /** - * Excel 导入 数据源IO流,不返回校验结果 导入 字段类型 Integer,Long,Double,Date,String,Boolean - * - * @param inputstream - * @param pojoClass - * @return - * @throws Exception - */ - public static ExcelImportResult importExcel(InputStream inputstream, Class pojoClass, ImportParams importParams) throws Exception { - return new ExcelImport().importExcelByIs(inputstream, pojoClass, importParams); - } - - -} diff --git a/src/main/java/com/wb/excel/api/datatable/ExcelImport.java b/src/main/java/com/wb/excel/api/datatable/ExcelImport.java deleted file mode 100644 index 42c10fa..0000000 --- a/src/main/java/com/wb/excel/api/datatable/ExcelImport.java +++ /dev/null @@ -1,601 +0,0 @@ -package com.wb.excel.api.datatable; - -import com.wb.excel.api.annotation.HeaderDescription; -import com.wb.excel.api.annotation.ExcelCollection; -import com.wb.excel.api.annotation.ExcelVerify; -import com.wb.excel.api.annotation.IsDuplicated; -import com.wb.excel.api.entity.*; -import com.wb.excel.api.style.ErrorCellStyle; -import com.wb.excel.api.util.ClassUtil; -import com.wb.excel.api.util.EnumUtil; -import com.wb.excel.api.util.StringUtils; -import com.wb.excel.api.util.VerifyDataUtil; -import org.apache.poi.POIXMLDocument; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.functions.T; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import com.wb.excel.api.annotation.HeaderName; -import com.wb.excel.api.annotation.Enum; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.sql.Time; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; - -/** - * *************************************************************** - *

- *

- * Copyright (c) 2014 –
- *  HeaderDescription:
- * ***************************************************************
- * 
- */ -public class ExcelImport { - /** - * 异常数据styler - */ - private CellStyle errorMessageStyle; - private boolean verfiyFail = false; - private VerifyDataUtil verifyDataUtil = new VerifyDataUtil(); - private Map verifyResultMap = new HashMap<>(); - private CellStyle errorcellStyle; - - /** - * 根据数据流解析Excel - * - * @param inputstream - * @param pojoClass - * @return - */ - public ExcelImportResult importExcelByIs(InputStream inputstream, Class pojoClass, ImportParams importParams) throws Exception { - List result = new ArrayList(); - Workbook book = null; - if (!(inputstream.markSupported())) { - inputstream = new PushbackInputStream(inputstream, 8); - } - if (POIFSFileSystem.hasPOIFSHeader(inputstream)) { - book = new HSSFWorkbook(inputstream); -// isXSSFWorkbook = false; - } else if (POIXMLDocument.hasOOXMLHeader(inputstream)) { - book = new XSSFWorkbook(OPCPackage.open(inputstream)); - } -// createErrorCellStyle(book); - errorcellStyle = new ErrorCellStyle(book).getStyle(); - for (int i = 0; i < importParams.getSheetNum(); i++) { - result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, importParams)); - } - return new ExcelImportResult(result, verfiyFail, book, verifyResultMap); - } - - /** - * @param result - * @param sheet - * @param pojoClass - * @param - * @return - */ - private Collection importExcel(List result, Sheet sheet, Class pojoClass, ImportParams importParams) throws Exception { - List collection = new ArrayList(); - //Excel Field 对象 - Map excelParams = new HashMap(); - //Excel Line 对象 - List excelCollection = new ArrayList(); - if (!Map.class.equals(pojoClass)) { - //获取所有的参数信息 - Field fields[] = ClassUtil.getClassFields(pojoClass); - getAllExcelField(fields, excelParams, excelCollection, pojoClass, null); - } - Iterator rows = sheet.rowIterator(); - Map titlemap = null; - Row row = null; - Object object = null; - if (rows.hasNext()) { - row = rows.next();// 排除标题信息 - titlemap = getTitleMap(row, excelParams, excelCollection); - } - while (rows.hasNext() && (row == null || sheet.getLastRowNum() - row.getRowNum() > 0)) { - row = rows.next();//获取某一行信息 - // 判断是集合元素还是不是集合元素,如果是就继续加入这个集合,不是就创建新的对象 - if (isLineRow(row, excelParams, titlemap) && object != null) { - for (ExcelCollectionEntity param : excelCollection) { - addListContinue(object, param, row, titlemap, importParams); - } - } else { - object = ClassUtil.createObject(pojoClass); - try { - for (int i = row.getFirstCellNum(), le = row.getLastCellNum(); i < le; i++) { - Cell cell = row.getCell(i) == null ? row.createCell(i) : row.getCell(i); - String titleString = (String) titlemap.get(i); - if (excelParams.containsKey(titleString) || Map.class.equals(pojoClass)) { - saveFieldValue(object, cell, excelParams, titleString, row, importParams); - } - } - for (ExcelCollectionEntity param : excelCollection) { - addListContinue(object, param, row, titlemap, importParams); - } - collection.add(object); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return collection; - } - - - /** - * 获取列数据,根据列属性 - * - * @param cell - * @return - */ - private Object getCellValue(Cell cell) { - Object result = null; - if (cell != null) { - if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { - result = cell.getNumericCellValue(); - } else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) { - result = cell.getBooleanCellValue(); - } else { - result = cell.getStringCellValue(); - } - } - result = result == null ? "" : result; - return result; - } - - /** - * 保存数据 - * - * @param object - * @param cell - * @param excelParams - * @param titleString - * @param row - */ - private void saveFieldValue(Object object, Cell cell, Map excelParams, String titleString, Row row, ImportParams importParams) throws Exception { - ExcelImportEntity entity = excelParams.get(titleString); - String xclass = "class java.lang.Object"; - if (!(object instanceof Map)) { - - Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? entity - .getMethods().get(entity.getMethods().size() - 1) : entity.getMethod(); - java.lang.reflect.Type[] ts = setMethod.getGenericParameterTypes(); - xclass = ts[0].toString(); - } - Object result = getCellValue(xclass, cell, entity); - -// if (entity != null) { - // 做值处理 -// result = replaceValue(entity., result); -// } - if (entity != null && entity.getEnum() != null) { - boolean ischeck = EnumUtil.check(entity.getEnum(), String.valueOf(result)); - if (!ischeck) { - DataVerifyResult verifyResult = new DataVerifyResult(); - verifyResult.setSuccess(false); - verifyResult.setMsg("参数[" + entity.getShowname() + "," + result + "]未匹配相应的值信息"); - verifyResultMap.put(row.getRowNum(), verifyResult); - } else { - result = EnumUtil.getKey(entity.getEnum(), String.valueOf(result)); - setValues(entity, object, result); - } - } - if (result instanceof Map) { - ((Map) object).put(titleString, result); - } else { - //可以做值校验 - DataVerifyResult verifyResult = verifyDataUtil.verifyData(object, result, entity.getFiledName(), entity.getShowname(), entity.getVerify(), importParams.getVerifyHanlder()); - //设置校验结果(第一列) - if (verifyResult.isSuccess()) { - setValues(entity, object, result); - } else { - Integer rowNum = Integer.valueOf(row.getRowNum()); - if (verifyResultMap.containsKey(rowNum)) { - // 如果有错误信息,则添加错误数据 - DataVerifyResult tempresult = verifyResultMap.get(rowNum); - tempresult.setMsg(tempresult.getMsg() + " " + verifyResult.getMsg()); - verifyResultMap.put(rowNum, tempresult); - } else { - verifyResultMap.put(rowNum, verifyResult); - } - verfiyFail = true; - } - } - } - - public void setValues(ExcelImportEntity entity, Object object, Object value) throws Exception { - if (entity.getMethods() != null) { - setFieldBySomeMethod(entity.getMethods(), object, value); - } else { - /* - if (String.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, value); - } else if (Long.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Long.valueOf(value.toString())); - } else if (int.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Integer.valueOf(value.toString())); - } else if (boolean.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Boolean.valueOf(value.toString())); - } else if (Boolean.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Boolean.valueOf(value.toString())); - } else if (Double.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Double.valueOf(value.toString())); - } else if (Integer.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Integer.valueOf(value.toString())); - } else if (Long.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Long.valueOf(value.toString())); - } else if (Float.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Float.valueOf(value.toString())); - } else if (Short.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, Short.valueOf(value.toString())); - } else if (Number.class.isAssignableFrom(entity.getMethod().getParameterTypes()[0])) { - entity.getMethod().invoke(object, (Number) value); - } else { - - }*/ - entity.getMethod().invoke(object, value); - } - } - - public void setFieldBySomeMethod(List setMethods, Object object, Object value) - throws Exception { - Object t = getFieldBySomeMethod(setMethods, object); - setMethods.get(setMethods.size() - 1).invoke(t, value); - } - - public Object getFieldBySomeMethod(List list, Object t) throws Exception { - Method m; - for (int i = 0; i < list.size() - 1; i++) { - m = list.get(i); - t = m.invoke(t, new Object[]{}); - } - return t; - } - - /** - * 获取单元格内的值 - * - * @param xclass - * @param cell - * @param entity - * @return - */ - private Object getCellValue(String xclass, Cell cell, ExcelImportEntity entity) { - if (cell == null) { - return ""; - } - Object result = null; - // 日期格式比较特殊,和cell格式不一致 - if ("class java.util.Date".equals(xclass) || ("class java.sql.Time").equals(xclass)) { - if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { - // 日期格式 - result = cell.getDateCellValue(); - } else { - cell.setCellType(Cell.CELL_TYPE_STRING); - result = getDateData(entity, cell.getStringCellValue()); - } - if (("class java.sql.Time").equals(xclass)) { - result = new Time(((Date) result).getTime()); - } - } else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { - result = cell.getNumericCellValue(); - } else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) { - result = cell.getBooleanCellValue(); - } else { - result = cell.getStringCellValue(); - } - if ("class java.lang.String".equals(xclass)) { - result = String.valueOf(result); - } - return result; - } - - /** - * 获取日期类型数据 - * - * @param entity - * @param value - * @return - * @Author JueYue - * @date 2013年11月26日 - */ - private Date getDateData(ExcelImportEntity entity, String value) { - if (StringUtils.isNotEmpty(entity.getDateFormat()) && StringUtils.isNotEmpty(value)) { - SimpleDateFormat format = new SimpleDateFormat(entity.getDateFormat()); - try { - return format.parse(value); - } catch (ParseException e) { -// LOGGER.error("时间格式化失败,格式化:" + entity.getDateFormat() + ",值:" + value); - e.printStackTrace(); - } - } - return null; - } - - /** - * 向List 里面添加元素 - * - * @param object - * @param param - * @param row - * @param titlemap - */ - private void addListContinue(Object object, ExcelCollectionEntity param, Row row, Map titlemap, ImportParams importParams) throws Exception { - Collection collection = (Collection) ClassUtil.getMethod(param.getName(), - object.getClass()).invoke(object, new Object[]{}); - Object entity = ClassUtil.createObject(param.getType()); - boolean isUsed = false;// 是否需要加上这个对象 - for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) { - Cell cell = row.getCell(i); - String titleString = (String) titlemap.get(i); - if (param.getExcelParams().containsKey(titleString)) { - saveFieldValue(entity, cell, param.getExcelParams(), titleString, row, importParams); - isUsed = true; - } - } - if (isUsed) { - collection.add(entity); - } - - } - - /** - * 查看某些列的数据,是否存在 - * - * @param row - * @param excelParams - * @return - */ - private Boolean isLineRow(Row row, Map excelParams, Map titlemap) { - Boolean isLineRow = true; - for (Integer index : titlemap.keySet()) { - String titleName = titlemap.get(index); - if (excelParams.containsKey(titleName)) { - Cell cell = row.getCell(index); - Object value = getCellValue("", cell, excelParams.get(titleName)); - if (!StringUtils.isEmpty(String.valueOf(value))) { - isLineRow = false; - break; - } - } - } - return isLineRow; - } - - /** - * 获取Title 与Index 关系 - * - * @param row - * @param excelParams - * @param excelCollection - * @return - */ - private Map getTitleMap(Row row, Map excelParams, List excelCollection) throws Exception { - Map titlemap = new HashMap(); - Iterator cellTitle = row.cellIterator(); - while (cellTitle.hasNext()) { - Cell cell = cellTitle.next(); - String value = getKeyValue(cell).replace("*", "").replace("\n", ""); - int i = cell.getColumnIndex(); - //支持重名导入 - if (StringUtils.isNotEmpty(value)) { - //判断当前列索引,是否为明细值 - if (!excelParams.containsKey(value)) { - if (excelCollection != null && !excelCollection.isEmpty()) { - for (ExcelCollectionEntity entity : excelCollection) { - if (entity.getExcelParams().containsKey(entity.getExcelName() + "_" + value)) { - ExcelImportEntity excelImportEntity = entity.getExcelParams().get(entity.getExcelName() + "_" + value); - excelImportEntity.setFiledName(entity.getName() + "_" + excelImportEntity.getFiledName()); - titlemap.put(i, entity.getExcelName() + "_" + value); - break; - } - } - } - } else { - titlemap.put(i, value); - } - } - } - //判断是否所有的列都满足,不满足抛Exception - //1判断主要信息 - Set params = excelParams.keySet(); - StringBuffer sb = new StringBuffer(); - for (String key : params) { - if (!titlemap.containsValue(key)) { - sb.append(key).append(" "); - } - } - for (ExcelCollectionEntity entity : excelCollection) { - Set eparams = entity.getExcelParams().keySet(); - for (String key : eparams) { - if (!titlemap.containsValue(key)) { - sb.append(key).append(" "); - } - } - } - if (sb.length() > 0) { - throw new Exception("不匹配的Excel文件,缺少如下标题:" + sb.toString()); - } - return titlemap; - } - - /** - * 获取key的值,针对不同类型获取不同的值 - * - * @param cell - * @return - * @Author JueYue - * @date 2013-11-21 - */ - private String getKeyValue(Cell cell) { - Object obj = null; - switch (cell.getCellType()) { - case Cell.CELL_TYPE_STRING: - obj = cell.getStringCellValue(); - break; - case Cell.CELL_TYPE_BOOLEAN: - obj = cell.getBooleanCellValue(); - break; - case Cell.CELL_TYPE_NUMERIC: - obj = cell.getNumericCellValue(); - break; - } - return obj == null ? null : obj.toString().trim(); - } - - /** - * 解析获取Excel 信息 - * - * @param fields - * @param excelParams - * @param excelCollection - * @param pojoClass - * @param getMethods - */ - private void getAllExcelField(Field[] fields, Map excelParams, List excelCollection, Class pojoClass, List getMethods) throws Exception { - ExcelImportEntity excelEntity = null; - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; - // 判断是否有注解,没有注解,不需要解析 - HeaderName headerName = field.getAnnotation(HeaderName.class); - ExcelCollection collectionannotation = field.getAnnotation(ExcelCollection.class); - if (headerName != null || collectionannotation != null) { - //如果是List 类型 - if (ClassUtil.isCollection(field.getType())) { - // 集合对象设置属性 - ExcelCollectionEntity collection = new ExcelCollectionEntity(); - collection.setName(field.getName()); - Map temp = new HashMap(); - ParameterizedType pt = (ParameterizedType) field.getGenericType(); - Class clz = (Class) pt.getActualTypeArguments()[0]; - collection.setType(clz); - getExcelFieldList(ClassUtil.getClassFields(clz), clz, temp, null); - collection.setExcelParams(temp); - collection.setExcelName(field.getAnnotation(ExcelCollection.class).value()); - additionalCollectionName(collection); - excelCollection.add(collection); - } else if (ClassUtil.isJavaClass(field)) { - addEntityToMap(field, excelEntity, pojoClass, getMethods, excelParams); - } else { - List newMethods = new ArrayList(); - if (getMethods != null) { - newMethods.addAll(getMethods); - } - newMethods.add(ClassUtil.getMethod(field.getName(), pojoClass)); - getAllExcelField(ClassUtil.getClassFields(field.getType()), - excelParams, excelCollection, field.getType(), newMethods); - } - } - } - - - } - - private void addEntityToMap(Field field, ExcelImportEntity excelEntity, Class pojoClass, List getMethods, Map temp) throws Exception { - HeaderName excel = field.getAnnotation(HeaderName.class); - if (excel != null) { - excelEntity = new ExcelImportEntity(); - excelEntity.setShowname(excel.value()); - excelEntity.setFiledName(field.getName()); - Enum targetEnum = field.getAnnotation(Enum.class); - if (targetEnum != null) { - excelEntity.setEnum(targetEnum.target()); - } - excelEntity.setVerify(getImportVerify(field)); - HeaderDescription headerDescription = field.getAnnotation(HeaderDescription.class); - excelEntity.setDescription(headerDescription == null ? "" : headerDescription.value()); - IsDuplicated isDuplicated = field.getAnnotation(IsDuplicated.class); - if (isDuplicated != null) { - excelEntity.setIsDuplicated(isDuplicated.value()); - } - getExcelField(field, excelEntity, excel, pojoClass); - if (getMethods != null) { - List newMethods = new ArrayList(); - newMethods.addAll(getMethods); - newMethods.add(excelEntity.getMethod()); - excelEntity.setMethods(newMethods); - } - temp.put(excelEntity.getShowname(), excelEntity); - } - } - - /** - * 获取导入校验参数 - * - * @param field - * @return - */ - public ExcelVerifyEntity getImportVerify(Field field) { - ExcelVerify verify = field.getAnnotation(ExcelVerify.class); - if (verify != null) { - ExcelVerifyEntity entity = new ExcelVerifyEntity(); - entity.setEmail(verify.isEmail()); - entity.setInterHandler(verify.interHandler()); - entity.setMaxLength(verify.maxLength()); - entity.setMinLength(verify.minLength()); - entity.setMobile(verify.isMobile()); - entity.setNotNull(verify.notNull()); - entity.setRegex(verify.regex()); - entity.setRegexTip(verify.regexTip()); - entity.setTel(verify.isTel()); - return entity; - } - return null; - } - - /** - * 获取Excel 列信息 - * - * @param field - * @param excelEntity - * @param excel - * @param pojoClass - */ - private void getExcelField(Field field, ExcelImportEntity excelEntity, HeaderName excel, Class pojoClass) throws Exception { - String fieldname = field.getName(); - excelEntity.setMethod(ClassUtil.getMethod(fieldname, pojoClass, field.getType())); - if (StringUtils.isNotEmpty(excel.dateFormat())) { - excelEntity.setDateFormat(excel.dateFormat()); - } - } - - private void additionalCollectionName(ExcelCollectionEntity collection) { - Set keys = new HashSet(); - keys.addAll(collection.getExcelParams().keySet()); - for (String key : keys) { - collection.getExcelParams().put(collection.getExcelName() + "_" + key, - collection.getExcelParams().get(key)); - collection.getExcelParams().remove(key); - } - } - - private void getExcelFieldList(Field[] fields, Class pojoClass, Map temp, List getMethods) throws Exception { - ExcelImportEntity excelEntity = null; - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; - if (ClassUtil.isJavaClass(field)) { - addEntityToMap(field, excelEntity, pojoClass, getMethods, temp); - } else { - List newMethods = new ArrayList(); - if (getMethods != null) { - newMethods.addAll(getMethods); - } - newMethods.add(ClassUtil.getMethod(field.getName(), pojoClass, field.getType())); - getExcelFieldList(ClassUtil.getClassFields(field.getType()), - field.getType(), temp, newMethods); - } - } - } - - -} diff --git a/src/main/java/com/wb/excel/api/datatable/ImportParams.java b/src/main/java/com/wb/excel/api/datatable/ImportParams.java deleted file mode 100644 index 244583a..0000000 --- a/src/main/java/com/wb/excel/api/datatable/ImportParams.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.wb.excel.api.datatable; - -import com.wb.excel.api.interfaces.IExcelVerifyHandler; - -/** - * *************************************************************** - *

- *

- * Copyright (c) 2014 –
- *  HeaderDescription:导入参数设置
- * ***************************************************************
- * 
- */ -public class ImportParams { -// /** -// * 表格标题行数,默认0 -// */ -// private int titleRows = 0; -// /** -// * 表头行数,默认1 -// */ -// private int headRows = 1; -// /** -// * 字段真正值和列标题之间的距离 默认0 -// */ -// private int startRows = 0; -// /** -// * 主键设置,如何这个cell没有值,就跳过 或者认为这个是list的下面的值 -// */ -// private int keyIndex = 0; - /** - * 上传表格需要读取的sheet 数量,默认为1 - */ - private int sheetNum = 1; - - /** - * 校验处理接口 - */ - private IExcelVerifyHandler verifyHanlder; -// /** -// * 最后的无效行数 -// */ -// private int lastOfInvalidRow = 0; - - - public int getSheetNum() { - return sheetNum; - } - - public void setSheetNum(int sheetNum) { - this.sheetNum = sheetNum; - } - - public IExcelVerifyHandler getVerifyHanlder() { - return verifyHanlder; - } - - public void setVerifyHanlder(IExcelVerifyHandler verifyHanlder) { - this.verifyHanlder = verifyHanlder; - } - -} diff --git a/src/main/java/com/wb/excel/api/datatable/Cell.java b/src/main/java/com/wb/excel/api/datatable/WCell.java similarity index 90% rename from src/main/java/com/wb/excel/api/datatable/Cell.java rename to src/main/java/com/wb/excel/api/datatable/WCell.java index a53199c..946cd46 100644 --- a/src/main/java/com/wb/excel/api/datatable/Cell.java +++ b/src/main/java/com/wb/excel/api/datatable/WCell.java @@ -12,7 +12,7 @@ import java.io.Serializable; * @author * @since 0.1.0 */ -public class Cell implements Serializable { +public class WCell implements Serializable { /** * 单元格的状态 */ @@ -26,7 +26,7 @@ public class Cell implements Serializable { /** * 默认无参构造方法.会将单元格的状态设为通过. */ - public Cell() { + public WCell() { this.status = Status.PASS; this.value = ""; } @@ -36,7 +36,7 @@ public class Cell implements Serializable { * * @param value 单元格的值. */ - public Cell(String value) { + public WCell(String value) { this.value = value; this.status = Status.PASS; } diff --git a/src/main/java/com/wb/excel/api/datatable/Column.java b/src/main/java/com/wb/excel/api/datatable/WColumn.java similarity index 88% rename from src/main/java/com/wb/excel/api/datatable/Column.java rename to src/main/java/com/wb/excel/api/datatable/WColumn.java index 2224b96..e4b1424 100644 --- a/src/main/java/com/wb/excel/api/datatable/Column.java +++ b/src/main/java/com/wb/excel/api/datatable/WColumn.java @@ -5,13 +5,14 @@ import com.wb.excel.api.enumeration.DataType; import com.wb.excel.api.util.StringUtil; import java.io.Serializable; +import java.lang.reflect.Field; /** * DataTable中的表头,包含本列的一些限制条件。
* 现有:列名、是否必须、是否允许重复、说明字段以及数据类型 * Created by edward on 9/19/14. */ -public class Column implements Serializable { +public class WColumn implements Serializable { /** * 列名 */ @@ -37,7 +38,9 @@ public class Column implements Serializable { */ private DataType dataType; - public Column() { + private Field field; + + public WColumn() { this.name = ""; this.cellWidth = 1; this.isHidden = false; @@ -46,7 +49,7 @@ public class Column implements Serializable { this.dataType = DataType.STRING; } - public Column(String name) { + public WColumn(String name) { this.name = name; this.cellWidth = 1; this.isHidden = false; @@ -67,6 +70,14 @@ public class Column implements Serializable { this.name = name; } + public Field getField() { + return field; + } + + public void setField(Field field) { + this.field = field; + } + public int getCellWidth() { return cellWidth; } diff --git a/src/main/java/com/wb/excel/api/datatable/DataRow.java b/src/main/java/com/wb/excel/api/datatable/WRow.java similarity index 70% rename from src/main/java/com/wb/excel/api/datatable/DataRow.java rename to src/main/java/com/wb/excel/api/datatable/WRow.java index 89a9879..6930e55 100644 --- a/src/main/java/com/wb/excel/api/datatable/DataRow.java +++ b/src/main/java/com/wb/excel/api/datatable/WRow.java @@ -10,5 +10,5 @@ import java.util.HashMap; * @author * @since 0.1.0 */ -public class DataRow extends HashMap implements Serializable { +public class WRow extends HashMap implements Serializable { } diff --git a/src/main/java/com/wb/excel/api/datatable/DataTable.java b/src/main/java/com/wb/excel/api/datatable/WSheet.java similarity index 71% rename from src/main/java/com/wb/excel/api/datatable/DataTable.java rename to src/main/java/com/wb/excel/api/datatable/WSheet.java index 1f1c358..0f30a6f 100644 --- a/src/main/java/com/wb/excel/api/datatable/DataTable.java +++ b/src/main/java/com/wb/excel/api/datatable/WSheet.java @@ -26,6 +26,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.*; +import java.util.Date; /** * 数据表的定义。
@@ -34,7 +35,7 @@ import java.util.*; * @author 沈振家 * @since 0.1.0 */ -public class DataTable implements Serializable, Cloneable { +public class WSheet implements Serializable, Cloneable { public final static String CHECK_STATUS_NAME = "检查状态"; public final static String CHECK_STATUS_RESULT = "结果消息"; @@ -57,7 +58,7 @@ public class DataTable implements Serializable, Cloneable { /** * 表头的集合 */ - private Column[] columns; + private WColumn[] WColumns; /** * 当前的行数 @@ -68,7 +69,7 @@ public class DataTable implements Serializable, Cloneable { /** * 单元格里存放的对象 */ - private Cell[][] data; + private WCell[][] data; /** * 整个Table的错误列表 @@ -87,8 +88,8 @@ public class DataTable implements Serializable, Cloneable { rowIndex = 0; columnIndex = 0; - columns = new Column[MAX_COLUMN_NUMBER]; - data = new Cell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER]; + WColumns = new WColumn[MAX_COLUMN_NUMBER]; + data = new WCell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER]; errorList = new ArrayList<>(); errorLists = new ArrayList<>(MAX_ROW_NUMBER); @@ -100,7 +101,7 @@ public class DataTable implements Serializable, Cloneable { /** * 默认构造方法。 */ - public DataTable() { + public WSheet() { init(); } @@ -109,9 +110,9 @@ public class DataTable implements Serializable, Cloneable { * * @param clazz 模板类 */ - public DataTable(Class clazz) { + public WSheet(Class clazz) { init(); - setColumns(clazz); + initColumns(clazz); } /** @@ -120,45 +121,53 @@ public class DataTable implements Serializable, Cloneable { * @param clazz 模板类 * @return 包含@Name标记的字段Set */ - private Set setColumns(Class clazz) { - HeaderName tempHeaderName = clazz.getAnnotation(HeaderName.class); - ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class); - boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value(); - if (tempHeaderName != null) { - this.setName(tempHeaderName.value()); + private WColumn[] initColumns(Class clazz) { + //获取工作簿名称,没有则以类名为默认工作簿名称 + SheetName sheetName = clazz.getAnnotation(SheetName.class); + if (sheetName != null) { + this.setName(sheetName.value()); } else { this.setName(clazz.getName()); } - //Field [] fields = clazz.getDeclaredFields(); + + //是否关注父类属性 + boolean parentFirst = clazz.isAnnotationPresent(ParentFirst.class) && clazz.getAnnotation(ParentFirst.class).value(); Field[] fields = ClassUtil.getFields(clazz, parentFirst); - Set set = new HashSet<>(); for (Field field : fields) { - set.add(field); - Column column = null; - if (!field.isAnnotationPresent(HeaderName.class)) { - String name = field.getName(); - column = new Column(name); + WColumn WColumn = new WColumn(); + WColumn.setField(field); + if (field.isAnnotationPresent(Ignore.class) && field.getAnnotation(Ignore.class).value()) { + WColumn.setHidden(true); + } + + //获取列名称 + if (!field.isAnnotationPresent(ColumnName.class)) { + WColumn.setName(field.getName()); } else { - HeaderName columnHeaderName = field.getAnnotation(HeaderName.class); - column = new Column(columnHeaderName.value()); + ColumnName columnColumnName = field.getAnnotation(ColumnName.class); + WColumn.setName(columnColumnName.value()); + } + //获取列填写说明或描述 + if (field.isAnnotationPresent(ColumnDescription.class)) { + WColumn.setDescription(field.getAnnotation(ColumnDescription.class).value()); } + + //列填写标志(是否必填) if (field.isAnnotationPresent(NotNull.class)) { - column.setRequired(true); + WColumn.setRequired(true); } - if (field.isAnnotationPresent(Type.class)) { - Type type = field.getAnnotation(Type.class); - column.setDataType(type.value()); + //获取列类型 + if (field.isAnnotationPresent(ColumnType.class)) { + ColumnType columnType = field.getAnnotation(ColumnType.class); + WColumn.setDataType(columnType.value()); } else { - column.setDataType(DataType.STRING); + WColumn.setDataType(DataType.STRING); } - if (field.isAnnotationPresent(HeaderDescription.class)) { - column.setDescription(field.getAnnotation(HeaderDescription.class).value()); - } - this.addColumn(column); + this.addColumn(WColumn); } - return set; + return this.WColumns; } /** @@ -170,75 +179,45 @@ public class DataTable implements Serializable, Cloneable { * @throws InvocationTargetException * @throws IllegalAccessException */ - public DataTable(List list) - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + public WSheet(List list) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { init(); if (list == null || list.size() == 0) { throw new IllegalParameterException("不允许传入空的列表"); } if (list.size() > 0) { T tClass = list.get(0); - Set set = setColumns(tClass.getClass()); + WColumn[] WColumns = initColumns(tClass.getClass()); for (T t : list) { - DataRow row = new DataRow(); - for (Field field : set) { - - // 获取字段上的名称注解(作为列名使用) - String HeaderName = ""; - HeaderName fieldHeaderName = field.getAnnotation(HeaderName.class); - if (fieldHeaderName == null) { - HeaderName = field.getName(); - } else { - HeaderName = fieldHeaderName.value(); + WRow row = new WRow(); + for (WColumn WColumn : WColumns) { + if (WColumn == null) { + continue; } + Field field = WColumn.getField(); String att = StringUtil.upperFirstWord(field.getName()); Method method = t.getClass().getMethod("get" + att); Object value = method.invoke(t); if (null == value) { - row.put(fieldHeaderName.value(), new Cell()); + row.put(WColumn.getName(), new WCell()); } else { - if (field.isAnnotationPresent(Type.class)) { - Type type = field.getAnnotation(Type.class); - switch (type.value()) { - case DATE: { - Date date = (Date) value; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - value = sdf.format(date); - break; - } - case DATETIME: { - Date date = (Date) value; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - value = sdf.format(date); - break; - } - case DATEMINUTE: { - Date date = (Date) value; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - value = sdf.format(date); - break; - } - case NUMBER: - value = StringUtil.transferInteger(value.toString()); - break; - case LONG: - value = StringUtil.transferLong(value.toString()); - break; - case BOOLEAN: - value = StringUtil.transferBoolean(value.toString()); - break; - default: - break; - } - } - - // 如果该变量包含枚举标签,处理枚举 - if (field.isAnnotationPresent(Enum.class)) { + if (field.getType() == Date.class) { + Date date = (Date) value; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + value = sdf.format(date); + } else if (field.getType() == java.sql.Date.class) { + Date date = (Date) value; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + value = sdf.format(date); + } else if (field.getType() == Boolean.class) { + value = StringUtil.transferBoolean(value.toString()); + } else if (field.getType() == Boolean.class) { + value = StringUtil.transferBoolean(value.toString()); + } else if (field.isAnnotationPresent(Enum.class)) { Enum e = field.getAnnotation(Enum.class); value = EnumUtil.getValue(e.target(), value.toString()); } - row.put(HeaderName, new Cell(value.toString())); + row.put(WColumn.getName(), new WCell(value.toString())); } } this.addRow(row); @@ -254,7 +233,7 @@ public class DataTable implements Serializable, Cloneable { * 1.流不能转换为Workbook */ @Deprecated - public DataTable(byte[] bytes) throws IOException, TemplateNotMatchException { + public WSheet(byte[] bytes) throws IOException, TemplateNotMatchException { init(); InputStream inputStream = null; //文件输入流 Workbook workbook = null; //导入的文档 @@ -291,21 +270,21 @@ public class DataTable implements Serializable, Cloneable { int columnNum = headRow.getPhysicalNumberOfCells(); for (int i = 0; i < columnNum; i++) { org.apache.poi.ss.usermodel.Cell cell = headRow.getCell(i); - Column column = new Column(); - column.setName(ExcelUtil.getValue(cell)); - this.addColumn(column); + WColumn WColumn = new WColumn(); + WColumn.setName(ExcelUtil.getValue(cell)); + this.addColumn(WColumn); } /* 逐行读取导入文件的数据,从1开始是因为第0行为表头 */ int rowNumber = sheet.getLastRowNum(); for (int i = 1; i <= rowNumber; i++) { Row inputRow = sheet.getRow(i); - DataRow row = new DataRow(); + WRow row = new WRow(); if (null != inputRow) { for (int j = 0; j < columnNum; j++) { org.apache.poi.ss.usermodel.Cell excelCell = inputRow.getCell(j); if (null != excelCell) { - row.put(this.getColumns()[j].getName(), new Cell(ExcelUtil.getValue(excelCell))); + row.put(this.getWColumns()[j].getName(), new WCell(ExcelUtil.getValue(excelCell))); } } } @@ -324,7 +303,7 @@ public class DataTable implements Serializable, Cloneable { * @throws TemplateNotMatchException
1:Excel文件的列数与对象类型不匹配 - 请检查Excel表与模板类是否一致;
* 2:获取枚举类型出错 - 你在模板类中标注了一个变量的值为枚举类型,但程序寻找枚举类时出错;
*/ - public DataTable(byte[] bytes, Class clazz) throws IOException, TemplateNotMatchException { + public WSheet(byte[] bytes, Class clazz) throws IOException, TemplateNotMatchException { init(); Workbook workbook = null; InputStream is = null; @@ -356,11 +335,11 @@ public class DataTable implements Serializable, Cloneable { String tableName = sheet.getSheetName(); //DataTable的名字 /* 获取指定类所有带有Name注解的属性集合 */ - HeaderName classHeaderName = clazz.getAnnotation(HeaderName.class); //该类所声明的名字 + ColumnName classColumnName = clazz.getAnnotation(ColumnName.class); //该类所声明的名字 ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class); boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value(); - if (classHeaderName != null) { - tableName = classHeaderName.value(); + if (classColumnName != null) { + tableName = classColumnName.value(); } this.setName(tableName); //将类名设为表名,如果类名不存在,将Excel表名设为表名 @@ -368,7 +347,7 @@ public class DataTable implements Serializable, Cloneable { Field[] fields = ClassUtil.getFields(clazz, parentFirst); //该类所声明的全部属性 Set set = new HashSet<>(); //用于保存所有带有Name注解的属性 for (Field field : fields) { - if (field.isAnnotationPresent(HeaderName.class)) { + if (field.isAnnotationPresent(ColumnName.class)) { set.add(field); } } @@ -380,7 +359,7 @@ public class DataTable implements Serializable, Cloneable { /* 为Excel表中的每一列分配空间 */ List> sets = new ArrayList<>(); - Type[] types = new Type[columnSum]; + ColumnType[] columnTypes = new ColumnType[columnSum]; Enum[] enums = new Enum[columnSum]; Split[] splits = new Split[columnSum]; Length[] lengths = new Length[columnSum]; @@ -388,7 +367,7 @@ public class DataTable implements Serializable, Cloneable { Substring[] substrings = new Substring[columnSum]; DecimalMin[] decimalMins = new DecimalMin[columnSum]; DecimalMax[] decimalMaxs = new DecimalMax[columnSum]; - HeaderDescription[] headerDescriptions = new HeaderDescription[columnSum]; + ColumnDescription[] columnDescriptions = new ColumnDescription[columnSum]; IsDuplicated[] isDuplicateds = new IsDuplicated[columnSum]; boolean[] matchFlag = new boolean[set.size()]; //保存字段是否出现在Excel文件中。 @@ -405,10 +384,10 @@ public class DataTable implements Serializable, Cloneable { int tempFieldIndex = 0; //字段的编号,临时变量 for (Field field : set) { - HeaderName fieldHeaderName = field.getAnnotation(HeaderName.class); - if (headValue.equals(fieldHeaderName.value())) { //如果Excel列名与Class属性名相一致 + ColumnName fieldColumnName = field.getAnnotation(ColumnName.class); + if (headValue.equals(fieldColumnName.value())) { //如果Excel列名与Class属性名相一致 columnMatchNumber++; //标记该列的存在 - types[i] = field.getAnnotation(Type.class); + columnTypes[i] = field.getAnnotation(ColumnType.class); enums[i] = field.getAnnotation(Enum.class); splits[i] = field.getAnnotation(Split.class); lengths[i] = field.getAnnotation(Length.class); @@ -416,7 +395,7 @@ public class DataTable implements Serializable, Cloneable { substrings[i] = field.getAnnotation(Substring.class); decimalMins[i] = field.getAnnotation(DecimalMin.class); decimalMaxs[i] = field.getAnnotation(DecimalMax.class); - headerDescriptions[i] = field.getAnnotation(HeaderDescription.class); + columnDescriptions[i] = field.getAnnotation(ColumnDescription.class); isDuplicateds[i] = field.getAnnotation(IsDuplicated.class); matchFlag[tempFieldIndex] = true; @@ -424,18 +403,18 @@ public class DataTable implements Serializable, Cloneable { } tempFieldIndex++; } - Column column = new Column(); - column.setName(ExcelUtil.getValue(cell)); - if (headerDescriptions[i] != null) { - column.setDescription(headerDescriptions[i].value()); + WColumn WColumn = new WColumn(); + WColumn.setName(ExcelUtil.getValue(cell)); + if (columnDescriptions[i] != null) { + WColumn.setDescription(columnDescriptions[i].value()); } - if (types[i] != null) { - column.setDataType(types[i].value()); + if (columnTypes[i] != null) { + WColumn.setDataType(columnTypes[i].value()); } if (notNulls[i] != null) { - column.setRequired(true); + WColumn.setRequired(true); } - this.addColumn(column); + this.addColumn(WColumn); } /* 如果文件不匹配 */ @@ -446,7 +425,7 @@ public class DataTable implements Serializable, Cloneable { if (matchFlag[tempIndex++]) { continue; } - templateExcept.append(field.getAnnotation(HeaderName.class).value()).append("栏;"); + templateExcept.append(field.getAnnotation(ColumnName.class).value()).append("栏;"); } throw new TemplateNotMatchException("不匹配的Excel文件,没有:" + templateExcept.toString()); } @@ -455,7 +434,7 @@ public class DataTable implements Serializable, Cloneable { /* 逐行读取导入文件的数据 */ for (int i = 0; i < maxRowNumber; i++) { Row inputRow = sheet.getRow(i + 1); //Excel中的一行数据,第0行为表头,所以要加1 - DataRow row = new DataRow(); //DataTable中的一行 + WRow row = new WRow(); //DataTable中的一行 this.addRow(row); if (null != inputRow) { @@ -463,8 +442,8 @@ public class DataTable implements Serializable, Cloneable { /* 取得当前格子的值 */ org.apache.poi.ss.usermodel.Cell excelCell = inputRow.getCell(j); - Cell cell = new Cell(); - this.setCell(i, columns[j].getName(), cell); + WCell WCell = new WCell(); + this.setCell(i, WColumns[j].getName(), WCell); String value = ""; if (null != excelCell) { @@ -483,7 +462,7 @@ public class DataTable implements Serializable, Cloneable { value = StringUtil.substring(value, substrings[j].start(), substrings[j].end()); } - cell.setValue(value); + WCell.setValue(value); /* 如果要求非空 */ if (null != notNulls[j]) { @@ -512,8 +491,8 @@ public class DataTable implements Serializable, Cloneable { } /* 如果对类型有要求 */ - if (cellFlag && null != types[j] && !types[j].value().equals(DataType.STRING)) { - if (!DataType.check(types[j].value(), cell, value)) { + if (cellFlag && null != columnTypes[j] && !columnTypes[j].value().equals(DataType.STRING)) { + if (!DataType.check(columnTypes[j].value(), WCell, value)) { this.setStatus(i, j, Status.FORMAT); cellFlag = false; } @@ -560,8 +539,8 @@ public class DataTable implements Serializable, Cloneable { * * @return 表头数组 */ - public Column[] getColumns() { - return this.columns; + public WColumn[] getWColumns() { + return this.WColumns; } /** @@ -573,7 +552,7 @@ public class DataTable implements Serializable, Cloneable { * @throws IndexOutOfBoundsException 下标越界 * @throws ColumnNameNotExistException 列名不存在 */ - public Cell getCell(int rowNumber, String columnName) + public WCell getCell(int rowNumber, String columnName) throws IndexOutOfBoundsException, ColumnNameNotExistException { int columnNumber = getColumnIndex(columnName); return getCell(rowNumber, columnNumber); @@ -586,7 +565,7 @@ public class DataTable implements Serializable, Cloneable { * @param columnNumber 列坐标 * @throws IndexOutOfBoundsException 下标越界 */ - public final Cell getCell(int rowNumber, int columnNumber) throws IndexOutOfBoundsException { + public final WCell getCell(int rowNumber, int columnNumber) throws IndexOutOfBoundsException { if (rowNumber > this.rowIndex || rowNumber < 0) { throw new IndexOutOfBoundsException("不存在的行坐标: " + rowNumber); } @@ -601,18 +580,18 @@ public class DataTable implements Serializable, Cloneable { * * @param rowNumber 行坐标 * @param columnNumber 列坐标 - * @param cell 单元格 + * @param WCell 单元格 * @throws IndexOutOfBoundsException 坐标不存在的情况下,会报出异常,提示坐标不存在。 */ - public void setCell(int rowNumber, int columnNumber, Cell cell) throws IndexOutOfBoundsException { + public void setCell(int rowNumber, int columnNumber, WCell WCell) throws IndexOutOfBoundsException { if (rowNumber > this.rowIndex || rowNumber < 0) { throw new IndexOutOfBoundsException("不存在的行坐标: " + rowNumber); } if (columnNumber > this.columnIndex || columnNumber < 0) { throw new IndexOutOfBoundsException("不存在的列坐标: " + columnNumber); } - data[rowNumber][columnNumber] = cell; - this.setStatus(rowNumber, columnNumber, cell.getStatus()); + data[rowNumber][columnNumber] = WCell; + this.setStatus(rowNumber, columnNumber, WCell.getStatus()); } /** @@ -620,14 +599,14 @@ public class DataTable implements Serializable, Cloneable { * * @param rowIndex 行坐标 * @param columnName 列坐标 - * @param cell 单元格 + * @param WCell 单元格 * @throws IndexOutOfBoundsException 下标越界 * @throws ColumnNameNotExistException 列名不存在 */ - public void setCell(int rowIndex, String columnName, Cell cell) + public void setCell(int rowIndex, String columnName, WCell WCell) throws IndexOutOfBoundsException, ColumnNameNotExistException { int columnNumber = getColumnIndex(columnName); - this.setCell(rowIndex, columnNumber, cell); + this.setCell(rowIndex, columnNumber, WCell); } /** @@ -640,14 +619,14 @@ public class DataTable implements Serializable, Cloneable { */ public void setStatus(int rowNumber, int columnNumber, Status status) throws IndexOutOfBoundsException { if (!status.equals(Status.PASS)) { - Cell cell = this.getCell(rowNumber, columnNumber); - if (null == cell) { - cell = new Cell(); - this.setCell(rowNumber, columnNumber, cell); + WCell WCell = this.getCell(rowNumber, columnNumber); + if (null == WCell) { + WCell = new WCell(); + this.setCell(rowNumber, columnNumber, WCell); } - cell.setStatus(status); + WCell.setStatus(status); - StringBuilder message = new StringBuilder(this.getColumns()[columnNumber].getName()); + StringBuilder message = new StringBuilder(this.getWColumns()[columnNumber].getName()); message.append("栏"); switch (status) { case NOTEXIST: @@ -692,7 +671,7 @@ public class DataTable implements Serializable, Cloneable { private int getColumnIndex(String columnName) throws ColumnNameNotExistException { int columnIndex = -1; for (int i = 0; i < this.getColumnIndex(); i++) { - if (this.getColumns()[i].getName().equals(columnName)) { + if (this.getWColumns()[i].getName().equals(columnName)) { columnIndex = i; break; } @@ -723,16 +702,16 @@ public class DataTable implements Serializable, Cloneable { * * @return 行的数组 */ - public DataRow[] getDataRows() { - DataRow[] dataRows = new DataRow[this.rowIndex]; + public WRow[] getDataRows() { + WRow[] wRows = new WRow[this.rowIndex]; for (int i = 0; i < this.rowIndex; i++) { - DataRow row = new DataRow(); + WRow row = new WRow(); for (int j = 0; j < this.columnIndex; j++) { - row.put(this.columns[j].getName(), this.data[i][j]); + row.put(this.WColumns[j].getName(), this.data[i][j]); } - dataRows[i] = row; + wRows[i] = row; } - return dataRows; + return wRows; } /** @@ -740,14 +719,14 @@ public class DataTable implements Serializable, Cloneable { * * @return 获取数据列的Map。 */ - public HashMap> getDataColumns() { - HashMap> columns = new HashMap<>(); + public HashMap> getDataColumns() { + HashMap> columns = new HashMap<>(); for (int i = 0; i < this.columnIndex; i++) { - List list = new ArrayList<>(); + List list = new ArrayList<>(); for (int j = 0; j < this.rowIndex; j++) { list.add(data[j][i]); } - columns.put(this.columns[i].getName(), list); + columns.put(this.WColumns[i].getName(), list); } return columns; } @@ -757,21 +736,21 @@ public class DataTable implements Serializable, Cloneable { * * @param row 一行记录 */ - public void addRow(DataRow row) { + public void addRow(WRow row) { /* 如果占用了一半以上,进行扩容 */ if (this.rowIndex >= MAX_ROW_NUMBER / 2) { expandRow(); } for (int i = 0; i < this.columnIndex; i++) { - Cell cell = row.get(this.columns[i].getName()); - if (null != cell) { - this.setCell(this.rowIndex, i, cell); - int width = StringUtil.getByteLength(cell.getValue()); - if (width > this.getColumns()[i].getCellWidth()) { + WCell WCell = row.get(this.WColumns[i].getName()); + if (null != WCell) { + this.setCell(this.rowIndex, i, WCell); + int width = StringUtil.getByteLength(WCell.getValue()); + if (width > this.getWColumns()[i].getCellWidth()) { if (width > 100) { width = 100; } - this.getColumns()[i].setCellWidth(width); + this.getWColumns()[i].setCellWidth(width); } } } @@ -781,25 +760,25 @@ public class DataTable implements Serializable, Cloneable { /** * 添加一列表头信息,会进行查重。当列数超过定义大小的一半时,会扩大容量至之前的1.5倍。 * - * @param column 要加入的表头信息 + * @param WColumn 要加入的表头信息 */ - public void addColumn(Column column) { + public void addColumn(WColumn WColumn) { /* 如果占用了一半以上,进行扩容 */ if (this.columnIndex >= MAX_COLUMN_NUMBER / 2) { expandColumn(); } boolean exist = false; - column.setName(column.getName().replace("*", "")); //删除标题中的星号 - column.setName(column.getName().replace(" ", "")); //删除标题中的空格 + WColumn.setName(WColumn.getName().replace("*", "")); //删除标题中的星号 + WColumn.setName(WColumn.getName().replace(" ", "")); //删除标题中的空格 for (int i = 0; i < this.columnIndex; i++) { - if (column.getName().equals(this.getColumns()[i].getName())) { + if (WColumn.getName().equals(this.getWColumns()[i].getName())) { exist = true; } } if (!exist) { - this.columns[this.columnIndex++] = column; + this.WColumns[this.columnIndex++] = WColumn; } else { - throw new ExistedColumnNameException("已存在名称为" + column.getName() + "的列"); + throw new ExistedColumnNameException("已存在名称为" + WColumn.getName() + "的列"); } } @@ -809,9 +788,9 @@ public class DataTable implements Serializable, Cloneable { protected void expandColumn() { MAX_COLUMN_NUMBER *= (3 / 2) + 1; /* 扩展表头 */ - Column[] temp = new Column[MAX_COLUMN_NUMBER]; - System.arraycopy(columns, 0, temp, 0, columns.length); - columns = temp; + WColumn[] temp = new WColumn[MAX_COLUMN_NUMBER]; + System.arraycopy(WColumns, 0, temp, 0, WColumns.length); + WColumns = temp; expand(); } @@ -832,7 +811,7 @@ public class DataTable implements Serializable, Cloneable { * 会先把数据复制到临时数组中,再把临时数组指向data */ protected void expand() { - Cell[][] temp = new Cell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER]; + WCell[][] temp = new WCell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER]; for (int i = 0; i < data.length; i++) { System.arraycopy(data[i], 0, temp[i], 0, data[0].length); } @@ -855,35 +834,32 @@ public class DataTable implements Serializable, Cloneable { T object = clazz.newInstance(); ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class); boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value(); - //Field[] fields = clazz.getDeclaredFields(); Field[] fields = ClassUtil.getFields(clazz, parentFirst); Set set = new HashSet<>(); for (Field field : fields) { - if (field.isAnnotationPresent(HeaderName.class)) { - set.add(field); - } + set.add(field); } for (int j = 0; j < this.getColumnIndex(); j++) { - if (this.getColumns()[j].isHidden()) { + if (this.getWColumns()[j].isHidden()) { continue; } - String key = this.getColumns()[j].getName(); + String key = this.getWColumns()[j].getName(); if (key.equals(CHECK_STATUS_NAME) || key.equals(CHECK_STATUS_RESULT)) { continue; } for (Field field : set) { - HeaderName fieldHeaderName = field.getAnnotation(HeaderName.class); + ColumnName fieldColumnName = field.getAnnotation(ColumnName.class); - if (key.equals(fieldHeaderName.value())) { + if (key.equals(fieldColumnName.value())) { String att = StringUtil.upperFirstWord(field.getName()); String value; - Cell cell = this.getCell(rowIndex, j); - if (null != cell) { - value = cell.getValue(); + WCell WCell = this.getCell(rowIndex, j); + if (null != WCell) { + value = WCell.getValue(); Method method = clazz.getMethod("set" + att, field.getType()); if (field.isAnnotationPresent(Enum.class)) { Enum e = field.getAnnotation(Enum.class); @@ -893,43 +869,22 @@ public class DataTable implements Serializable, Cloneable { } else { method.invoke(object, EnumUtil.valueOf(e.target(), sValue)); } - } else if (field.isAnnotationPresent(Type.class)) { - Type type = field.getAnnotation(Type.class); - switch (type.value()) { - case DATETIME: - case DATE: { - Date date = TransferUtil.transferDate(value); - method.invoke(object, date); - break; - } - case DATEMINUTE: { - Date date = TransferUtil.transferDateminute(value); - method.invoke(object, date); - break; - } - case DECIMAL: - Double d = TransferUtil.transferDouble(value); - method.invoke(object, d); - break; - - case NUMBER: - Integer integer = TransferUtil.transferInteger(value); - method.invoke(object, integer); - break; - - case BOOLEAN: - Boolean b = TransferUtil.transferBoolean(value); - method.invoke(object, b); - break; - - case LONG: - Long l = TransferUtil.transferLong(value); - method.invoke(object, l); - break; - default: - method.invoke(object, value); - break; - } + } else if (field.getType() == Date.class || field.getType() == java.sql.Date.class) { + Date date = TransferUtil.transferDate(value); + method.invoke(object, date); + } else if (field.getType() == Double.class || field.getType() == double.class + || field.getType() == Float.class || field.getType() == float.class) { + Double d = TransferUtil.transferDouble(value); + method.invoke(object, d); + } else if (field.getType() == Integer.class || field.getType() == int.class + || field.getType() == Long.class || field.getType() == long.class + || field.getType() == Short.class || field.getType() == short.class + || field.getType() == Byte.class || field.getType() == byte.class) { + Integer integer = TransferUtil.transferInteger(value); + method.invoke(object, integer); + } else if (field.getType() == Boolean.class || field.getType() == boolean.class) { + Boolean b = TransferUtil.transferBoolean(value); + method.invoke(object, b); } else { method.invoke(object, value); } @@ -948,7 +903,7 @@ public class DataTable implements Serializable, Cloneable { * 注解的值在这里作为唯一的标识。 * * @return T型列表 - * @see Column 列名称 + * @see WColumn 列名称 */ public List transferList(Class clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { @@ -1000,23 +955,22 @@ public class DataTable implements Serializable, Cloneable { public final String toCSV() { StringBuilder sb = new StringBuilder(); - for (Column column : this.getColumns()) { - if (column != null) { - sb.append(column.getName()).append(","); + for (WColumn WColumn : this.getWColumns()) { + if (WColumn != null) { + sb.append(WColumn.getName()).append(","); } } sb.append("\n"); for (int i = 0; i < this.getRowIndex(); i++) { for (int j = 0; j < this.getColumnIndex(); j++) { - Cell cell = this.getCell(i, j); - if (this.getColumns()[j].getDataType().equals(DataType.STRING) - || this.getColumns()[j].getDataType().equals(DataType.DATE) - || this.getColumns()[j].getDataType().equals(DataType.DATETIME) - || this.getColumns()[j].getDataType().equals(DataType.DATEMINUTE)) { - sb.append("\"\t").append(cell.getValue()).append("\","); + WCell WCell = this.getCell(i, j); + if (this.getWColumns()[j].getDataType().equals(DataType.STRING) + || this.getWColumns()[j].getDataType().equals(DataType.DATE) + || this.getWColumns()[j].getDataType().equals(DataType.DATETIME)) { + sb.append("\"\t").append(WCell.getValue()).append("\","); } else { - sb.append(cell.getValue()).append(","); + sb.append(WCell.getValue()).append(","); } } sb.append("\n"); @@ -1030,11 +984,11 @@ public class DataTable implements Serializable, Cloneable { for (int i = 0; i < columnIndex; i++) { for (int j = 0; j < rowIndex; j++) { int length = StringUtil.getByteLength(this.getCell(j, i).getValue()); - if (columns[i].getCellWidth() < length) { + if (WColumns[i].getCellWidth() < length) { if (length > 100) { length = 100; } - columns[i].setCellWidth(length); + WColumns[i].setCellWidth(length); } } } @@ -1044,19 +998,19 @@ public class DataTable implements Serializable, Cloneable { /* 打印表头 */ for (int i = 0; i < this.getColumnIndex(); i++) { - Column column = this.getColumns()[i]; - int width = column.getCellWidth() - StringUtil.getByteLength(column.getName()) + 4; + WColumn WColumn = this.getWColumns()[i]; + int width = WColumn.getCellWidth() - StringUtil.getByteLength(WColumn.getName()) + 4; int left = width / 2; int right = width - left; for (int j = 0; j < left; j++) { sb.append(" "); } - sb.append(column.getName()); + sb.append(WColumn.getName()); for (int j = 0; j < right; j++) { sb.append(" "); } - sumWidth += column.getCellWidth(); + sumWidth += WColumn.getCellWidth(); } sb.append(CHECK_STATUS_NAME); @@ -1071,15 +1025,15 @@ public class DataTable implements Serializable, Cloneable { /* 打印数据 */ for (int i = 0; i < this.getRowIndex(); i++) { for (int j = 0; j < this.getColumnIndex(); j++) { - int cellWidth = this.getColumns()[j].getCellWidth(); - Cell cell = null; + int cellWidth = this.getWColumns()[j].getCellWidth(); + WCell WCell = null; try { - cell = this.getCell(i, j); + WCell = this.getCell(i, j); } catch (Exception e) { e.printStackTrace(); } - if (null != cell) { - Object obj = cell.getValue(); + if (null != WCell) { + Object obj = WCell.getValue(); int width = cellWidth - StringUtil.getByteLength(obj.toString()) + 4; int left = width / 2; int right = width - left; @@ -1088,7 +1042,7 @@ public class DataTable implements Serializable, Cloneable { sb.append(" "); } sb.append(obj); - if (Status.PASS != cell.getStatus()) { + if (Status.PASS != WCell.getStatus()) { sb.append("*"); if (right > 1) { right--; diff --git a/src/main/java/com/wb/excel/api/entity/DataVerifyResult.java b/src/main/java/com/wb/excel/api/entity/DataVerifyResult.java index 9fb9ed9..f19279a 100644 --- a/src/main/java/com/wb/excel/api/entity/DataVerifyResult.java +++ b/src/main/java/com/wb/excel/api/entity/DataVerifyResult.java @@ -7,7 +7,7 @@ import java.io.Serializable; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:数据校验结果
+ *  ColumnDescription:数据校验结果
  * ***************************************************************
  * 
*/ diff --git a/src/main/java/com/wb/excel/api/entity/ExcelCollectionEntity.java b/src/main/java/com/wb/excel/api/entity/ExcelCollectionEntity.java index f3b676a..42cd014 100644 --- a/src/main/java/com/wb/excel/api/entity/ExcelCollectionEntity.java +++ b/src/main/java/com/wb/excel/api/entity/ExcelCollectionEntity.java @@ -7,7 +7,7 @@ import java.util.Map; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:Excel 集合对象
+ *  ColumnDescription:WExcel 集合对象
  * ***************************************************************
  * 
*/ @@ -17,7 +17,7 @@ public class ExcelCollectionEntity { */ private String name; /** - * Excel 列名称 + * WExcel 列名称 */ private String excelName; /** diff --git a/src/main/java/com/wb/excel/api/entity/ExcelEntity.java b/src/main/java/com/wb/excel/api/entity/ExcelEntity.java index 64370ba..f3f62a5 100644 --- a/src/main/java/com/wb/excel/api/entity/ExcelEntity.java +++ b/src/main/java/com/wb/excel/api/entity/ExcelEntity.java @@ -8,7 +8,7 @@ import java.util.List; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:
+ *  ColumnDescription:
  * ***************************************************************
  * 
*/ diff --git a/src/main/java/com/wb/excel/api/entity/ExcelImportEntity.java b/src/main/java/com/wb/excel/api/entity/ExcelImportEntity.java index 996eca0..d61d44e 100644 --- a/src/main/java/com/wb/excel/api/entity/ExcelImportEntity.java +++ b/src/main/java/com/wb/excel/api/entity/ExcelImportEntity.java @@ -5,7 +5,7 @@ package com.wb.excel.api.entity; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:导入的实体信息
+ *  ColumnDescription:导入的实体信息
  * ***************************************************************
  * 
*/ diff --git a/src/main/java/com/wb/excel/api/entity/ExcelImportResult.java b/src/main/java/com/wb/excel/api/entity/ExcelImportResult.java index d130099..e436a91 100644 --- a/src/main/java/com/wb/excel/api/entity/ExcelImportResult.java +++ b/src/main/java/com/wb/excel/api/entity/ExcelImportResult.java @@ -15,7 +15,7 @@ import java.util.Map; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:导入返回结果
+ *  ColumnDescription:导入返回结果
  * ***************************************************************
  * 
*/ diff --git a/src/main/java/com/wb/excel/api/entity/ExcelVerifyEntity.java b/src/main/java/com/wb/excel/api/entity/ExcelVerifyEntity.java index a3dd496..aa064c2 100644 --- a/src/main/java/com/wb/excel/api/entity/ExcelVerifyEntity.java +++ b/src/main/java/com/wb/excel/api/entity/ExcelVerifyEntity.java @@ -1,7 +1,7 @@ package com.wb.excel.api.entity; /** - * Excel 校验对象 + * WExcel 校验对象 */ public class ExcelVerifyEntity { diff --git a/src/main/java/com/wb/excel/api/enumeration/DataType.java b/src/main/java/com/wb/excel/api/enumeration/DataType.java index f7b51e6..697c70a 100644 --- a/src/main/java/com/wb/excel/api/enumeration/DataType.java +++ b/src/main/java/com/wb/excel/api/enumeration/DataType.java @@ -1,8 +1,8 @@ package com.wb.excel.api.enumeration; -import com.wb.excel.api.annotation.HeaderDescription; -import com.wb.excel.api.annotation.HeaderName; -import com.wb.excel.api.datatable.Cell; +import com.wb.excel.api.annotation.ColumnDescription; +import com.wb.excel.api.annotation.ColumnName; +import com.wb.excel.api.datatable.WCell; import com.wb.excel.api.util.EnumUtil; import com.wb.excel.api.util.StringUtil; import com.wb.excel.api.util.ValidationUtil; @@ -16,98 +16,62 @@ import com.wb.excel.api.util.ValidationUtil; * @version v1.0.0.0 */ public enum DataType { - @HeaderName("字符型") - @HeaderDescription("普通的字符串类型,例如:abc123.,!@#") + @ColumnName("字符型") + @ColumnDescription("普通的字符串类型,例如:abc123.,!@#") STRING, - @HeaderName("整数型") - @HeaderDescription("整数类型,小数点后的数字会被抹去(不是四舍五入),例如:11,200,4000") + @ColumnName("整数型") + @ColumnDescription("整数类型,小数点后的数字会被抹去(不是四舍五入),例如:11,200,4000") NUMBER, - @HeaderName("数字类型") - @HeaderDescription("可以带小数点的数字类型,例如:1.00,1.01") + @ColumnName("数字类型") + @ColumnDescription("可以带小数点的数字类型,例如:1.00,1.01") DECIMAL, - @HeaderName("网络地址型") - @HeaderDescription("网址,文件地址等。") - URL, - @HeaderName("邮箱型") - @HeaderDescription("邮箱地址,例如:test@xxx.com , test@xxx.com.cn") - EMAIL, - @HeaderName("手机号码型") - @HeaderDescription("手机号码。仅限用于大陆手机号中。如:13300010002") - PHONE, - @HeaderName("日期型") - @HeaderDescription("普通的日期类型,例如:2014-10-01") + @ColumnName("日期型") + @ColumnDescription("普通的日期类型,例如:2014-10-01") DATE, - @HeaderName("时间日期型(秒)") - @HeaderDescription("时间精确到秒的日期类型,例如:2014-10-01 10:30:00") + @ColumnName("时间日期型(秒)") + @ColumnDescription("时间精确到秒的日期类型,例如:2014-10-01 10:30:00") DATETIME, - @HeaderName("时间日期型(分钟)") - @HeaderDescription("时间精确到分钟的日期类型,例如:2014-10-01 10:30") - DATEMINUTE, - @HeaderName("是否型") - @HeaderDescription("指定是或者否的类型,例如:是,否") - BOOLEAN, - @HeaderName("大数型") - @HeaderDescription("用于较大的数字类型,会忽略小数点以后的内容") - LONG; + @ColumnName("是否型") + @ColumnDescription("指定是或者否的类型,例如:是,否") + BOOLEAN; /** * 匹配格式. * * @param type 要判断的类型 - * @param cell 需要判断类型的单元格(可能会有改变值的情况发生,所以需要传入此值) + * @param WCell 需要判断类型的单元格(可能会有改变值的情况发生,所以需要传入此值) * @param value 已被简单处理过的需要判断的值 * @return 匹配结果。true,符合;false,不符合 */ - public static boolean check(DataType type, Cell cell, String value) { + public static boolean check(DataType type, WCell WCell, String value) { boolean typeFlag = true; if (value.length() > 0) { switch (type) { - case EMAIL: - typeFlag = ValidationUtil.checkEmail(value); - break; - case PHONE: - typeFlag = ValidationUtil.checkPhone(value); - break; - case URL: - typeFlag = ValidationUtil.checkUrl(value); - break; case DECIMAL: typeFlag = ValidationUtil.checkDouble(value); break; case NUMBER: typeFlag = ValidationUtil.checkInteger(value); if (typeFlag) { - cell.setValue(StringUtil.transferInteger(value)); + WCell.setValue(StringUtil.transferInteger(value)); } break; case DATE: typeFlag = ValidationUtil.checkDate(value); if (typeFlag) { - cell.setValue(StringUtil.transferDate(value)); + WCell.setValue(StringUtil.transferDate(value)); } break; case DATETIME: typeFlag = ValidationUtil.checkDatetime(value); if (typeFlag) { - cell.setValue(StringUtil.transferDatetime(value)); - } - break; - case DATEMINUTE: - typeFlag = ValidationUtil.checkDatetime(value); - if (typeFlag) { - cell.setValue(StringUtil.transferDateminute(value)); + WCell.setValue(StringUtil.transferDatetime(value)); } break; case BOOLEAN: typeFlag = EnumUtil.check(YesNo.class, value); if (typeFlag) { - cell.setValue(StringUtil.transferBoolean(value)); - } - break; - case LONG: - typeFlag = ValidationUtil.checkLong(value); - if (typeFlag) { - cell.setValue(StringUtil.transferLong(value)); + WCell.setValue(StringUtil.transferBoolean(value)); } break; default: diff --git a/src/main/java/com/wb/excel/api/util/BaseVerifyUtil.java b/src/main/java/com/wb/excel/api/util/BaseVerifyUtil.java index 29685a3..591eae1 100644 --- a/src/main/java/com/wb/excel/api/util/BaseVerifyUtil.java +++ b/src/main/java/com/wb/excel/api/util/BaseVerifyUtil.java @@ -10,7 +10,7 @@ import java.util.regex.Pattern; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:数据基础校验
+ *  ColumnDescription:数据基础校验
  * ***************************************************************
  * 
*/ diff --git a/src/main/java/com/wb/excel/api/util/ClassUtil.java b/src/main/java/com/wb/excel/api/util/ClassUtil.java index 0db27a9..5c13325 100644 --- a/src/main/java/com/wb/excel/api/util/ClassUtil.java +++ b/src/main/java/com/wb/excel/api/util/ClassUtil.java @@ -15,6 +15,13 @@ import java.util.*; */ public class ClassUtil { + /** + * 获取模板类所有字段 + * + * @param clazz 模板对象 + * @param parentFirst 是否关注父类的字段 + * @return + */ public static Field[] getFields(Class clazz, boolean parentFirst) { List returnList = new ArrayList<>(); Set nameSet = new HashSet<>(); diff --git a/src/main/java/com/wb/excel/api/util/StringUtils.java b/src/main/java/com/wb/excel/api/util/StringUtils.java index d76add6..efe7e74 100644 --- a/src/main/java/com/wb/excel/api/util/StringUtils.java +++ b/src/main/java/com/wb/excel/api/util/StringUtils.java @@ -7,7 +7,7 @@ import org.apache.poi.hpsf.Constants; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:
+ *  ColumnDescription:
  * ***************************************************************
  * 
*/ diff --git a/src/main/java/com/wb/excel/api/util/VerifyDataUtil.java b/src/main/java/com/wb/excel/api/util/VerifyDataUtil.java index 3107441..e46319f 100644 --- a/src/main/java/com/wb/excel/api/util/VerifyDataUtil.java +++ b/src/main/java/com/wb/excel/api/util/VerifyDataUtil.java @@ -9,7 +9,7 @@ import com.wb.excel.api.interfaces.IExcelVerifyHandler; *

*

  * Copyright (c) 2014 –
- *  HeaderDescription:
+ *  ColumnDescription:
  * ***************************************************************
  * 
*/ diff --git a/src/test/java/ExampleTest.java b/src/test/java/ExampleTest.java index a2e86e7..d4a29e5 100644 --- a/src/test/java/ExampleTest.java +++ b/src/test/java/ExampleTest.java @@ -1,11 +1,12 @@ -import com.wb.excel.api.Excel; -import com.wb.excel.api.datatable.DataTable; +import com.wb.excel.api.WExcel; +import com.wb.excel.api.datatable.WSheet; import com.wb.excel.api.enumeration.YesNo; import com.wb.excel.api.exception.TemplateNotMatchException; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; +import java.util.Date; import java.util.List; /** @@ -24,19 +25,23 @@ public class ExampleTest { //第一步,准备数据模型及数据,模型需要打上注解 List pos = new ArrayList(); - User user = new User("张三", "zs123", "123123"); + User user = new User(); + user.setName("张三"); + user.setDate(new Date()); + user.setSqlDate(new java.sql.Date(new Date().getTime())); + user.setAge(20); user.setSex(YesNo.Y); pos.add(user); pos.add(user); //第二步,初始化数据 - DataTable dataTable = new DataTable(pos); + WSheet WSheet = new WSheet(pos); //第三步,初始化Excel - Excel excel = new Excel(dataTable); + WExcel WExcel = new WExcel(false, WSheet); //第四步,导出xlsx文件 - output("user.xlsx", excel.getBytes()); + output("user.xlsx", WExcel.getBytes()); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IOException e) { @@ -46,7 +51,6 @@ public class ExampleTest { } catch (InvocationTargetException e) { e.printStackTrace(); } - } public static void testImport() { @@ -57,13 +61,13 @@ public class ExampleTest { byte[] bytes = new byte[stream.available()]; stream.read(bytes); - DataTable dataTable = new DataTable(bytes, User.class); + WSheet WSheet = new WSheet(bytes, User.class); - if (dataTable.hasError()) { - Excel excel = new Excel(true, dataTable); - output("user_err.xlsx", excel.getBytes()); + if (WSheet.hasError()) { + WExcel WExcel = new WExcel(true, WSheet); + output("user_err.xlsx", WExcel.getBytes()); } else { - List list = dataTable.transferList(User.class); + List list = WSheet.transferList(User.class); System.out.println("本次读取数据" + list.size() + "条!"); } diff --git a/src/test/java/User.java b/src/test/java/User.java index 1e361b9..f412083 100644 --- a/src/test/java/User.java +++ b/src/test/java/User.java @@ -1,26 +1,28 @@ +import com.wb.excel.api.annotation.ColumnName; import com.wb.excel.api.annotation.Enum; import com.wb.excel.api.annotation.EnumValue; +import com.wb.excel.api.annotation.SheetName; import com.wb.excel.api.enumeration.YesNo; +import javax.validation.constraints.NotNull; +import java.sql.Date; +@SheetName("用户") public class User { + @NotNull + @ColumnName("姓名") private String name; - private String password; - private String qq; - + @ColumnName("出生日期时间") + private java.util.Date date; + @ColumnName("出生日期") + private Date sqlDate; + @ColumnName("年纪") + private int age; @Enum(target = YesNo.class) + @ColumnName("性别") private YesNo sex; - public User() { - } - - public User(String name, String password, String qq) { - this.name = name; - this.password = password; - this.qq = qq; - } - public YesNo getSex() { return sex; } @@ -29,14 +31,6 @@ public class User { this.sex = sex; } - public String getQq() { - return qq; - } - - public void setQq(String qq) { - this.qq = qq; - } - public String getName() { return name; } @@ -45,11 +39,28 @@ public class User { this.name = name; } - public String getPassword() { - return password; + public java.util.Date getDate() { + return date; } - public void setPassword(String password) { - this.password = password; + public void setDate(java.util.Date date) { + this.date = date; } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + }