diff --git a/pom.xml b/pom.xml index e5f6851..b95c439 100644 --- a/pom.xml +++ b/pom.xml @@ -12,11 +12,13 @@ org.hibernate hibernate-validator + 5.1.2.Final + - org.hibernate - hibernate-validator - 5.1.2.Final + javax.el + javax.el-api + 2.2.4 diff --git a/src/main/java/com/wb/excel/api/WCell.java b/src/main/java/com/wb/excel/api/WCell.java index e7b584e..9738363 100644 --- a/src/main/java/com/wb/excel/api/WCell.java +++ b/src/main/java/com/wb/excel/api/WCell.java @@ -1,26 +1,16 @@ package com.wb.excel.api; -import com.wb.excel.api.entity.DataVerifyResult; -import com.wb.excel.api.enumeration.Status; - import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; public class WCell implements Serializable { - private Status status; - private String value; - private List verifyResultList = new ArrayList<>(); - /** * 默认无参构造方法.会将单元格的状态设为通过. */ public WCell() { - this.status = Status.PASS; this.value = ""; } @@ -31,15 +21,6 @@ public class WCell implements Serializable { */ public WCell(String value) { this.value = value; - this.status = Status.PASS; - } - - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; } public String getValue() { @@ -49,12 +30,4 @@ public class WCell implements Serializable { public void setValue(String value) { this.value = value; } - - public void addVerifyResult(DataVerifyResult verifyResult) { - verifyResultList.add(verifyResult); - } - - public boolean hasVerifyResult(DataVerifyResult verifyResult) { - return verifyResultList.size() > 0; - } } diff --git a/src/main/java/com/wb/excel/api/WColumn.java b/src/main/java/com/wb/excel/api/WColumn.java index 427f66b..bbb2b3e 100644 --- a/src/main/java/com/wb/excel/api/WColumn.java +++ b/src/main/java/com/wb/excel/api/WColumn.java @@ -40,6 +40,8 @@ public class WColumn implements Serializable { private Field field; + private int cellType = 1; + public WColumn() { this.name = ""; this.cellWidth = 1; @@ -115,4 +117,12 @@ public class WColumn implements Serializable { public void setConverter(Converter converter) { this.converter = converter; } + + public int getCellType() { + return cellType; + } + + public void setCellType(int cellType) { + this.cellType = cellType; + } } diff --git a/src/main/java/com/wb/excel/api/WRow.java b/src/main/java/com/wb/excel/api/WRow.java index 70909e3..fce72d0 100644 --- a/src/main/java/com/wb/excel/api/WRow.java +++ b/src/main/java/com/wb/excel/api/WRow.java @@ -1,7 +1,9 @@ package com.wb.excel.api; import java.io.Serializable; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; /** * DataTable中的行对象. @@ -11,4 +13,18 @@ import java.util.HashMap; * @since 0.1.0 */ public class WRow extends HashMap implements Serializable { + + private List errorList = new ArrayList<>(); + + public final boolean hasError() { + return errorList.size() > 0; + } + + public final void addError(String errorMsg) { + errorList.add(errorMsg); + } + + public List getErrorList() { + return errorList; + } } diff --git a/src/main/java/com/wb/excel/api/WSheet.java b/src/main/java/com/wb/excel/api/WSheet.java index 68439ba..f058cb4 100644 --- a/src/main/java/com/wb/excel/api/WSheet.java +++ b/src/main/java/com/wb/excel/api/WSheet.java @@ -3,12 +3,12 @@ package com.wb.excel.api; import com.wb.excel.api.annotation.*; import com.wb.excel.api.converter.*; import com.wb.excel.api.converter.Converter; -import com.wb.excel.api.enumeration.Status; import com.wb.excel.api.exception.IllegalParameterException; import com.wb.excel.api.exception.TemplateNotMatchException; import com.wb.excel.api.style.*; import com.wb.excel.api.util.ClassUtil; import com.wb.excel.api.util.StringUtil; +import com.wb.excel.api.util.ValidationUtil; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; @@ -108,24 +108,34 @@ public class WSheet implements Serializable, Cloneable { } else { if (field.getType() == boolean.class || field.getType() == Boolean.class) { WColumn.setConverter(new BooleanConverter()); + WColumn.setCellType(Cell.CELL_TYPE_BOOLEAN); } else if (field.getType() == byte.class || field.getType() == Byte.class) { WColumn.setConverter(new ByteConverter()); + WColumn.setCellType(Cell.CELL_TYPE_NUMERIC); } else if (field.getType() == char.class || field.getType() == Character.class) { WColumn.setConverter(new CharacterConverter()); + WColumn.setCellType(Cell.CELL_TYPE_STRING); } else if (field.getType() == short.class || field.getType() == Short.class) { WColumn.setConverter(new ShortConverter()); + WColumn.setCellType(Cell.CELL_TYPE_NUMERIC); } else if (field.getType() == int.class || field.getType() == Integer.class) { WColumn.setConverter(new IntegerConverter()); + WColumn.setCellType(Cell.CELL_TYPE_NUMERIC); } else if (field.getType() == long.class || field.getType() == Long.class) { WColumn.setConverter(new LongConverter()); + WColumn.setCellType(Cell.CELL_TYPE_NUMERIC); } else if (field.getType() == float.class || field.getType() == Float.class) { WColumn.setConverter(new FloatConverter()); + WColumn.setCellType(Cell.CELL_TYPE_NUMERIC); } else if (field.getType() == double.class || field.getType() == Double.class) { WColumn.setConverter(new DoubleConverter()); + WColumn.setCellType(Cell.CELL_TYPE_NUMERIC); } else if (field.getType() == Date.class) { WColumn.setConverter(new DateConverter()); + WColumn.setCellType(Cell.CELL_TYPE_NUMERIC); } else if (field.getType() == String.class) { WColumn.setConverter(new StringConverter()); + WColumn.setCellType(Cell.CELL_TYPE_STRING); } else { throw new RuntimeException("Can not find Converter"); } @@ -172,7 +182,8 @@ public class WSheet implements Serializable, Cloneable { if (null == value) { row.put(column.getName(), new WCell()); } else { - row.put(column.getName(), new WCell(column.getConverter().string(value))); + column.getConverter().string(value); + row.put(column.getName(), new WCell()); } } this.rowList.add(row); @@ -231,8 +242,6 @@ public class WSheet implements Serializable, Cloneable { Row headRow = sheet.getRow(0); //获取Excel列的总数 int columnSum = headRow.getPhysicalNumberOfCells(); - //匹配列的数量。用于判断Excel是否包含所有必须列。 - int columnMatchNumber = 0; //检查列数量 List list = initColumns(clazz); @@ -253,7 +262,7 @@ public class WSheet implements Serializable, Cloneable { } int maxRowNumber = sheet.getLastRowNum(); //Excel文件的总行数 - /* 逐行读取导入文件的数据 */ + // 逐行读取导入文件的数据 for (int i = 0; i < maxRowNumber; i++) { Row inputRow = sheet.getRow(i + 1); //Excel中的一行数据,第0行为表头,所以要加1 WRow row = new WRow(); @@ -275,55 +284,23 @@ public class WSheet implements Serializable, Cloneable { value = value.trim(); WCell.setValue(value); + } + } - // 检查是否必须项 - if (wcolumn.isRequired()) { - if (value.length() == 0) { - WCell.setStatus(Status.EMPTY); - } + try { + T t = transferOneObject(clazz, i); + List validate = ValidationUtil.validate(t); + if (validate.size() > 0) { + for (String s : validate) { + row.addError(s); } - - // 检查长度是否合法 -// if (wcolumn) { -// if (value.length() > lengths[j].max() || value.length() < lengths[j].min()) { -// this.setStatus(i, j, Status.LENGTH); -// cellFlag = false; -// } -// } - - // 检查字符是否符合正则表达式 -// 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; -// } -// } } + } catch (Exception e) { + row.addError("数据检查错误"); } } } -// /** -// * 能过列名取得列下标。 -// * -// * @param columnName 列名 -// * @return 该列对应的下标 -// * @throws ColumnNameNotExistException -// */ -// private int getColumnIndex(String columnName) throws ColumnNameNotExistException { -// int columnIndex = -1; -// for (int i = 0; i < this.getColumnIndex(); i++) { -// if (this.columnList.get(i).getName().equals(columnName)) { -// columnIndex = i; -// break; -// } -// } -// if (columnIndex == -1) { -// throw new ColumnNameNotExistException("不存在的列名:" + columnName); -// } -// return columnIndex; -// } - /** * 转换某行为一个对象 * @@ -335,8 +312,7 @@ public class WSheet implements Serializable, Cloneable { * @throws NoSuchMethodException * @throws InvocationTargetException */ - public T transferOneObject(Class clazz, int rowIndex) - throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { + public T transferOneObject(Class clazz, int rowIndex) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { T object = clazz.newInstance(); ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class); boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value(); @@ -428,9 +404,9 @@ public class WSheet implements Serializable, Cloneable { // for (int i = 0; i < this.getRowIndex(); i++) { // for (int j = 0; j < this.getColumnIndex(); j++) { // WCell WCell = this.getCell(i, j); -// if (this.columnList.get(j).getDataType().equals(DataType.STRING) -// || this.columnList.get(j).getDataType().equals(DataType.DATE) -// || this.columnList.get(j).getDataType().equals(DataType.DATETIME)) { +// if (this.columnList.get(j).getExcelType().equals(ExcelType.STRING) +// || this.columnList.get(j).getExcelType().equals(ExcelType.DATE) +// || this.columnList.get(j).getExcelType().equals(ExcelType.DATETIME)) { // sb.append("\"\t").append(WCell.getValue()).append("\","); // } else { // sb.append(WCell.getValue()).append(","); @@ -449,16 +425,9 @@ public class WSheet implements Serializable, Cloneable { */ public final boolean hasError() { for (WRow wRow : rowList) { - Iterator iterator = wRow.values().iterator(); - - while (iterator.hasNext()) { - WCell next = iterator.next(); - - if (next.getStatus().name() != Status.PASS.name()) { - return true; - } + if (wRow.hasError()) { + return true; } - } return false; } @@ -479,62 +448,55 @@ public class WSheet implements Serializable, Cloneable { return null; } - public XSSFWorkbook getExcel(boolean flag) { + public byte[] getBytes(boolean checkResult) throws IOException { + XSSFWorkbook workbook = getExcel(checkResult); + if (workbook != null) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + workbook.write(outputStream); + return outputStream.toByteArray(); + } + return null; + } + + public XSSFWorkbook getExcel(boolean checkResult) { XSSFWorkbook workbook = new XSSFWorkbook(); //---------- 创建样式 ------------------ CellStyle headCellStyle = new HeadCellStyle(workbook).getStyle(); - CellStyle errorCellStyle = new ErrorCellStyle(workbook).getStyle(); - CellStyle errorNumberCellStyle = new ErrorNumberCellStyle(workbook).getStyle(); - CellStyle normalCellStyle = new NormalCellStyle(workbook).getStyle(); - CellStyle normalNumberCellStyle = new NormalNumberCellStyle(workbook).getStyle(); - CellStyle checkMessageCellStyle = new CheckMessageCellStyle(workbook).getStyle(); - CellStyle checkFailureCellStyle = new CheckFailureCellStyle(workbook).getStyle(); - CellStyle checkSuccessCellStyle = new CheckSuccessCellStyle(workbook).getStyle(); + CellStyle alignRightCellStyle = new AlignRightCellStyle(workbook).getStyle(); //----------- 创建字体 ---------------- + Font headFont = new HeadFont(workbook).getFont(); Font normalFont = new NormalFont(workbook).getFont(); Font redFont = new RedFont(workbook).getFont(); //创建一个Sheet表 XSSFSheet sheet = workbook.createSheet(name); - sheet.setDefaultRowHeightInPoints(20); + sheet.setDefaultRowHeightInPoints(18); Row firstRow = sheet.createRow(0); // 下标为0的行开始 XSSFDrawing drawing = sheet.createDrawingPatriarch(); - //----------------表头-------------------- -// if (flag) { + // 错误表头 +// if (checkResult) { // // 检查结果栏 -// org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(0); -// String columnName = WSheet.CHECK_STATUS_NAME; +// Cell firstCell = firstRow.createCell(this.columnList.size()); // firstCell.setCellStyle(headCellStyle); -// firstCell.setCellValue(new XSSFRichTextString(columnName)); +// firstCell.setCellValue(new XSSFRichTextString("检查结果")); // sheet.setColumnWidth(0, (4 + 8) * 256); // } - // 数据栏 - int hiddenNumber = 0; for (int j = 0; j < this.columnList.size(); j++) { WColumn column = this.columnList.get(j); Field field = column.getField(); - - if (column.isHidden()) { - hiddenNumber++; - continue; - } - int k = j - hiddenNumber; - if (flag) { - k++; - } - org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(k); + Cell firstCell = firstRow.createCell(j); String columnName = column.getName(); XSSFRichTextString textString; if (column.isRequired()) { textString = new XSSFRichTextString("*" + columnName); textString.applyFont(0, 1, redFont); - textString.applyFont(1, textString.length(), normalFont); + textString.applyFont(1, textString.length(), headFont); } else { textString = new XSSFRichTextString(columnName); - textString.applyFont(normalFont); + textString.applyFont(headFont); } StringBuilder sb = new StringBuilder(); sb.append(column.getDescription()).append("\n"); @@ -555,82 +517,47 @@ public class WSheet implements Serializable, Cloneable { } firstCell.setCellValue(textString); firstCell.setCellStyle(headCellStyle); - sheet.setColumnWidth(k, (4 + column.getCellWidth()) * 256); + sheet.setColumnWidth(j, (4 + column.getCellWidth()) * 256); } // 错误消息栏 -// if (flag) { -// org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(table.getColumnIndex() + 1 - hiddenNumber); -// String columnName = WSheet.CHECK_STATUS_RESULT; +// if (checkResult) { +// Cell firstCell = firstRow.createCell(this.columnList.size()); // firstCell.setCellStyle(headCellStyle); -// firstCell.setCellValue(new XSSFRichTextString(columnName)); -// sheet.setColumnWidth(table.getColumnIndex() + 1, (4 + 10) * 256); +// firstCell.setCellValue(new XSSFRichTextString("======================")); +// sheet.setColumnWidth(this.columnList.size() + 1, (4 + 10) * 256); // } // 冻结第一行 - //sheet.createFreezePane(255,1); +// sheet.createFreezePane(255,1); - //------------------数据-------------------- + // 填充数据 for (int i = 0; i < this.rowList.size(); i++) { + boolean flag = this.rowList.get(i).; + WRow wRow = this.rowList.get(i); Row row = sheet.createRow(i + 1); - boolean rowFlag = true; - - //如果该行有错误 -// if (flag) { -// org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(0); -// if (table.getRowError(i) != null) { -// rowFlag = false; -// xssfCell.setCellValue("不通过"); -// xssfCell.setCellStyle(checkFailureCellStyle); -// } else { -// xssfCell.setCellValue("通过"); -// xssfCell.setCellStyle(checkSuccessCellStyle); -// } -// } - int j = 0; - hiddenNumber = 0; - for (; j < this.columnList.size(); j++) { + for (int j = 0; j < this.columnList.size(); j++) { WColumn column = this.columnList.get(j); - if (column.isHidden()) { - hiddenNumber++; - continue; - } - int k = j - hiddenNumber; - if (flag) { - k++; - } - org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(k); + Cell xssfCell = row.createCell(j); WCell WCell = this.rowList.get(i).get(column.getName()); if (null == WCell) { continue; } String value = WCell.getValue(); - xssfCell.setCellValue(value); + List errorList = wRow.getErrorList(); + xssfCell.setCellType(column.getCellType()); + if (column.getCellType() == Cell.CELL_TYPE_NUMERIC || column.getCellType() == Cell.CELL_TYPE_BOOLEAN) { + xssfCell.setCellStyle(new AlignRightCellStyle(workbook, wRow.hasError()).getStyle()); + } else { + xssfCell.setCellStyle(new NormalCellStyle(workbook, flag).getStyle()); + } - // 如果该列是数字类型,则靠右 -// 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 && !WCell.getStatus().equals(Status.PASS)) { -// xssfCell.setCellStyle(errorCellStyle); -// } else { -// xssfCell.setCellStyle(normalCellStyle); -// } -// } + xssfCell.setCellValue(value); } -// if (flag && !rowFlag) { -// Cell xssfCell = row.createCell(j + 1 - hiddenNumber); -// xssfCell.setCellValue(table.getRowError(i)); -// xssfCell.setCellStyle(checkMessageCellStyle); -// } + if (flag) } return workbook; } @@ -652,7 +579,9 @@ public class WSheet implements Serializable, Cloneable { Date value = cell.getDateCellValue(); return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value); } else { - return String.valueOf(cell.getNumericCellValue()); + double numericCellValue = cell.getNumericCellValue(); + String s = String.valueOf(numericCellValue); + return s.replaceAll("\\.0$", ""); } default: return cell.getStringCellValue(); diff --git a/src/main/java/com/wb/excel/api/converter/FloatConverter.java b/src/main/java/com/wb/excel/api/converter/FloatConverter.java index 1e6af31..bf88a2e 100644 --- a/src/main/java/com/wb/excel/api/converter/FloatConverter.java +++ b/src/main/java/com/wb/excel/api/converter/FloatConverter.java @@ -5,6 +5,11 @@ public class FloatConverter implements Converter { @Override public Float convert(String var) { try { + //增加对1.0一类的的优化显示 + if (var.matches("(\\d+)\\.0")) { + var = var.replaceAll("\\.0$", ""); + } + return Float.parseFloat(var); } catch (Exception e) { return 0f; diff --git a/src/main/java/com/wb/excel/api/converter/LongConverter.java b/src/main/java/com/wb/excel/api/converter/LongConverter.java index 7cb422e..7dc7ce9 100644 --- a/src/main/java/com/wb/excel/api/converter/LongConverter.java +++ b/src/main/java/com/wb/excel/api/converter/LongConverter.java @@ -1,10 +1,23 @@ package com.wb.excel.api.converter; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class LongConverter implements Converter { @Override public Long convert(String var) { try { + //增加对1.0一类的的兼容性 + if (var.matches("(\\d+)\\.(\\d*)")) { + Pattern compile = Pattern.compile("(\\d+)\\.(\\d*)"); + Matcher matcher = compile.matcher(var); + if (matcher.find()) { + var = matcher.group(1); + } + } + return Long.parseLong(var); } catch (Exception e) { return 0L; diff --git a/src/main/java/com/wb/excel/api/entity/ExcelImportResult.java b/src/main/java/com/wb/excel/api/entity/ExcelImportResult.java deleted file mode 100644 index 56be87f..0000000 --- a/src/main/java/com/wb/excel/api/entity/ExcelImportResult.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.wb.excel.api.entity; - -import com.wb.excel.api.style.ErrorCellStyle; -import org.apache.poi.ss.usermodel.*; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * *************************************************************** - *

- *

- * Copyright (c) 2014 –
- *  ColumnDescription:导入返回结果
- * ***************************************************************
- * 
- */ -public class ExcelImportResult { - /** - * 结果集 - */ - private List list; - /** - * 是否存在校验失败 - */ - private boolean verfiyFail; - - private Map verifyResult; - - /** - * 数据源 - */ - private Workbook workbook; - private CellStyle errorMessageStyle; - private ErrorCellStyle errorCellStyle; - - public ExcelImportResult(List list, boolean verfiyFail, Workbook workbook, Map verifyResult) { - this.list = list; - this.verfiyFail = verfiyFail; - this.workbook = workbook; - this.verifyResult = verifyResult; - this.createErrorCellStyle(workbook); - errorCellStyle = new ErrorCellStyle(workbook); - } - - public List getList() { - return list; - } - - public Workbook getWorkbook() { - //循环添加错误信息 - Sheet sheet = workbook.getSheetAt(0); - Iterator rows = sheet.rowIterator(); - //行信息,添加校验结果 - Row titleRow = rows.next(); - addValidateTitleInfo(titleRow); - //循环,给行添加错误信息 - Row row = null; - while (rows.hasNext() && (row == null || sheet.getLastRowNum() - row.getRowNum() > 0)) { - row = rows.next(); - addValidateInfo(row, verifyResult.get(row.getRowNum())); - } - return workbook; - } - - public byte[] getBytes() throws IOException { - Workbook tempworkbook = this.getWorkbook(); - if (tempworkbook != null) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - tempworkbook.write(outputStream); - return outputStream.toByteArray(); - } - return null; - } - - /** - * 添加校验信息 - * - * @param row - */ - private void addValidateTitleInfo(Row row) { - Map temptitle = new HashMap(); - for (int i = row.getFirstCellNum(), le = row.getLastCellNum(); i < le; i++) { - temptitle.put(i, row.getCell(i).getStringCellValue()); - } - for (int i = row.getFirstCellNum(), le = row.getLastCellNum(); i < le; i++) { - row.createCell(i + 1).setCellValue(temptitle.get(i)); - } - row.createCell(0).setCellValue("检查状态"); - row.createCell(row.getLastCellNum()).setCellValue("错误信息"); - } - - /** - * 添加错误行信息 - * - * @param row - * @param dataVerifyResult - */ - private void addValidateInfo(Row row, DataVerifyResult dataVerifyResult) { - Map temptitle = new HashMap(); - for (int i = row.getFirstCellNum(), le = row.getLastCellNum(); i < le; i++) { - temptitle.put(i, String.valueOf(getCellValue(row.getCell(i)))); - } - for (int i = row.getFirstCellNum(), le = row.getLastCellNum(); i < le; i++) { - row.createCell(i + 1).setCellValue(temptitle.get(i)); - } - Boolean result = dataVerifyResult == null || dataVerifyResult.isSuccess(); - Cell statusCell = row.createCell(0); - if (!result) { - statusCell.setCellStyle(errorCellStyle.getStyle()); - } - statusCell.setCellValue(result ? "通过" : "不通过"); - Cell errorcell = row.createCell(row.getLastCellNum()); - errorcell.setCellStyle(errorMessageStyle); - errorcell.setCellValue(dataVerifyResult == null ? "" : dataVerifyResult.getMsg()); - } - - /** - * 获取列数据,根据列属性 - * - * @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; - } - - public boolean isVerfiyFail() { - return verfiyFail; - } - - public void setList(List list) { - this.list = list; - } - - public void setVerfiyFail(boolean verfiyFail) { - this.verfiyFail = verfiyFail; - } - - public void setWorkbook(Workbook workbook) { - this.workbook = workbook; - } - - public void setVerifyResult(Map verifyResult) { - Iterator keys = verifyResult.keySet().iterator(); - while (keys.hasNext()) { - Integer key = keys.next(); - if (this.verifyResult == null) { - this.verifyResult = new HashMap<>(); - } - if (this.verifyResult.containsKey(key)) { - DataVerifyResult result = this.verifyResult.get(key); - result.setMsg(result.getMsg() + " " + verifyResult.get(key).getMsg()); - result.setSuccess(verifyResult.get(key).isSuccess()); - this.verifyResult.put(key, result); - } else { - this.verifyResult.put(key, verifyResult.get(key)); - } - } - } - - private void createErrorCellStyle(Workbook workbook) { - errorMessageStyle = workbook.createCellStyle(); - Font font = workbook.createFont(); - font.setColor(Font.COLOR_RED); - errorMessageStyle.setFont(font); - } -} diff --git a/src/main/java/com/wb/excel/api/style/AlignRightCellStyle.java b/src/main/java/com/wb/excel/api/style/AlignRightCellStyle.java new file mode 100644 index 0000000..2555c43 --- /dev/null +++ b/src/main/java/com/wb/excel/api/style/AlignRightCellStyle.java @@ -0,0 +1,24 @@ +package com.wb.excel.api.style; + +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.ss.usermodel.Workbook; + +/** + * Created on 2015/1/29. + * + * @author + * @since 2.0.0 + */ +public class AlignRightCellStyle extends NormalCellStyle { + public AlignRightCellStyle(Workbook workbook) { + this(workbook, false); + } + + public AlignRightCellStyle(Workbook workbook, boolean error) { + super(workbook, error); + style.setAlignment(CellStyle.ALIGN_RIGHT); + Font font = new BaseFont(workbook).getFont(); + style.setFont(font); + } +} diff --git a/src/main/java/com/wb/excel/api/style/BaseCellStyle.java b/src/main/java/com/wb/excel/api/style/BaseCellStyle.java index b76f82b..b18360f 100644 --- a/src/main/java/com/wb/excel/api/style/BaseCellStyle.java +++ b/src/main/java/com/wb/excel/api/style/BaseCellStyle.java @@ -1,5 +1,6 @@ package com.wb.excel.api.style; +import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Workbook; @@ -16,7 +17,16 @@ public class BaseCellStyle { protected CellStyle style; public BaseCellStyle(Workbook workbook) { + this(workbook, false); + } + + public BaseCellStyle(Workbook workbook, boolean error) { style = workbook.createCellStyle(); + style.setFillPattern(CellStyle.NO_FILL); //单元格不填充 + if (error) { + style.setFillForegroundColor(HSSFColor.RED.index); //背景颜色红色 + style.setFillPattern(CellStyle.SOLID_FOREGROUND); //设置单元格填充样式 + } } public CellStyle getStyle() { diff --git a/src/main/java/com/wb/excel/api/style/CheckFailureCellStyle.java b/src/main/java/com/wb/excel/api/style/CheckFailureCellStyle.java deleted file mode 100644 index b84b512..0000000 --- a/src/main/java/com/wb/excel/api/style/CheckFailureCellStyle.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.wb.excel.api.style; - -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Created on 2015/1/29. - * - * @author - * @since 2.0.0 - */ -public class CheckFailureCellStyle extends BaseCellStyle { - public CheckFailureCellStyle(Workbook workbook) { - super(workbook); - Font font = workbook.createFont(); // 单元格的字体 - font.setColor(HSSFColor.WHITE.index); // 字体颜色-白色 - CellStyle style = workbook.createCellStyle(); // 单元格的样式 - style.setFillForegroundColor(HSSFColor.RED.index); // 背景颜色-红色 - style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置单元格填充样式 - style.setAlignment(CellStyle.ALIGN_CENTER); // 居中 - style.setFont(font); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //上下居中 - - //下边框 - style.setBorderBottom(CellStyle.SOLID_FOREGROUND); - //下边框颜色 - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - //左边框 - style.setBorderLeft(CellStyle.SOLID_FOREGROUND); - //左边框颜色 - style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - //右边框 - style.setBorderRight(CellStyle.SOLID_FOREGROUND); - //右边框颜色 - style.setRightBorderColor(IndexedColors.BLACK.getIndex()); - //上边框 - style.setBorderTop(CellStyle.SOLID_FOREGROUND); - //上边框颜色 - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - } -} diff --git a/src/main/java/com/wb/excel/api/style/CheckMessageCellStyle.java b/src/main/java/com/wb/excel/api/style/CheckMessageCellStyle.java deleted file mode 100644 index 3759662..0000000 --- a/src/main/java/com/wb/excel/api/style/CheckMessageCellStyle.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.wb.excel.api.style; - -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Created on 2015/1/29. - * - * @author - * @since 2.0.0 - */ -public class CheckMessageCellStyle extends BaseCellStyle { - public CheckMessageCellStyle(Workbook workbook) { - super(workbook); - Font font = workbook.createFont(); // 单元格的字体 - font.setColor(HSSFColor.BLACK.index); // 字体颜色-黑色 - CellStyle style = workbook.createCellStyle(); // 单元格的样式 - style.setFillPattern(CellStyle.NO_FILL); // 设置单元格无填充 - style.setFont(font); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //上下居中 - } -} diff --git a/src/main/java/com/wb/excel/api/style/CheckSuccessCellStyle.java b/src/main/java/com/wb/excel/api/style/CheckSuccessCellStyle.java deleted file mode 100644 index a6a2e02..0000000 --- a/src/main/java/com/wb/excel/api/style/CheckSuccessCellStyle.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.wb.excel.api.style; - -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Created on 2015/1/29. - * - * @author - * @since 2.0.0 - */ -public class CheckSuccessCellStyle extends BaseCellStyle { - public CheckSuccessCellStyle(Workbook workbook) { - super(workbook); - style.setFillForegroundColor(HSSFColor.LIME.index); // 背景颜色-绿色 - style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置单元格填充样式 - style.setAlignment(CellStyle.ALIGN_CENTER); // 居中 - //style.setFont(font); - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //上下居中 - - //下边框 - style.setBorderBottom(CellStyle.SOLID_FOREGROUND); - //下边框颜色 - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - //左边框 - style.setBorderLeft(CellStyle.SOLID_FOREGROUND); - //左边框颜色 - style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - //右边框 - style.setBorderRight(CellStyle.SOLID_FOREGROUND); - //右边框颜色 - style.setRightBorderColor(IndexedColors.BLACK.getIndex()); - //上边框 - style.setBorderTop(CellStyle.SOLID_FOREGROUND); - //上边框颜色 - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - } -} diff --git a/src/main/java/com/wb/excel/api/style/ErrorCellStyle.java b/src/main/java/com/wb/excel/api/style/ErrorCellStyle.java deleted file mode 100644 index 9eea4b1..0000000 --- a/src/main/java/com/wb/excel/api/style/ErrorCellStyle.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.wb.excel.api.style; - -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Created on 2015/1/29. - * - * @author - * @since 2.0.0 - */ -public class ErrorCellStyle extends BaseCellStyle { - public ErrorCellStyle(Workbook workbook) { - super(workbook); - style.setFillForegroundColor(HSSFColor.ORANGE.index); //背景颜色-紫罗兰色 - style.setFillPattern(CellStyle.SOLID_FOREGROUND); //设置单元格填充样式 - //style.setFont(font); //设置单元格字体 - style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//上下居中 - - //下边框 - style.setBorderBottom(CellStyle.SOLID_FOREGROUND); - //下边框颜色 - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - //左边框 - style.setBorderLeft(CellStyle.SOLID_FOREGROUND); - //左边框颜色 - style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - //右边框 - style.setBorderRight(CellStyle.SOLID_FOREGROUND); - //右边框颜色 - style.setRightBorderColor(IndexedColors.BLACK.getIndex()); - //上边框 - style.setBorderTop(CellStyle.SOLID_FOREGROUND); - //上边框颜色 - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - } -} diff --git a/src/main/java/com/wb/excel/api/style/ErrorNumberCellStyle.java b/src/main/java/com/wb/excel/api/style/ErrorNumberCellStyle.java deleted file mode 100644 index 3d5ebb5..0000000 --- a/src/main/java/com/wb/excel/api/style/ErrorNumberCellStyle.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.wb.excel.api.style; - -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Created on 2015/1/29. - * - * @author - * @since 2.0.0 - */ -public class ErrorNumberCellStyle extends ErrorCellStyle { - public ErrorNumberCellStyle(Workbook workbook) { - super(workbook); - style.setAlignment(CellStyle.ALIGN_RIGHT); - } -} diff --git a/src/main/java/com/wb/excel/api/style/HeadCellStyle.java b/src/main/java/com/wb/excel/api/style/HeadCellStyle.java index 2e668c9..15705c7 100644 --- a/src/main/java/com/wb/excel/api/style/HeadCellStyle.java +++ b/src/main/java/com/wb/excel/api/style/HeadCellStyle.java @@ -5,12 +5,6 @@ import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Workbook; -/** - * Created on 2015/1/29. - * - * @author - * @since 2.0.0 - */ public class HeadCellStyle extends BaseCellStyle { public HeadCellStyle(Workbook workbook) { super(workbook); @@ -18,6 +12,7 @@ public class HeadCellStyle extends BaseCellStyle { style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置单元格填充样式 style.setAlignment(CellStyle.ALIGN_CENTER); // 居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//上下居中 + style.setFont(new HeadFont(workbook).getFont()); //下边框 style.setBorderBottom(CellStyle.SOLID_FOREGROUND); diff --git a/src/main/java/com/wb/excel/api/style/HeadFont.java b/src/main/java/com/wb/excel/api/style/HeadFont.java new file mode 100644 index 0000000..f50b992 --- /dev/null +++ b/src/main/java/com/wb/excel/api/style/HeadFont.java @@ -0,0 +1,16 @@ +package com.wb.excel.api.style; + +import org.apache.poi.ss.usermodel.Workbook; + +/** + * 普通字体.颜色黑 + * Created on 2015/1/29. + * + * @author + * @since 2.0.0 + */ +public class HeadFont extends BaseFont { + public HeadFont(Workbook workbook) { + super(workbook); + } +} diff --git a/src/main/java/com/wb/excel/api/style/NormalCellStyle.java b/src/main/java/com/wb/excel/api/style/NormalCellStyle.java index 27e62c3..ac7126d 100644 --- a/src/main/java/com/wb/excel/api/style/NormalCellStyle.java +++ b/src/main/java/com/wb/excel/api/style/NormalCellStyle.java @@ -12,9 +12,11 @@ import org.apache.poi.ss.usermodel.Workbook; */ public class NormalCellStyle extends BaseCellStyle { public NormalCellStyle(Workbook workbook) { - super(workbook); - style.setFillPattern(CellStyle.NO_FILL); //单元格不填充 - //style.setFont(font); //设置单元格字体 + this(workbook, false); + } + + public NormalCellStyle(Workbook workbook, boolean error) { + super(workbook, error); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //上下居中 style.setBorderBottom(CellStyle.SOLID_FOREGROUND); //下边框 style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //下边框颜色 diff --git a/src/main/java/com/wb/excel/api/style/NormalNumberCellStyle.java b/src/main/java/com/wb/excel/api/style/NormalNumberCellStyle.java deleted file mode 100644 index b2f6513..0000000 --- a/src/main/java/com/wb/excel/api/style/NormalNumberCellStyle.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.wb.excel.api.style; - -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Created on 2015/1/29. - * - * @author - * @since 2.0.0 - */ -public class NormalNumberCellStyle extends NormalCellStyle { - public NormalNumberCellStyle(Workbook workbook) { - super(workbook); - style.setAlignment(CellStyle.ALIGN_RIGHT); - } -} diff --git a/src/main/java/com/wb/excel/api/util/ValidationUtil.java b/src/main/java/com/wb/excel/api/util/ValidationUtil.java new file mode 100644 index 0000000..675d82a --- /dev/null +++ b/src/main/java/com/wb/excel/api/util/ValidationUtil.java @@ -0,0 +1,42 @@ +package com.wb.excel.api.util; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * 验证工具类。提供一些通用简单的数据验证功能 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class ValidationUtil { + + private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + + public static List validate(Object req) { + List validResult = new ArrayList<>(); + if (req == null) { + validResult.add("当前数据为空"); + return validResult; + } + + try { + Validator validator = factory.getValidator(); + Set> constraintViolations = validator.validate(req); + if (constraintViolations.size() > 0) { + for (ConstraintViolation violation : constraintViolations) { + validResult.add(violation.getMessage()); + } + } + } catch (Exception e) { + validResult.add("数据检查错误"); + } + return validResult; + } +} diff --git a/src/test/java/ExampleTest.java b/src/test/java/ExampleTest.java index 1b6a4be..ebc67f2 100644 --- a/src/test/java/ExampleTest.java +++ b/src/test/java/ExampleTest.java @@ -13,8 +13,8 @@ import java.util.List; public class ExampleTest { public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - testTemplate(); - testExport(); +// testTemplate(); +// testExport(); testImport(); } @@ -71,12 +71,13 @@ public class ExampleTest { byte[] bytes = new byte[stream.available()]; stream.read(bytes); - WSheet WSheet = new WSheet(bytes, User.class); + WSheet WSheet = new WSheet<>(bytes, User.class); if (WSheet.hasError()) { -// WExcel WExcel = new WExcel(true, WSheet); -// output("user_err.xlsx", WExcel.getBytes()); + System.out.println("数据出现非法值"); + output("user_err.xlsx", WSheet.getBytes(true)); } else { + System.out.println("数据全部通过"); List list = WSheet.transferList(User.class); System.out.println("本次读取数据" + list.size() + "条!"); for (User user : list) { diff --git a/src/test/java/User.java b/src/test/java/User.java index 9546803..eb95c24 100644 --- a/src/test/java/User.java +++ b/src/test/java/User.java @@ -1,11 +1,16 @@ +import com.wb.excel.api.annotation.ColumnDescription; import com.wb.excel.api.annotation.ColumnName; import com.wb.excel.api.annotation.SheetName; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; import java.util.Date; @SheetName("用户") public class User { + @NotNull + @ColumnDescription("文字填写规范") @ColumnName("文字") private String wz; @ColumnName("日期时间") @@ -21,6 +26,7 @@ public class User { @ColumnName("整数") private int zs; @ColumnName("长整数") + @Min(value = 100,message = "最低不得小于100") private long czs; @ColumnName("浮点") private float fd;