master
wangbing 5 years ago
parent 94f0b157f5
commit b86062b7a7

@ -12,11 +12,13 @@
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId> <artifactId>hibernate-validator</artifactId>
<version>5.1.2.Final</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>javax.el</groupId>
<artifactId>hibernate-validator</artifactId> <artifactId>javax.el-api</artifactId>
<version>5.1.2.Final</version> <version>2.2.4</version>
</dependency> </dependency>
<dependency> <dependency>

@ -1,26 +1,16 @@
package com.wb.excel.api; 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.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class WCell implements Serializable { public class WCell implements Serializable {
private Status status;
private String value; private String value;
private List<DataVerifyResult> verifyResultList = new ArrayList<>();
/** /**
* .. * ..
*/ */
public WCell() { public WCell() {
this.status = Status.PASS;
this.value = ""; this.value = "";
} }
@ -31,15 +21,6 @@ public class WCell implements Serializable {
*/ */
public WCell(String value) { public WCell(String value) {
this.value = value; this.value = value;
this.status = Status.PASS;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
} }
public String getValue() { public String getValue() {
@ -49,12 +30,4 @@ public class WCell implements Serializable {
public void setValue(String value) { public void setValue(String value) {
this.value = value; this.value = value;
} }
public void addVerifyResult(DataVerifyResult verifyResult) {
verifyResultList.add(verifyResult);
}
public boolean hasVerifyResult(DataVerifyResult verifyResult) {
return verifyResultList.size() > 0;
}
} }

@ -40,6 +40,8 @@ public class WColumn implements Serializable {
private Field field; private Field field;
private int cellType = 1;
public WColumn() { public WColumn() {
this.name = ""; this.name = "";
this.cellWidth = 1; this.cellWidth = 1;
@ -115,4 +117,12 @@ public class WColumn implements Serializable {
public void setConverter(Converter converter) { public void setConverter(Converter converter) {
this.converter = converter; this.converter = converter;
} }
public int getCellType() {
return cellType;
}
public void setCellType(int cellType) {
this.cellType = cellType;
}
} }

@ -1,7 +1,9 @@
package com.wb.excel.api; package com.wb.excel.api;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
/** /**
* DataTable. * DataTable.
@ -11,4 +13,18 @@ import java.util.HashMap;
* @since 0.1.0 * @since 0.1.0
*/ */
public class WRow extends HashMap<String, WCell> implements Serializable { public class WRow extends HashMap<String, WCell> implements Serializable {
private List<String> errorList = new ArrayList<>();
public final boolean hasError() {
return errorList.size() > 0;
}
public final void addError(String errorMsg) {
errorList.add(errorMsg);
}
public List<String> getErrorList() {
return errorList;
}
} }

@ -3,12 +3,12 @@ package com.wb.excel.api;
import com.wb.excel.api.annotation.*; import com.wb.excel.api.annotation.*;
import com.wb.excel.api.converter.*; import com.wb.excel.api.converter.*;
import com.wb.excel.api.converter.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.IllegalParameterException;
import com.wb.excel.api.exception.TemplateNotMatchException; import com.wb.excel.api.exception.TemplateNotMatchException;
import com.wb.excel.api.style.*; import com.wb.excel.api.style.*;
import com.wb.excel.api.util.ClassUtil; import com.wb.excel.api.util.ClassUtil;
import com.wb.excel.api.util.StringUtil; 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.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.*;
@ -108,24 +108,34 @@ public class WSheet<T> implements Serializable, Cloneable {
} else { } else {
if (field.getType() == boolean.class || field.getType() == Boolean.class) { if (field.getType() == boolean.class || field.getType() == Boolean.class) {
WColumn.setConverter(new BooleanConverter()); WColumn.setConverter(new BooleanConverter());
WColumn.setCellType(Cell.CELL_TYPE_BOOLEAN);
} else if (field.getType() == byte.class || field.getType() == Byte.class) { } else if (field.getType() == byte.class || field.getType() == Byte.class) {
WColumn.setConverter(new ByteConverter()); WColumn.setConverter(new ByteConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == char.class || field.getType() == Character.class) { } else if (field.getType() == char.class || field.getType() == Character.class) {
WColumn.setConverter(new CharacterConverter()); WColumn.setConverter(new CharacterConverter());
WColumn.setCellType(Cell.CELL_TYPE_STRING);
} else if (field.getType() == short.class || field.getType() == Short.class) { } else if (field.getType() == short.class || field.getType() == Short.class) {
WColumn.setConverter(new ShortConverter()); WColumn.setConverter(new ShortConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == int.class || field.getType() == Integer.class) { } else if (field.getType() == int.class || field.getType() == Integer.class) {
WColumn.setConverter(new IntegerConverter()); WColumn.setConverter(new IntegerConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == long.class || field.getType() == Long.class) { } else if (field.getType() == long.class || field.getType() == Long.class) {
WColumn.setConverter(new LongConverter()); WColumn.setConverter(new LongConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == float.class || field.getType() == Float.class) { } else if (field.getType() == float.class || field.getType() == Float.class) {
WColumn.setConverter(new FloatConverter()); WColumn.setConverter(new FloatConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == double.class || field.getType() == Double.class) { } else if (field.getType() == double.class || field.getType() == Double.class) {
WColumn.setConverter(new DoubleConverter()); WColumn.setConverter(new DoubleConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == Date.class) { } else if (field.getType() == Date.class) {
WColumn.setConverter(new DateConverter()); WColumn.setConverter(new DateConverter());
WColumn.setCellType(Cell.CELL_TYPE_NUMERIC);
} else if (field.getType() == String.class) { } else if (field.getType() == String.class) {
WColumn.setConverter(new StringConverter()); WColumn.setConverter(new StringConverter());
WColumn.setCellType(Cell.CELL_TYPE_STRING);
} else { } else {
throw new RuntimeException("Can not find Converter"); throw new RuntimeException("Can not find Converter");
} }
@ -172,7 +182,8 @@ public class WSheet<T> implements Serializable, Cloneable {
if (null == value) { if (null == value) {
row.put(column.getName(), new WCell()); row.put(column.getName(), new WCell());
} else { } 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); this.rowList.add(row);
@ -231,8 +242,6 @@ public class WSheet<T> implements Serializable, Cloneable {
Row headRow = sheet.getRow(0); Row headRow = sheet.getRow(0);
//获取Excel列的总数 //获取Excel列的总数
int columnSum = headRow.getPhysicalNumberOfCells(); int columnSum = headRow.getPhysicalNumberOfCells();
//匹配列的数量。用于判断Excel是否包含所有必须列。
int columnMatchNumber = 0;
//检查列数量 //检查列数量
List<WColumn> list = initColumns(clazz); List<WColumn> list = initColumns(clazz);
@ -253,7 +262,7 @@ public class WSheet<T> implements Serializable, Cloneable {
} }
int maxRowNumber = sheet.getLastRowNum(); //Excel文件的总行数 int maxRowNumber = sheet.getLastRowNum(); //Excel文件的总行数
/* 逐行读取导入文件的数据 */ // 逐行读取导入文件的数据
for (int i = 0; i < maxRowNumber; i++) { for (int i = 0; i < maxRowNumber; i++) {
Row inputRow = sheet.getRow(i + 1); //Excel中的一行数据第0行为表头所以要加1 Row inputRow = sheet.getRow(i + 1); //Excel中的一行数据第0行为表头所以要加1
WRow row = new WRow(); WRow row = new WRow();
@ -275,55 +284,23 @@ public class WSheet<T> implements Serializable, Cloneable {
value = value.trim(); value = value.trim();
WCell.setValue(value); WCell.setValue(value);
}
}
// 检查是否必须项 try {
if (wcolumn.isRequired()) { T t = transferOneObject(clazz, i);
if (value.length() == 0) { List<String> validate = ValidationUtil.validate(t);
WCell.setStatus(Status.EMPTY); 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<T> implements Serializable, Cloneable {
* @throws NoSuchMethodException * @throws NoSuchMethodException
* @throws InvocationTargetException * @throws InvocationTargetException
*/ */
public T transferOneObject(Class<T> clazz, int rowIndex) public T transferOneObject(Class<T> clazz, int rowIndex) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
T object = clazz.newInstance(); T object = clazz.newInstance();
ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class); ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class);
boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value(); boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value();
@ -428,9 +404,9 @@ public class WSheet<T> implements Serializable, Cloneable {
// for (int i = 0; i < this.getRowIndex(); i++) { // for (int i = 0; i < this.getRowIndex(); i++) {
// for (int j = 0; j < this.getColumnIndex(); j++) { // for (int j = 0; j < this.getColumnIndex(); j++) {
// WCell WCell = this.getCell(i, j); // WCell WCell = this.getCell(i, j);
// if (this.columnList.get(j).getDataType().equals(DataType.STRING) // if (this.columnList.get(j).getExcelType().equals(ExcelType.STRING)
// || this.columnList.get(j).getDataType().equals(DataType.DATE) // || this.columnList.get(j).getExcelType().equals(ExcelType.DATE)
// || this.columnList.get(j).getDataType().equals(DataType.DATETIME)) { // || this.columnList.get(j).getExcelType().equals(ExcelType.DATETIME)) {
// sb.append("\"\t").append(WCell.getValue()).append("\","); // sb.append("\"\t").append(WCell.getValue()).append("\",");
// } else { // } else {
// sb.append(WCell.getValue()).append(","); // sb.append(WCell.getValue()).append(",");
@ -449,16 +425,9 @@ public class WSheet<T> implements Serializable, Cloneable {
*/ */
public final boolean hasError() { public final boolean hasError() {
for (WRow wRow : rowList) { for (WRow wRow : rowList) {
Iterator<WCell> iterator = wRow.values().iterator(); if (wRow.hasError()) {
return true;
while (iterator.hasNext()) {
WCell next = iterator.next();
if (next.getStatus().name() != Status.PASS.name()) {
return true;
}
} }
} }
return false; return false;
} }
@ -479,62 +448,55 @@ public class WSheet<T> implements Serializable, Cloneable {
return null; 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(); XSSFWorkbook workbook = new XSSFWorkbook();
//---------- 创建样式 ------------------ //---------- 创建样式 ------------------
CellStyle headCellStyle = new HeadCellStyle(workbook).getStyle(); CellStyle headCellStyle = new HeadCellStyle(workbook).getStyle();
CellStyle errorCellStyle = new ErrorCellStyle(workbook).getStyle(); CellStyle alignRightCellStyle = new AlignRightCellStyle(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();
//----------- 创建字体 ---------------- //----------- 创建字体 ----------------
Font headFont = new HeadFont(workbook).getFont();
Font normalFont = new NormalFont(workbook).getFont(); Font normalFont = new NormalFont(workbook).getFont();
Font redFont = new RedFont(workbook).getFont(); Font redFont = new RedFont(workbook).getFont();
//创建一个Sheet表 //创建一个Sheet表
XSSFSheet sheet = workbook.createSheet(name); XSSFSheet sheet = workbook.createSheet(name);
sheet.setDefaultRowHeightInPoints(20); sheet.setDefaultRowHeightInPoints(18);
Row firstRow = sheet.createRow(0); // 下标为0的行开始 Row firstRow = sheet.createRow(0); // 下标为0的行开始
XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFDrawing drawing = sheet.createDrawingPatriarch();
//----------------表头-------------------- // 错误表头
// if (flag) { // if (checkResult) {
// // 检查结果栏 // // 检查结果栏
// org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(0); // Cell firstCell = firstRow.createCell(this.columnList.size());
// String columnName = WSheet.CHECK_STATUS_NAME;
// firstCell.setCellStyle(headCellStyle); // firstCell.setCellStyle(headCellStyle);
// firstCell.setCellValue(new XSSFRichTextString(columnName)); // firstCell.setCellValue(new XSSFRichTextString("检查结果"));
// sheet.setColumnWidth(0, (4 + 8) * 256); // sheet.setColumnWidth(0, (4 + 8) * 256);
// } // }
// 数据栏
int hiddenNumber = 0;
for (int j = 0; j < this.columnList.size(); j++) { for (int j = 0; j < this.columnList.size(); j++) {
WColumn column = this.columnList.get(j); WColumn column = this.columnList.get(j);
Field field = column.getField(); Field field = column.getField();
Cell firstCell = firstRow.createCell(j);
if (column.isHidden()) {
hiddenNumber++;
continue;
}
int k = j - hiddenNumber;
if (flag) {
k++;
}
org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(k);
String columnName = column.getName(); String columnName = column.getName();
XSSFRichTextString textString; XSSFRichTextString textString;
if (column.isRequired()) { if (column.isRequired()) {
textString = new XSSFRichTextString("*" + columnName); textString = new XSSFRichTextString("*" + columnName);
textString.applyFont(0, 1, redFont); textString.applyFont(0, 1, redFont);
textString.applyFont(1, textString.length(), normalFont); textString.applyFont(1, textString.length(), headFont);
} else { } else {
textString = new XSSFRichTextString(columnName); textString = new XSSFRichTextString(columnName);
textString.applyFont(normalFont); textString.applyFont(headFont);
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(column.getDescription()).append("\n"); sb.append(column.getDescription()).append("\n");
@ -555,82 +517,47 @@ public class WSheet<T> implements Serializable, Cloneable {
} }
firstCell.setCellValue(textString); firstCell.setCellValue(textString);
firstCell.setCellStyle(headCellStyle); firstCell.setCellStyle(headCellStyle);
sheet.setColumnWidth(k, (4 + column.getCellWidth()) * 256); sheet.setColumnWidth(j, (4 + column.getCellWidth()) * 256);
} }
// 错误消息栏 // 错误消息栏
// if (flag) { // if (checkResult) {
// org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(table.getColumnIndex() + 1 - hiddenNumber); // Cell firstCell = firstRow.createCell(this.columnList.size());
// String columnName = WSheet.CHECK_STATUS_RESULT;
// firstCell.setCellStyle(headCellStyle); // firstCell.setCellStyle(headCellStyle);
// firstCell.setCellValue(new XSSFRichTextString(columnName)); // firstCell.setCellValue(new XSSFRichTextString("======================"));
// sheet.setColumnWidth(table.getColumnIndex() + 1, (4 + 10) * 256); // 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++) { 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); 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; for (int j = 0; j < this.columnList.size(); j++) {
hiddenNumber = 0;
for (; j < this.columnList.size(); j++) {
WColumn column = this.columnList.get(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()); WCell WCell = this.rowList.get(i).get(column.getName());
if (null == WCell) { if (null == WCell) {
continue; continue;
} }
String value = WCell.getValue(); String value = WCell.getValue();
xssfCell.setCellValue(value); List<String> 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());
}
// 如果该列是数字类型,则靠右 xssfCell.setCellValue(value);
// 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);
// }
// }
} }
// if (flag && !rowFlag) { if (flag)
// Cell xssfCell = row.createCell(j + 1 - hiddenNumber);
// xssfCell.setCellValue(table.getRowError(i));
// xssfCell.setCellStyle(checkMessageCellStyle);
// }
} }
return workbook; return workbook;
} }
@ -652,7 +579,9 @@ public class WSheet<T> implements Serializable, Cloneable {
Date value = cell.getDateCellValue(); Date value = cell.getDateCellValue();
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value); return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
} else { } else {
return String.valueOf(cell.getNumericCellValue()); double numericCellValue = cell.getNumericCellValue();
String s = String.valueOf(numericCellValue);
return s.replaceAll("\\.0$", "");
} }
default: default:
return cell.getStringCellValue(); return cell.getStringCellValue();

@ -5,6 +5,11 @@ public class FloatConverter implements Converter<Float> {
@Override @Override
public Float convert(String var) { public Float convert(String var) {
try { try {
//增加对1.0一类的的优化显示
if (var.matches("(\\d+)\\.0")) {
var = var.replaceAll("\\.0$", "");
}
return Float.parseFloat(var); return Float.parseFloat(var);
} catch (Exception e) { } catch (Exception e) {
return 0f; return 0f;

@ -1,10 +1,23 @@
package com.wb.excel.api.converter; package com.wb.excel.api.converter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LongConverter implements Converter<Long> { public class LongConverter implements Converter<Long> {
@Override @Override
public Long convert(String var) { public Long convert(String var) {
try { 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); return Long.parseLong(var);
} catch (Exception e) { } catch (Exception e) {
return 0L; return 0L;

@ -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;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* ColumnDescription:
* ***************************************************************
* </pre>
*/
public class ExcelImportResult<T> {
/**
*
*/
private List<T> list;
/**
*
*/
private boolean verfiyFail;
private Map<Integer, DataVerifyResult> verifyResult;
/**
*
*/
private Workbook workbook;
private CellStyle errorMessageStyle;
private ErrorCellStyle errorCellStyle;
public ExcelImportResult(List<T> list, boolean verfiyFail, Workbook workbook, Map<Integer, DataVerifyResult> verifyResult) {
this.list = list;
this.verfiyFail = verfiyFail;
this.workbook = workbook;
this.verifyResult = verifyResult;
this.createErrorCellStyle(workbook);
errorCellStyle = new ErrorCellStyle(workbook);
}
public List<T> getList() {
return list;
}
public Workbook getWorkbook() {
//循环添加错误信息
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> 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<Integer, String> temptitle = new HashMap<Integer, String>();
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<Integer, String> temptitle = new HashMap<Integer, String>();
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<T> list) {
this.list = list;
}
public void setVerfiyFail(boolean verfiyFail) {
this.verfiyFail = verfiyFail;
}
public void setWorkbook(Workbook workbook) {
this.workbook = workbook;
}
public void setVerifyResult(Map<Integer, DataVerifyResult> verifyResult) {
Iterator<Integer> 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);
}
}

@ -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);
}
}

@ -1,5 +1,6 @@
package com.wb.excel.api.style; 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.CellStyle;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
@ -16,7 +17,16 @@ public class BaseCellStyle {
protected CellStyle style; protected CellStyle style;
public BaseCellStyle(Workbook workbook) { public BaseCellStyle(Workbook workbook) {
this(workbook, false);
}
public BaseCellStyle(Workbook workbook, boolean error) {
style = workbook.createCellStyle(); style = workbook.createCellStyle();
style.setFillPattern(CellStyle.NO_FILL); //单元格不填充
if (error) {
style.setFillForegroundColor(HSSFColor.RED.index); //背景颜色红色
style.setFillPattern(CellStyle.SOLID_FOREGROUND); //设置单元格填充样式
}
} }
public CellStyle getStyle() { public CellStyle getStyle() {

@ -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());
}
}

@ -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); //上下居中
}
}

@ -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());
}
}

@ -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());
}
}

@ -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);
}
}

@ -5,12 +5,6 @@ import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
/**
* Created on 2015/1/29.
*
* @author
* @since 2.0.0
*/
public class HeadCellStyle extends BaseCellStyle { public class HeadCellStyle extends BaseCellStyle {
public HeadCellStyle(Workbook workbook) { public HeadCellStyle(Workbook workbook) {
super(workbook); super(workbook);
@ -18,6 +12,7 @@ public class HeadCellStyle extends BaseCellStyle {
style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置单元格填充样式 style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置单元格填充样式
style.setAlignment(CellStyle.ALIGN_CENTER); // 居中 style.setAlignment(CellStyle.ALIGN_CENTER); // 居中
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//上下居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//上下居中
style.setFont(new HeadFont(workbook).getFont());
//下边框 //下边框
style.setBorderBottom(CellStyle.SOLID_FOREGROUND); style.setBorderBottom(CellStyle.SOLID_FOREGROUND);

@ -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);
}
}

@ -12,9 +12,11 @@ import org.apache.poi.ss.usermodel.Workbook;
*/ */
public class NormalCellStyle extends BaseCellStyle { public class NormalCellStyle extends BaseCellStyle {
public NormalCellStyle(Workbook workbook) { public NormalCellStyle(Workbook workbook) {
super(workbook); this(workbook, false);
style.setFillPattern(CellStyle.NO_FILL); //单元格不填充 }
//style.setFont(font); //设置单元格字体
public NormalCellStyle(Workbook workbook, boolean error) {
super(workbook, error);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //上下居中 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); //上下居中
style.setBorderBottom(CellStyle.SOLID_FOREGROUND); //下边框 style.setBorderBottom(CellStyle.SOLID_FOREGROUND); //下边框
style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //下边框颜色 style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //下边框颜色

@ -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);
}
}

@ -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<String> validate(Object req) {
List<String> validResult = new ArrayList<>();
if (req == null) {
validResult.add("当前数据为空");
return validResult;
}
try {
Validator validator = factory.getValidator();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(req);
if (constraintViolations.size() > 0) {
for (ConstraintViolation<Object> violation : constraintViolations) {
validResult.add(violation.getMessage());
}
}
} catch (Exception e) {
validResult.add("数据检查错误");
}
return validResult;
}
}

@ -13,8 +13,8 @@ import java.util.List;
public class ExampleTest { public class ExampleTest {
public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
testTemplate(); // testTemplate();
testExport(); // testExport();
testImport(); testImport();
} }
@ -71,12 +71,13 @@ public class ExampleTest {
byte[] bytes = new byte[stream.available()]; byte[] bytes = new byte[stream.available()];
stream.read(bytes); stream.read(bytes);
WSheet WSheet = new WSheet(bytes, User.class); WSheet<User> WSheet = new WSheet<>(bytes, User.class);
if (WSheet.hasError()) { if (WSheet.hasError()) {
// WExcel WExcel = new WExcel(true, WSheet); System.out.println("数据出现非法值");
// output("user_err.xlsx", WExcel.getBytes()); output("user_err.xlsx", WSheet.getBytes(true));
} else { } else {
System.out.println("数据全部通过");
List<User> list = WSheet.transferList(User.class); List<User> list = WSheet.transferList(User.class);
System.out.println("本次读取数据" + list.size() + "条!"); System.out.println("本次读取数据" + list.size() + "条!");
for (User user : list) { for (User user : list) {

@ -1,11 +1,16 @@
import com.wb.excel.api.annotation.ColumnDescription;
import com.wb.excel.api.annotation.ColumnName; import com.wb.excel.api.annotation.ColumnName;
import com.wb.excel.api.annotation.SheetName; import com.wb.excel.api.annotation.SheetName;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Date; import java.util.Date;
@SheetName("用户") @SheetName("用户")
public class User { public class User {
@NotNull
@ColumnDescription("文字填写规范")
@ColumnName("文字") @ColumnName("文字")
private String wz; private String wz;
@ColumnName("日期时间") @ColumnName("日期时间")
@ -21,6 +26,7 @@ public class User {
@ColumnName("整数") @ColumnName("整数")
private int zs; private int zs;
@ColumnName("长整数") @ColumnName("长整数")
@Min(value = 100,message = "最低不得小于100")
private long czs; private long czs;
@ColumnName("浮点") @ColumnName("浮点")
private float fd; private float fd;

Loading…
Cancel
Save

Powered by TurnKey Linux.