master
wangbing 5 years ago
parent 58a837d81c
commit d011846d84

16
.gitignore vendored

@ -10,3 +10,19 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
/.idea
*.iml
/.settings
/bin
/gen
/build
/gradle
/classes
.classpath
.project
*.gradle
*.bat
gradlew
local.properties

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xyx.wbsite</groupId>
<artifactId>wexcel</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.2.Final</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,341 @@
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.enumeration.DataType;
import com.wb.excel.api.enumeration.Status;
import 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.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
/**
* Excel.
* <p/>
* Created on 2014/9/27.
*
* @author
* @since 0.1.0
*/
public class Excel {
/**
* Excel
*/
private XSSFWorkbook workbook;
/**
*
*/
private CellStyle headCellStyle;
/**
*
*/
private CellStyle errorCellStyle;
/**
* ()
*/
private CellStyle errorNumberCellStyle;
/**
*
*/
private CellStyle normalCellStyle;
/**
*
*/
private CellStyle normalNumberCellStyle;
/**
* ()
*/
private CellStyle checkMessageCellStyle;
/**
*
*/
private CellStyle checkFailureCellStyle;
/**
*
*/
private CellStyle checkSuccessCellStyle;
/**
*
*/
private Font normalFont;
/**
*
*/
private Font redFont;
/**
* Excel.
*/
public void init() {
workbook = new XSSFWorkbook();
//---------- 创建样式 ------------------
headCellStyle = new HeadCellStyle(workbook).getStyle();
errorCellStyle = new ErrorCellStyle(workbook).getStyle();
errorNumberCellStyle = new ErrorNumberCellStyle(workbook).getStyle();
normalCellStyle = new NormalCellStyle(workbook).getStyle();
normalNumberCellStyle = new NormalNumberCellStyle(workbook).getStyle();
checkMessageCellStyle = new CheckMessageCellStyle(workbook).getStyle();
checkFailureCellStyle = new CheckFailureCellStyle(workbook).getStyle();
checkSuccessCellStyle = new CheckSuccessCellStyle(workbook).getStyle();
//----------- 创建字体 ----------------
normalFont = new NormalFont(workbook).getFont();
redFont = new RedFont(workbook).getFont();
}
/**
* .
*/
public Excel() {
init();
}
/**
* DataTableExcel,.<br/>
* .
* {@link Excel#Excel(boolean flag, DataTable... dataTable)}
*
* @param tables DataTable
*/
public Excel(DataTable... tables) {
workbook = this.initExcel(false, tables);
}
/**
* DataTableExcel.
*
* @param table DataTable
* @param flag truefalse
*/
@Deprecated
public Excel(DataTable table, boolean flag) {
workbook = this.initExcel(flag, table);
}
/**
* DataTableExcel.
*
* @param flag truefalse
* @param tables DataTable
*/
public Excel(boolean flag, DataTable... tables) {
workbook = this.initExcel(flag, tables);
}
public XSSFWorkbook initExcel(boolean flag, DataTable... tables) {
init();
Set<String> nameSet = new HashSet<>(tables.length);
for (DataTable table : tables) {
String name = table.getName();
int index = 1;
while (nameSet.contains(name)) {
name = table.getName() + "(" + index + ")";
index++;
}
nameSet.add(name);
//创建一个Sheet表
XSSFSheet sheet = workbook.createSheet(name);
sheet.setDefaultRowHeightInPoints(20);
Row firstRow = sheet.createRow(0); // 下标为0的行开始
XSSFDrawing drawing = sheet.createDrawingPatriarch();
//----------------表头--------------------
if (flag) {
// 检查结果栏
org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(0);
String columnName = DataTable.CHECK_STATUS_NAME;
firstCell.setCellStyle(headCellStyle);
firstCell.setCellValue(new XSSFRichTextString(columnName));
sheet.setColumnWidth(0, (4 + 8) * 256);
}
// 数据栏
int hiddenNumber = 0;
for (int j = 0; j < table.getColumnIndex(); j++) {
Column column = table.getColumns()[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();
XSSFRichTextString textString;
if (column.isRequired()) {
textString = new XSSFRichTextString("*" + columnName);
textString.applyFont(0, 1, redFont);
textString.applyFont(1, textString.length(), normalFont);
} else {
textString = new XSSFRichTextString(columnName);
textString.applyFont(normalFont);
}
StringBuilder sb = new StringBuilder();
sb.append(column.getDescription()).append("\n");
if (column.getDataType() != DataType.STRING) {
// 如果数据类型不是字符串类型,添加特殊数据类型的说明信息。
Field[] fields = DataType.class.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(column.getDataType().name())) {
if (field.isAnnotationPresent(HeaderDescription.class)) {
// 获取声明字段上的Description信息。
HeaderDescription headerDescription = field.getAnnotation(HeaderDescription.class);
if (headerDescription.value() != null) {
sb.append(headerDescription.value());
}
}
}
}
}
// 如果填写了注释信息
if (sb.length() > 1) {
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6);
XSSFComment comment = drawing.createCellComment(anchor);
comment.setString(sb.toString());
firstCell.setCellComment(comment);
}
firstCell.setCellValue(textString);
firstCell.setCellStyle(headCellStyle);
sheet.setColumnWidth(k, (4 + column.getCellWidth()) * 256);
}
// 错误消息栏
if (flag) {
org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(table.getColumnIndex() + 1 - hiddenNumber);
String columnName = DataTable.CHECK_STATUS_RESULT;
firstCell.setCellStyle(headCellStyle);
firstCell.setCellValue(new XSSFRichTextString(columnName));
sheet.setColumnWidth(table.getColumnIndex() + 1, (4 + 10) * 256);
}
// 冻结第一行
//sheet.createFreezePane(255,1);
//------------------数据--------------------
for (int i = 0; i < table.getRowIndex(); 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 < table.getColumnIndex(); j++) {
Column column = table.getColumns()[j];
if (column.isHidden()) {
hiddenNumber++;
continue;
}
int k = j - hiddenNumber;
if (flag) {
k++;
}
org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(k);
Cell cell = table.getCell(i, j);
if (null == cell) {
continue;
}
String value = cell.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)) {
xssfCell.setCellStyle(errorNumberCellStyle);
} else {
xssfCell.setCellStyle(normalNumberCellStyle);
}
} else {
if (flag && !cell.getStatus().equals(Status.PASS)) {
xssfCell.setCellStyle(errorCellStyle);
} else {
xssfCell.setCellStyle(normalCellStyle);
}
}
}
if (flag && !rowFlag) {
org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(j + 1 - hiddenNumber);
xssfCell.setCellValue(table.getRowError(i));
xssfCell.setCellStyle(checkMessageCellStyle);
}
}
}
return workbook;
}
/**
* DataTableExcel
*
* @param table DataTable
* @param flag
* @return ExcelWorkbook
*/
@Deprecated
public XSSFWorkbook initExcel(DataTable table, boolean flag) {
return initExcel(flag, table);
}
/**
* Excel
*
* @return
* @throws IOException
*/
public byte[] getBytes() throws IOException {
if (workbook != null) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
return outputStream.toByteArray();
}
return null;
}
//------------ getter & setter --------------------
public Workbook getWorkbook() {
return workbook;
}
public void setWorkbook(XSSFWorkbook workbook) {
this.workbook = workbook;
}
}

@ -0,0 +1,17 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* target
* Created on 2014/9/26.
*
* @author
* @version v1.0.0.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Enum {
public Class target();
}

@ -0,0 +1,26 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* keyvalue<br/><br/>
*
* value<br/>
* <br/><br/>
* <p/>
*
* valuevaluekey<br/><br/>
* valueDataTable使valueKey<br/>
* <br/>
* 使<br/><br/>
* Created on 2014/9/28.
*
* @author
* @version 0.1.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EnumValue {
String[] value() default "";
}

@ -0,0 +1,39 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelCollection {
/**
*
*
* @return
*/
public String value();
/**
*
*
* @return
*/
public String orderNum() default "0";
/**
* arrayList
*/
public Class<?> type() default ArrayList.class;
}

@ -0,0 +1,94 @@
/**
* Copyright 2013-2015 JueYue (qrb.jueyue@gmail.com)
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wb.excel.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel
*
* @author JueYue
* @date 2014623 10:46:26
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelVerify {
/**
*
* @return
*/
public boolean interHandler() default false;
/**
*
*
* @return
*/
public boolean isEmail() default false;
/**
* 13
*
* @return
*/
public boolean isMobile() default false;
/**
*
*
* @return
*/
public boolean isTel() default false;
/**
*
*
* @return
*/
public int maxLength() default -1;
/**
*
*
* @return
*/
public int minLength() default -1;
/**
*
*
* @return
*/
public boolean notNull() default false;
/**
*
*
* @return
*/
public String regex() default "";
/**
* ,
*
* @return
*/
public String regexTip() default "数据不符合规范";
}

@ -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.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HeaderDescription {
String value() default "";
}

@ -0,0 +1,31 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* <br/>
* Created on 2014/9/24.
*
* @author
* @version v1.0.0.0
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HeaderName {
String value();
/**
*
*
* @return
*/
public String orderNum() default "0";
/**
*
*
* @return
*/
public String dateFormat() default "yyyy-MM-dd";
}

@ -0,0 +1,17 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* false(
* Created on 2014/9/24.
*
* @author
* @version v1.0.0.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IsDuplicated {
boolean value() default false;
}

@ -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.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoRepeat {
String value() default "";
}

@ -0,0 +1,16 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* Created on 2015/5/28.
*
* @author
* @since 2.1.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ParentFirst {
boolean value() default true;
}

@ -0,0 +1,28 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* Created on 2014/9/26.
*
* @author
* @version v1.0.0.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Split {
/**
*
*
* @return
*/
String reg() default "";
/**
* 0
*
* @return
*/
int index() default 0;
}

@ -0,0 +1,18 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* Created on 2014/9/26.
*
* @author
* @version v1.0.0.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Substring {
int start() default 0;
int end() default 0;
}

@ -0,0 +1,19 @@
package com.wb.excel.api.annotation;
import com.wb.excel.api.enumeration.DataType;
import java.lang.annotation.*;
/**
* Created on 2014/9/24.
*
* @author
* @version v1.0.0.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Type {
public DataType value() default DataType.STRING;
}

@ -0,0 +1,59 @@
package com.wb.excel.api.datatable;
import com.wb.excel.api.enumeration.Status;
import java.io.Serializable;
/**
* .
* Created on 2014/9/23.
*
* @author
* @since 0.1.0
*/
public class Cell implements Serializable {
/**
*
*/
private Status status;
/**
*
*/
private String value;
/**
* ..
*/
public Cell() {
this.status = Status.PASS;
this.value = "";
}
/**
* .
*
* @param value .
*/
public Cell(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() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

@ -0,0 +1,109 @@
package com.wb.excel.api.datatable;
import com.wb.excel.api.enumeration.DataType;
import com.wb.excel.api.util.StringUtil;
import java.io.Serializable;
/**
* DataTable<br/>
*
* Created by edward on 9/19/14.
*/
public class Column implements Serializable {
/**
*
*/
private String name;
/**
*
*/
private int cellWidth;
/**
* Excel
*/
private boolean isHidden;
/**
*
*/
private boolean isRequired;
/**
*
*/
private String description;
/**
*
*/
private DataType dataType;
public Column() {
this.name = "";
this.cellWidth = 1;
this.isHidden = false;
this.isRequired = false;
this.description = "";
this.dataType = DataType.STRING;
}
public Column(String name) {
this.name = name;
this.cellWidth = 1;
this.isHidden = false;
this.isRequired = false;
this.description = "";
this.dataType = DataType.STRING;
}
//----------- getter & setter --------------
public String getName() {
return name;
}
public void setName(String name) {
if (StringUtil.getByteLength(name) > cellWidth) {
cellWidth = StringUtil.getByteLength(name);
}
this.name = name;
}
public int getCellWidth() {
return cellWidth;
}
public void setCellWidth(int cellWidth) {
this.cellWidth = cellWidth;
}
public boolean isHidden() {
return isHidden;
}
public void setHidden(boolean isHidden) {
this.isHidden = isHidden;
}
public boolean isRequired() {
return isRequired;
}
public void setRequired(boolean isRequired) {
this.isRequired = isRequired;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public DataType getDataType() {
return dataType;
}
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
}

@ -0,0 +1,60 @@
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;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class DataExcel {
// static Logger LOGGER = Logger.getLogger(DataExcel.class);
/**
* @param file
* @param pojoClass
* @param <T>
* @return
*/
public static <T> ExcelImportResult<T> 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 <T> ExcelImportResult<T> importExcel(InputStream inputstream, Class<?> pojoClass, ImportParams importParams) throws Exception {
return new ExcelImport().importExcelByIs(inputstream, pojoClass, importParams);
}
}

@ -0,0 +1,14 @@
package com.wb.excel.api.datatable;
import java.io.Serializable;
import java.util.HashMap;
/**
* DataTable.
* Created on 2014/09/19.
*
* @author
* @since 0.1.0
*/
public class DataRow extends HashMap<String, Cell> implements Serializable {
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,601 @@
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.*;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class ExcelImport {
/**
* styler
*/
private CellStyle errorMessageStyle;
private boolean verfiyFail = false;
private VerifyDataUtil verifyDataUtil = new VerifyDataUtil();
private Map<Integer, DataVerifyResult> verifyResultMap = new HashMap<>();
private CellStyle errorcellStyle;
/**
* Excel
*
* @param inputstream
* @param pojoClass
* @return
*/
public ExcelImportResult importExcelByIs(InputStream inputstream, Class<?> pojoClass, ImportParams importParams) throws Exception {
List<T> result = new ArrayList<T>();
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 <T>
* @return
*/
private <T> Collection<? extends T> importExcel(List<T> result, Sheet sheet, Class<?> pojoClass, ImportParams importParams) throws Exception {
List collection = new ArrayList();
//Excel Field 对象
Map<String, ExcelImportEntity> excelParams = new HashMap<String, ExcelImportEntity>();
//Excel Line 对象
List<ExcelCollectionEntity> excelCollection = new ArrayList<ExcelCollectionEntity>();
if (!Map.class.equals(pojoClass)) {
//获取所有的参数信息
Field fields[] = ClassUtil.getClassFields(pojoClass);
getAllExcelField(fields, excelParams, excelCollection, pojoClass, null);
}
Iterator<Row> rows = sheet.rowIterator();
Map<Integer, String> 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<String, ExcelImportEntity> 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<Method> setMethods, Object object, Object value)
throws Exception {
Object t = getFieldBySomeMethod(setMethods, object);
setMethods.get(setMethods.size() - 1).invoke(t, value);
}
public Object getFieldBySomeMethod(List<Method> 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 20131126
*/
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<Integer, String> 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<String, ExcelImportEntity> excelParams, Map<Integer, String> 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<Integer, String> getTitleMap(Row row, Map<String, ExcelImportEntity> excelParams, List<ExcelCollectionEntity> excelCollection) throws Exception {
Map<Integer, String> titlemap = new HashMap<Integer, String>();
Iterator<Cell> 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<String> params = excelParams.keySet();
StringBuffer sb = new StringBuffer();
for (String key : params) {
if (!titlemap.containsValue(key)) {
sb.append(key).append(" ");
}
}
for (ExcelCollectionEntity entity : excelCollection) {
Set<String> 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<String, ExcelImportEntity> excelParams, List<ExcelCollectionEntity> excelCollection, Class<?> pojoClass, List<Method> 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<String, ExcelImportEntity> temp = new HashMap<String, ExcelImportEntity>();
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<Method> newMethods = new ArrayList<Method>();
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<Method> getMethods, Map<String, ExcelImportEntity> 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<Method> newMethods = new ArrayList<Method>();
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<String> keys = new HashSet<String>();
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<String, ExcelImportEntity> temp, List<Method> 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<Method> newMethods = new ArrayList<Method>();
if (getMethods != null) {
newMethods.addAll(getMethods);
}
newMethods.add(ClassUtil.getMethod(field.getName(), pojoClass, field.getType()));
getExcelFieldList(ClassUtil.getClassFields(field.getType()),
field.getType(), temp, newMethods);
}
}
}
}

@ -0,0 +1,62 @@
package com.wb.excel.api.datatable;
import com.wb.excel.api.interfaces.IExcelVerifyHandler;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
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;
}
}

@ -0,0 +1,51 @@
package com.wb.excel.api.entity;
import java.io.Serializable;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class DataVerifyResult implements Serializable {
/**
*
*/
private boolean success;
/**
*
*/
private String msg;
public DataVerifyResult() {
}
public DataVerifyResult(boolean issuccess) {
this.success = issuccess;
}
public DataVerifyResult(boolean success, String msg) {
this.success = success;
this.msg = msg;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

@ -0,0 +1,61 @@
package com.wb.excel.api.entity;
import java.util.Map;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:Excel
* ***************************************************************
* </pre>
*/
public class ExcelCollectionEntity {
/**
*
*/
private String name;
/**
* Excel
*/
private String excelName;
/**
*
*/
private Class<?> type;
private Map<String, ExcelImportEntity> excelParams;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExcelName() {
return excelName;
}
public void setExcelName(String excelName) {
this.excelName = excelName;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
public Map<String, ExcelImportEntity> getExcelParams() {
return excelParams;
}
public void setExcelParams(Map<String, ExcelImportEntity> excelParams) {
this.excelParams = excelParams;
}
}

@ -0,0 +1,124 @@
package com.wb.excel.api.entity;
import java.lang.reflect.Method;
import java.util.List;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class ExcelEntity {
/**
*
*/
protected String filedName;
/**
* name
*/
protected String showname;
/**
*
*/
protected Class Enum;
/**
*
*/
protected String split;
/**
*
*/
protected String description;
/**
*
*/
protected Boolean isDuplicated;
/**
*
*/
protected String dateFormat = "yyyy-MM-dd";
/**
* set/get
*/
private Method method;
private List<Method> methods;
public String getFiledName() {
return filedName;
}
public void setFiledName(String filedName) {
this.filedName = filedName;
}
public String getShowname() {
return showname;
}
public void setShowname(String showname) {
this.showname = showname;
}
public Class getEnum() {
return Enum;
}
public void setEnum(Class anEnum) {
Enum = anEnum;
}
public String getSplit() {
return split;
}
public void setSplit(String split) {
this.split = split;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getIsDuplicated() {
return isDuplicated;
}
public void setIsDuplicated(Boolean isDuplicated) {
this.isDuplicated = isDuplicated;
}
public List<Method> getMethods() {
return methods;
}
public void setMethods(List<Method> methods) {
this.methods = methods;
}
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
}

@ -0,0 +1,37 @@
package com.wb.excel.api.entity;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class ExcelImportEntity extends ExcelEntity {
/**
*
*/
private ExcelVerifyEntity verify;
/**
*
*/
// private String verifyFieldName ;
public ExcelVerifyEntity getVerify() {
return verify;
}
public void setVerify(ExcelVerifyEntity verify) {
this.verify = verify;
}
// public String getVerifyFieldName() {
// return verifyFieldName;
// }
//
// public void setVerifyFieldName(String verifyFieldName) {
// this.verifyFieldName = verifyFieldName;
// }
}

@ -0,0 +1,183 @@
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
* HeaderDescription:
* ***************************************************************
* </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()) ? true : false;
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,141 @@
package com.wb.excel.api.entity;
/**
* Excel
*/
public class ExcelVerifyEntity {
/**
*
*
* @return
*/
private boolean interHandler;
/**
*
*
* @return
*/
private boolean notNull;
/**
* 13
*
* @return
*/
private boolean isMobile;
/**
*
*
* @return
*/
private boolean isTel;
/**
*
*
* @return
*/
private boolean isEmail;
/**
*
*
* @return
*/
private int minLength;
/**
*
*
* @return
*/
private int maxLength;
/**
*
*
* @return
*/
private String regex;
/**
* ,
*
* @return
*/
private String regexTip;
public int getMaxLength() {
return maxLength;
}
public int getMinLength() {
return minLength;
}
public String getRegex() {
return regex;
}
public String getRegexTip() {
return regexTip;
}
public boolean isEmail() {
return isEmail;
}
public boolean isInterHandler() {
return interHandler;
}
public boolean isMobile() {
return isMobile;
}
public boolean isNotNull() {
return notNull;
}
public boolean isTel() {
return isTel;
}
public void setEmail(boolean isEmail) {
this.isEmail = isEmail;
}
public void setInterHandler(boolean interHandler) {
this.interHandler = interHandler;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public void setMobile(boolean isMobile) {
this.isMobile = isMobile;
}
public void setNotNull(boolean notNull) {
this.notNull = notNull;
}
public void setRegex(String regex) {
this.regex = regex;
}
public void setRegexTip(String regexTip) {
this.regexTip = regexTip;
}
public void setTel(boolean isTel) {
this.isTel = isTel;
}
}

@ -0,0 +1,119 @@
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.util.EnumUtil;
import com.wb.excel.api.util.StringUtil;
import com.wb.excel.api.util.ValidationUtil;
/**
* DataTable11<br/>
* DataTable
* Created on 2014/9/19/.
*
* @author
* @version v1.0.0.0
*/
public enum DataType {
@HeaderName("字符型")
@HeaderDescription("普通的字符串类型例如abc123.,!@#")
STRING,
@HeaderName("整数型")
@HeaderDescription("整数类型,小数点后的数字会被抹去(不是四舍五入),例如112004000")
NUMBER,
@HeaderName("数字类型")
@HeaderDescription("可以带小数点的数字类型例如1.001.01")
DECIMAL,
@HeaderName("网络地址型")
@HeaderDescription("网址,文件地址等。")
URL,
@HeaderName("邮箱型")
@HeaderDescription("邮箱地址例如test@xxx.com , test@xxx.com.cn")
EMAIL,
@HeaderName("手机号码型")
@HeaderDescription("手机号码。仅限用于大陆手机号中。如13300010002")
PHONE,
@HeaderName("日期型")
@HeaderDescription("普通的日期类型例如2014-10-01")
DATE,
@HeaderName("时间日期型(秒)")
@HeaderDescription("时间精确到秒的日期类型例如2014-10-01 10:30:00")
DATETIME,
@HeaderName("时间日期型(分钟)")
@HeaderDescription("时间精确到分钟的日期类型例如2014-10-01 10:30")
DATEMINUTE,
@HeaderName("是否型")
@HeaderDescription("指定是或者否的类型,例如:是,否")
BOOLEAN,
@HeaderName("大数型")
@HeaderDescription("用于较大的数字类型,会忽略小数点以后的内容")
LONG;
/**
* .
*
* @param type
* @param cell
* @param value
* @return truefalse
*/
public static boolean check(DataType type, Cell cell, 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));
}
break;
case DATE:
typeFlag = ValidationUtil.checkDate(value);
if (typeFlag) {
cell.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));
}
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));
}
break;
default:
break;
}
}
return typeFlag;
}
}

@ -0,0 +1,18 @@
package com.wb.excel.api.enumeration;
import com.wb.excel.api.annotation.EnumValue;
/**
* Created on 2014/9/26.
*
* @author
* @version 0.1.0
*/
public enum Gender {
@EnumValue({"男", "male", "m"})
M,
@EnumValue({"女", "female", "f"})
F,
@EnumValue({"未知", "其它", "其他", "u"})
U
}

@ -0,0 +1,50 @@
package com.wb.excel.api.enumeration;
/**
* Created on 2014/9/23.
*
* @author
* @version v1.0.0.0
*/
public enum Status {
/**
*
*/
EXIST,
/**
*
*/
NOTEXIST,
/**
*
*/
ERROR_VALUE,
/**
*
*/
PASS,
/**
*
*/
REPEAT,
/**
*
*/
FORMAT,
/**
*
*/
LENGTH,
/**
*
*/
EMPTY,
/**
*
*/
TOO_SMALL,
/**
*
*/
TOO_BIG
}

@ -0,0 +1,18 @@
package com.wb.excel.api.enumeration;
import com.wb.excel.api.annotation.EnumValue;
/**
* BooleanDataTableBoolean使<br/><br/>
* <b>使</b><br/><br/>
* Created on 2014/9/27.
*
* @author
* @version 0.1.0
*/
public enum YesNo {
@EnumValue({"是", "yes", "y", "true"})
Y,
@EnumValue({"否", "no", "n", "false"})
N
}

@ -0,0 +1,32 @@
package com.wb.excel.api.exception;
/**
* Created on 2014/10/12.
*
* @author
* @version 0.1.0
*/
public class ColumnNameNotExistException extends RuntimeException {
private static final long serialVersionUID = 234122996006212387L;
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public ColumnNameNotExistException() {
super();
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public ColumnNameNotExistException(String message) {
super(message);
}
}

@ -0,0 +1,52 @@
package com.wb.excel.api.exception;
import java.io.Serializable;
public class Error implements Serializable {
private static final long serialVersionUID = 3L;
private String code;
private ErrorType type;
private String message;
public Error() {
}
public Error(String code, String message) {
this.code = code;
this.message = message;
}
public Error(ErrorType type, String message) {
this.type = type;
this.code = type.toString();
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ErrorType getType() {
return type;
}
public void setType(ErrorType type) {
this.type = type;
}
}

@ -0,0 +1,38 @@
package com.wb.excel.api.exception;
/**
* Created on 2014/10/15.
*
* @author
* @version 0.1.0
*/
public class ErrorType {
/**
*
*/
public static String UNIQUENESS_ERROR = "UNIQUENESS_ERROR";
/**
*
*/
public static String EXPECTATION_NULL = "EXPECTATION_NULL";
/**
*
*/
public static String BUSINESS_ERROR = "BUSINESS_ERROR";
/**
* JDBC
*/
public static String SYSTEM_ERROR = "SYSTEM_ERROR";
/**
*
*/
public static String INVALID_PARAMETER = "INVALID_PARAMETER";
/**
*
*/
public static String OTHER = "OTHER";
/**
* Dump
*/
public static String STACK_DUMP = "STACK_DUMP";
}

@ -0,0 +1,32 @@
package com.wb.excel.api.exception;
/**
* Created on 2014/10/12.
*
* @author
* @version 0.1.0
*/
public class ExistedColumnNameException extends RuntimeException {
private static final long serialVersionUID = 234122996006212387L;
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public ExistedColumnNameException() {
super();
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public ExistedColumnNameException(String message) {
super(message);
}
}

@ -0,0 +1,32 @@
package com.wb.excel.api.exception;
/**
* Created on 2014/10/12.
*
* @author
* @version 0.1.0
*/
public class IllegalParameterException extends RuntimeException {
private static final long serialVersionUID = 234122996006212387L;
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public IllegalParameterException() {
super();
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public IllegalParameterException(String message) {
super(message);
}
}

@ -0,0 +1,29 @@
package com.wb.excel.api.exception;
/**
* Created on 2014/10/12.
*
* @author
* @version 0.1.0
*/
public class TemplateNotMatchException extends Exception {
/**
* Constructs a new exception with {@code null} as its detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*/
public TemplateNotMatchException() {
}
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public TemplateNotMatchException(String message) {
super(message);
}
}

@ -0,0 +1,38 @@
package com.wb.excel.api.interfaces;
/**
*
* Created on 2014/9/27.
*
* @author
* @version 0.1.0
*/
@Deprecated
public interface EnumSupport {
/**
* <br/>
*
*
* @param str
* @return true || false / ||
*/
public Boolean check(String str);
/**
* ValueKey<br/>
* MalemaleFF
*
* @param value
* @return Key
*/
public Object getKey(String value);
/**
* KeyValue<br/>
* F,
*
* @param key
* @return Value
*/
public String getValue(Object key);
}

@ -0,0 +1,34 @@
package com.wb.excel.api.interfaces;
import com.wb.excel.api.entity.DataVerifyResult;
/**
*
*/
public interface IExcelVerifyHandler {
// /**
// * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段
// *
// * @return
// */
// public String[] getNeedVerifyFields();
//
// /**
// * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段
// *
// * @return
// */
// public void setNeedVerifyFields(String[] arr);
/**
*
*
* @param obj
* @param name
* @param value
* @return
*/
public DataVerifyResult verifyHandler(Object obj, String name, Object value);
}

@ -0,0 +1,29 @@
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 BaseCellStyle {
/**
*
*/
protected CellStyle style;
public BaseCellStyle(Workbook workbook) {
style = workbook.createCellStyle();
}
public CellStyle getStyle() {
return style;
}
public void setStyle(CellStyle style) {
this.style = style;
}
}

@ -0,0 +1,29 @@
package com.wb.excel.api.style;
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 BaseFont {
/**
*
*/
protected Font font;
public BaseFont(Workbook workbook) {
font = workbook.createFont();
}
public Font getFont() {
return font;
}
public void setFont(Font font) {
this.font = font;
}
}

@ -0,0 +1,44 @@
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());
}
}

@ -0,0 +1,24 @@
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); //上下居中
}
}

@ -0,0 +1,40 @@
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());
}
}

@ -0,0 +1,39 @@
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());
}
}

@ -0,0 +1,17 @@
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);
}
}

@ -0,0 +1,39 @@
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 HeadCellStyle extends BaseCellStyle {
public HeadCellStyle(Workbook workbook) {
super(workbook);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); //背景颜色-灰色
style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置单元格填充样式
style.setAlignment(CellStyle.ALIGN_CENTER); // 居中
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());
}
}

@ -0,0 +1,28 @@
package com.wb.excel.api.style;
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 NormalCellStyle extends BaseCellStyle {
public NormalCellStyle(Workbook workbook) {
super(workbook);
style.setFillPattern(CellStyle.NO_FILL); //单元格不填充
//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()); //上边框颜色
}
}

@ -0,0 +1,18 @@
package com.wb.excel.api.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
/**
* .
* Created on 2015/1/29.
*
* @author
* @since 2.0.0
*/
public class NormalFont extends BaseFont {
public NormalFont(Workbook workbook) {
super(workbook);
font.setColor(HSSFColor.BLACK.index); //字体颜色-黑色
}
}

@ -0,0 +1,17 @@
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,18 @@
package com.wb.excel.api.style;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
/**
* .
* Created on 2015/1/29.
*
* @author
* @since 2.0.0
*/
public class RedFont extends BaseFont {
public RedFont(Workbook workbook) {
super(workbook);
font.setColor(HSSFColor.RED.index); //字体颜色-黑色
}
}

@ -0,0 +1,135 @@
package com.wb.excel.api.util;
import com.wb.excel.api.entity.DataVerifyResult;
import java.util.regex.Pattern;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class BaseVerifyUtil {
private static String NOT_NULL = "不允许为空";
private static String IS_MOBILE = "不是手机号";
private static String IS_TEL = "不是电话号码";
private static String IS_EMAIL = "不是邮箱地址";
private static String MIN_LENGHT = "小于规定长度";
private static String MAX_LENGHT = "超过规定长度";
private static Pattern mobilePattern = Pattern.compile("^[1][3,4,5,8,7][0-9]{9}$");
private static Pattern telPattern = Pattern.compile("^([0][1-9]{2,3}-)?[0-9]{5,10}$");
private static Pattern emailPattern = Pattern
.compile("^([a-zA-Z0-9]+[_|\\_|\\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\\_|\\.]?)*[a-zA-Z0-9]+\\.[a-zA-Z]{2,3}$");
/**
* email
*
* @param name
* @param val
* @return
*/
public static DataVerifyResult isEmail(String name, Object val) {
if (!emailPattern.matcher(String.valueOf(val)).matches()) {
return new DataVerifyResult(false, name + IS_EMAIL);
}
return new DataVerifyResult(true);
}
/**
*
*
* @param name
* @param val
* @return
*/
public static DataVerifyResult isMobile(String name, Object val) {
if (!mobilePattern.matcher(String.valueOf(val)).matches()) {
return new DataVerifyResult(false, name + IS_MOBILE);
}
return new DataVerifyResult(true);
}
/**
*
*
* @param name
* @param val
* @return
*/
public static DataVerifyResult isTel(String name, Object val) {
if (!telPattern.matcher(String.valueOf(val)).matches()) {
return new DataVerifyResult(false, name + IS_TEL);
}
return new DataVerifyResult(true);
}
/**
*
*
* @param name
* @param val
* @return
*/
public static DataVerifyResult maxLength(String name, Object val, int maxLength) {
if (notNull(name, val).isSuccess() && String.valueOf(val).length() > maxLength) {
return new DataVerifyResult(false, name + MAX_LENGHT);
}
return new DataVerifyResult(true);
}
/**
*
*
* @param name
* @param val
* @param minLength
* @return
*/
public static DataVerifyResult minLength(String name, Object val, int minLength) {
if (notNull(name, val).isSuccess() && String.valueOf(val).length() < minLength) {
return new DataVerifyResult(false, name + MIN_LENGHT);
}
return new DataVerifyResult(true);
}
/**
*
*
* @param name
* @param val
* @return
*/
public static DataVerifyResult notNull(String name, Object val) {
if (val == null || val.toString().equals("")) {
return new DataVerifyResult(false, name + NOT_NULL);
}
return new DataVerifyResult(true);
}
/**
*
*
* @param name
* @param val
* @param regex
* @param regexTip
* @return
*/
public static DataVerifyResult regex(String name, Object val, String regex,
String regexTip) {
Pattern pattern = Pattern.compile(regex);
if (!pattern.matcher(String.valueOf(val)).matches()) {
return new DataVerifyResult(false, name + regexTip);
}
return new DataVerifyResult(true);
}
}

@ -0,0 +1,195 @@
package com.wb.excel.api.util;
import com.wb.excel.api.annotation.ExcelCollection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* Created on 2015/5/28.
*
* @author
* @version 2.1.0
*/
public class ClassUtil {
public static Field[] getFields(Class clazz, boolean parentFirst) {
List<Field> returnList = new ArrayList<>();
Set<String> nameSet = new HashSet<>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
returnList.add(field);
nameSet.add(field.getName());
}
List<Field> parentList = getParentFields(clazz.getSuperclass(), nameSet, parentFirst);
if (parentFirst) {
parentList.addAll(returnList);
returnList = parentList;
} else {
returnList.addAll(parentList);
}
fields = new Field[returnList.size()];
int index = 0;
for (Field field : returnList) {
fields[index++] = field;
}
return fields;
}
/**
* class
*
* @param clazz
* @return
*/
public static Field[] getClassFields(Class<?> clazz) {
List<Field> list = new ArrayList<Field>();
Field[] fields;
do {
fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
list.add(fields[i]);
}
clazz = clazz.getSuperclass();
} while (clazz != Object.class && clazz != null);
return list.toArray(fields);
}
/**
*
*
* @param clazz
* @return
*/
public static boolean isCollection(Class<?> clazz) {
return Collection.class.isAssignableFrom(clazz);
}
/**
* GET
*
* @param name
* @param pojoClass
* @return
* @throws Exception
*/
public static Method getMethod(String name, Class<?> pojoClass) throws Exception {
StringBuffer getMethodName = new StringBuffer("get");
getMethodName.append(name.substring(0, 1).toUpperCase());
getMethodName.append(name.substring(1));
Method method = null;
try {
method = pojoClass.getMethod(getMethodName.toString(), new Class[]{});
} catch (Exception e) {
method = pojoClass.getMethod(
getMethodName.toString().replace("get", "is"),
new Class[]{});
}
return method;
}
/**
* SET
*
* @param name
* @param pojoClass
* @param type
* @return
* @throws Exception
*/
public static Method getMethod(String name, Class<?> pojoClass, Class<?> type) throws Exception {
StringBuffer getMethodName = new StringBuffer("set");
getMethodName.append(name.substring(0, 1).toUpperCase());
getMethodName.append(name.substring(1));
return pojoClass.getMethod(getMethodName.toString(), new Class[]{type});
}
/**
* java
*
* @param field
* @return
*/
public static boolean isJavaClass(Field field) {
Class<?> fieldType = field.getType();
boolean isBaseClass = false;
if (fieldType.isArray()) {
isBaseClass = false;
} else if (fieldType.isPrimitive() || fieldType.getPackage() == null
|| fieldType.getPackage().getName().equals("java.lang")
|| fieldType.getPackage().getName().equals("java.math")
|| fieldType.getPackage().getName().equals("java.sql")
|| fieldType.getPackage().getName().equals("java.util")) {
isBaseClass = true;
}
return isBaseClass;
}
/**
*
*
* @param clazz
* @return
*/
public static Field[] getFields(Class clazz) {
return getFields(clazz, false);
}
private static List<Field> getParentFields(Class parentClazz, Set<String> nameSet, boolean parentFirst) {
List<Field> fieldList = new ArrayList<>();
if (parentClazz != null) {
Field[] parentList = parentClazz.getDeclaredFields();
int index = 0;
for (Field field : parentList) {
int beginSize = nameSet.size();
nameSet.add(field.getName());
int endSize = nameSet.size();
if (endSize > beginSize) {
if (parentFirst) {
fieldList.add(index++, field);
} else {
fieldList.add(field);
}
}
}
fieldList.addAll(getParentFields(parentClazz.getSuperclass(), nameSet, parentFirst));
}
return fieldList;
}
public static Object createObject(Class<?> clazz) {
Object obj = null;
Method setMethod;
try {
if (clazz.equals(Map.class)) {
return new HashMap<String, Object>();
}
obj = clazz.newInstance();
Field[] fields = getClassFields(clazz);
for (Field field : fields) {
if (isCollection(field.getType())) {
ExcelCollection collection = field.getAnnotation(ExcelCollection.class);
setMethod = getMethod(field.getName(), clazz, field.getType());
setMethod.invoke(obj, collection.type().newInstance());
} else if (!isJavaClass(field)) {
setMethod = getMethod(field.getName(), clazz, field.getType());
setMethod.invoke(obj, createObject(field.getType()));
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("创建对象异常");
}
return obj;
}
}

@ -0,0 +1,46 @@
package com.wb.excel.api.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created on 2014/10/12.
*
* @author
* @version 0.1.0
*/
public class DataTableUtil {
/**
*
*
* @param url
* @return byte
* @throws java.io.IOException
*/
public static byte[] readFile(String url) throws IOException {
File file = new File(url);
InputStream is = new FileInputStream(file);
Long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("文件过大,无法读取");
}
byte[] bytes = new byte[length.intValue()];
int offset = 0;
int numRead;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
//如果得到的字节长度和file实际的长度不一致就可能出错了
if (offset < bytes.length) {
System.out.println("文件长度不一致");
}
is.close();
return bytes;
}
}

@ -0,0 +1,127 @@
package com.wb.excel.api.util;
import com.wb.excel.api.annotation.EnumValue;
import java.lang.reflect.Field;
/**
* Created on 2014/10/10.
*
* @author
* @version 0.1.0
*/
public class EnumUtil {
/**
*
*
* @param clazz
* @param value
* @return true || false / ||
*/
public static Boolean check(Class clazz, String value) {
if (clazz.isEnum() && value.length() > 0) {
value = value.toLowerCase();
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (!field.isAnnotationPresent(EnumValue.class)) {
continue;
}
EnumValue enumValue = field.getAnnotation(EnumValue.class);
String[] enumValues = enumValue.value();
for (String temp : enumValues) {
if (temp.equals(value)) {
return true;
}
}
}
return false;
}
return true;
}
/**
* valuekeykey
*
* @param clazz
* @param value
* @return
*/
public static String getKey(Class clazz, String value) {
if (clazz.isEnum()) {
value = value.toLowerCase();
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (!field.isAnnotationPresent(EnumValue.class)) {
continue;
}
EnumValue enumValue = field.getAnnotation(EnumValue.class);
String[] enumValues = enumValue.value();
for (String temp : enumValues) {
if (temp.equals(value)) {
return field.getName();
}
}
}
}
return "";
}
/**
* keyvaluevaluekey
*
* @param clazz
* @param key key
* @return value
*/
public static String getValue(Class clazz, String key) {
if (clazz.isEnum()) {
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (!field.isAnnotationPresent(EnumValue.class)) {
continue;
}
EnumValue enumValue = field.getAnnotation(EnumValue.class);
String[] enumValues = enumValue.value();
/* 如果找到了key */
if (field.getName().equals(key)) {
/* 如果没有注明枚举的内容,直接返回key */
if (enumValues.length == 1 && enumValues[0].equals("")) {
enumValues[0] = key;
}
/* 返回 */
return enumValues[0];
}
}
}
return "";
}
/**
*
*
* @param <T>
* @param clazz
* @param ordinal
* @return
*/
public static <T extends Enum<T>> T valueOf(Class<T> clazz, int ordinal) {
return clazz.getEnumConstants()[ordinal];
}
/**
* name
*
* @param <T>
* @param enumType
* @param name
* @return
*/
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) {
if (name != null && !"".equals(name)) {
return Enum.valueOf(enumType, name);
}
return null;
}
}

@ -0,0 +1,32 @@
package com.wb.excel.api.util;
import org.apache.poi.ss.usermodel.Cell;
/**
* Excel.
* Created on 2014/9/1.
*
* @author
* @since 0.1.0
*/
public class ExcelUtil {
/**
*
*
* @param cell
* @return
*/
public static String getValue(Cell cell) {
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型的值
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
// 返回数值类型的值
return String.valueOf(cell.getNumericCellValue());
} else {
// 返回字符串类型的值
return String.valueOf(cell.getStringCellValue());
}
}
}

@ -0,0 +1,206 @@
package com.wb.excel.api.util;
import com.wb.excel.api.enumeration.YesNo;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by DEV001 on 2014/9/1.
*/
public class StringUtil {
public static int getByteLength(String str) {
int length = str.replaceAll("[^\\x00-\\xff]", "**").length();
return length;
}
public static String upperFirstWord(String str) {
String temp = str.substring(0, 1);
return temp.toUpperCase() + str.substring(1);
}
/**
* TODO
*
* @param str
* @param reg
* @param index
* @return
*/
public static String split(String str, String reg, int index) {
if (reg.length() == 0) {
return str;
}
String[] strings = str.split(reg);
if (index < 0) {
index = 0;
}
if (index >= strings.length) {
index = strings.length - 1;
}
return strings[index];
}
public static String substring(String str, int start, int end) {
if (0 >= start || start >= str.length()) {
end = str.length() - 1;
}
if (0 >= end || end >= str.length()) {
end = str.length() - 1;
}
return str.substring(start, end);
}
public static String transferDate(String value) {
Double d = TransferUtil.transferDouble(value);
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (d == null) {
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
date = HSSFDateUtil.getJavaDate(d);
}
return sdf.format(date);
}
public static String transferDatetime(String value) {
Double d = TransferUtil.transferDouble(value);
Date date = null;
List<String> sdfList = new ArrayList<>();
sdfList.add("yyyy-MM-dd HH:mm:ss");
sdfList.add("yyyy-MM-dd hh:mm:ss");
sdfList.add("yyyy/MM/dd HH:mm:ss");
sdfList.add("yyyy/MM/dd hh:mm:ss");
SimpleDateFormat stdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (d == null) {
for (String sdfValue : sdfList) {
SimpleDateFormat sdf = new SimpleDateFormat(sdfValue);
try {
date = sdf.parse(value);
break;
} catch (ParseException ignored) {
}
}
} else {
date = HSSFDateUtil.getJavaDate(d);
}
return stdFormat.format(date);
}
public static String transferDateminute(String value) {
Double d = TransferUtil.transferDouble(value);
Date date = null;
List<String> sdfList = new ArrayList<>();
sdfList.add("yyyy-MM-dd HH:mm:ss");
sdfList.add("yyyy-MM-dd hh:mm:ss");
sdfList.add("yyyy/MM/dd HH:mm:ss");
sdfList.add("yyyy/MM/dd hh:mm:ss");
SimpleDateFormat stdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
if (d == null) {
for (String sdfValue : sdfList) {
SimpleDateFormat sdf = new SimpleDateFormat(sdfValue);
try {
date = sdf.parse(value);
break;
} catch (ParseException ignored) {
}
}
} else {
date = HSSFDateUtil.getJavaDate(d);
}
return stdFormat.format(date);
}
public static String transferInteger(String value) {
try {
Double d = Double.parseDouble(value);
int i = d.intValue();
if (d != i) {
return null;
} else {
return "" + i;
}
} catch (Exception e) {
return null;
}
}
public static String transferBoolean(String value) {
String key = EnumUtil.getKey(YesNo.class, value);
if (key.equals("Y")) {
return "是";
} else if (key.equals("N")) {
return "否";
}
return "";
}
public static String transferLong(String value) {
try {
Double d = Double.parseDouble(value);
long i = d.longValue();
if (d != i) {
return null;
} else {
return "" + i;
}
} catch (Exception e) {
return null;
}
}
/**
* ,sample@passionnetwork.com samp***********.com
*
* @param input
* @param startLength
* @param endLength
* @param isAbsolute
* @return
*/
public static String encryptString(String input, int startLength, int endLength, boolean isAbsolute) {
int length = input.length();
int endIndex = length - endLength;
if (startLength > length || endLength > length) {
return input;
}
String start = input.substring(0, startLength);
String end = input.substring(endIndex);
String out = start;
if (isAbsolute) {
for (int i = startLength; i < endIndex; i++) {
out += "*";
}
} else {
out += "****";
}
out += end;
return out;
}
public static String fixNumberLength(int number, int length) {
String fixedNumber = "" + String.valueOf(number);
while (fixedNumber.length() < length) {
fixedNumber = "0" + fixedNumber;
}
return fixedNumber;
}
}

@ -0,0 +1,146 @@
package com.wb.excel.api.util;
import org.apache.poi.hpsf.Constants;
/**
* ***************************************************************
* <p>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class StringUtils {
private StringUtils() {
}
/**
*
* <ul>
* <li>SysUtils.isEmpty(null) = true</li>
* <li>SysUtils.isEmpty("") = true</li>
* <li>SysUtils.isEmpty(" ") = true</li>
* <li>SysUtils.isEmpty("abc") = false</li>
* </ul>
*
* @param value
* @return true/false
*/
public static boolean isEmpty(String value) {
int strLen;
if(value == null || (strLen = value.length()) == 0) {
return true;
}
for(int i = 0; i < strLen; i++) {
if((Character.isWhitespace(value.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isNotEmpty(String value) {
int strLen;
if(value == null || (strLen = value.length()) == 0) {
return false;
}
for(int i = 0; i < strLen; i++) {
if((Character.isWhitespace(value.charAt(i)) == false)) {
return true;
}
}
return false;
}
/**
* ,
*/
public static boolean isNumeric(Object obj) {
if(obj == null) {
return false;
}
char[] chars = obj.toString().toCharArray();
int length = chars.length;
if(length < 1)
return false;
int i = 0;
if(length > 1 && chars[0] == '-')
i = 1;
for(; i < length; i++) {
if(!Character.isDigit(chars[i])) {
return false;
}
}
return true;
}
/**
*
*/
public static boolean areNotEmpty(String... values) {
boolean result = true;
if(values == null || values.length == 0) {
result = false;
} else {
for(String value : values) {
result &= !isEmpty(value);
}
}
return result;
}
/**
*
*/
public static String unicodeToChinese(String unicode) {
StringBuilder out = new StringBuilder();
if(!isEmpty(unicode)) {
for(int i = 0; i < unicode.length(); i++) {
out.append(unicode.charAt(i));
}
}
return out.toString();
}
public static String toUnderlineStyle(String name) {
StringBuilder newName = new StringBuilder();
for(int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if(Character.isUpperCase(c)) {
if(i > 0) {
newName.append("_");
}
newName.append(Character.toLowerCase(c));
} else {
newName.append(c);
}
}
return newName.toString();
}
//
// public static String convertString(byte[] data, int offset, int length) {
// if(data == null) {
// return null;
// } else {
// try {
// return new String(data, offset, length, Constants.CHARSET_UTF8);
// } catch(Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// public static byte[] convertBytes(String data) {
// if(data == null) {
// return null;
// } else {
// try {
// return data.getBytes(Constants.CHARSET_UTF8);
// } catch(Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
}

@ -0,0 +1,101 @@
package com.wb.excel.api.util;
import com.wb.excel.api.enumeration.YesNo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created on 2014/9/27.
*
* @author
* @version 0.1.0
*/
public class TransferUtil {
public static Date transferDate(String value) {
Date date = null;
try {
if (value.length() == 10) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.parse(value);
} else if (value.length() > 10) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = sdf.parse(value);
}
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static Date transferDatetime(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static Date transferDateminute(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = null;
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static Integer transferInteger(String value) {
try {
Double d = Double.parseDouble(value);
int i = d.intValue();
if (d != i) {
return null;
} else {
return i;
}
} catch (Exception e) {
return null;
}
}
public static Double transferDouble(String value) {
try {
return Double.parseDouble(value);
} catch (Exception e) {
return null;
}
}
public static Boolean transferBoolean(String value) {
String key = EnumUtil.getKey(YesNo.class, value);
if (key.equals("Y")) {
return true;
} else if (key.equals("N")) {
return false;
} else {
return null;
}
}
public static Long transferLong(String value) {
try {
Double d = Double.parseDouble(value);
long i = d.longValue();
if (d != i) {
return null;
} else {
return i;
}
} catch (Exception e) {
return null;
}
}
}

@ -0,0 +1,241 @@
package com.wb.excel.api.util;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* Created by DEV001 on 2014/8/1.
*/
public class ValidationUtil {
private static Validator validator;
/**
* ID
*
* @param id ID
* @return true, ID
*/
public static Boolean checkId(Long id) {
return !(null == id || id < 1);
}
public static Boolean checkDate(String value) {
try {
Double.valueOf(value);
} catch (Exception e) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
sdf.parse(value);
return true;
} catch (ParseException e1) {
e1.printStackTrace();
}
return false;
}
return true;
}
public static Boolean checkDatetime(String value) {
try {
Double.valueOf(value);
} catch (Exception e) {
List<String> sdfList = new ArrayList<>();
sdfList.add("yyyy-MM-dd HH:mm:ss");
sdfList.add("yyyy-MM-dd hh:mm:ss");
sdfList.add("yyyy/MM/dd HH:mm:ss");
sdfList.add("yyyy/MM/dd hh:mm:ss");
for (int i = 0; i < sdfList.size(); i++) {
String sdfValue = sdfList.get(i);
SimpleDateFormat sdf = new SimpleDateFormat(sdfValue);
try {
sdf.parse(value);
return true;
} catch (ParseException ignored) {
}
}
return false;
}
return true;
}
public static Boolean checkDouble(String value) {
try {
Double.parseDouble(value);
} catch (Exception e) {
return false;
}
return true;
}
/**
*
*
* @param value
* @return true || false
*/
public static Boolean checkInteger(String value) {
try {
Double d = Double.parseDouble(value);
int i = d.intValue();
return d == i;
} catch (Exception e) {
return false;
}
}
/**
*
*
* @param value
* @return true || false
*/
public static boolean checkLong(String value) {
try {
Double d = Double.parseDouble(value);
long l = d.longValue();
return d == l;
} catch (Exception e) {
return false;
}
}
/**
* ID
*
* @param ids ID
* @return true, ID
*/
public static Boolean checkIdList(List<Long> ids) {
return !(null == ids || ids.size() == 0);
}
/**
* truefalse<br/>
* <b></b>
*
* @param str
* @return true,false,
*/
public static Boolean checkString(String str) {
return !(null == str || 0 == str.trim().length());
}
/**
* <br><b></b>
*
* @param str
* @param minLength
* @param maxLength
* @return 250"aa"true"a"false
*/
public static Boolean checkStringLength(String str, int minLength, int maxLength) {
if (null == str) {
return false;
} else {
if (str.length() >= minLength && str.length() <= maxLength) {
return true;
}
}
return false;
}
/**
* <br/>
*
* @param email
* @return true, false<br/>
* <br/>
* 0123-abcd_ABCD@0123-abcd_ABCD.00aaBB--__.cc <b>true</b><br/>
* a@a.a <b>true</b><br/>
* tony@sina@qq.com <b>false</b>
*/
public static Boolean checkEmail(String email) {
//验证邮箱地址的正则表达式
Pattern p;
p = Pattern.compile(
"^([a-zA-Z0-9]+[_|_|-|-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|-|-|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,3}$");
Matcher m = p.matcher(email);
return m.matches();
}
/**
* <br/>
*
* @param filePath
* @return true, false<br/>
* <br/>
* C:\b.txt <b>true</b><br/>
* C:\abc\a.txt <b>true</b><br/>
* C:\windows\sys<\mfc.dll <b>false</b>
*/
public static Boolean checkFilePath(String filePath) {
//验证文件路径格式的正则表达式
Pattern p = Pattern.compile("^(?<path>(?:[a-zA-Z]:)?\\\\(?:[^\\\\\\?\\/\\*\\|<>:\"]+\\\\)+)(?<filename>(?<name>[^\\\\\\?\\/\\*\\|<>:\"]+?)\\.(?<ext>[^.\\\\\\?\\/\\*\\|<>:\"]+))$");
Matcher m = p.matcher(filePath);
return m.matches();
}
/**
*
*
* @param phone
* @return true, false<br>
* <br>
* 13345661234 <b>true</b> <br>
* 16812341234 <b>false</b> <br>
* 0512-123456 <b>false</b> <br>
* 0512-2345678 <b>true</b> <br>
* 12345678 <b>false</b> <br>
* 22345678 <b>true</b>
*/
public static Boolean checkPhone(String phone) {
List<Pattern> list = new LinkedList<>();
list.add(Pattern.compile("^[1][3,4,5,8][0-9]{9}$")); //验证手机号
list.add(Pattern.compile("^[0][1-9]{1,2}[0-9]-[2-9][0-9]{6,7}$")); //验证带区号固定电话,区号后加“-”
list.add(Pattern.compile("^[2-9][0-9]{6,7}$")); //验证不带区号的固定电话
list.add(Pattern.compile("([0][1-9]{1,2}[0-9])[2-9][0-9]{6,7}$"));
Matcher matcher;
Boolean result = false;
for (Pattern pattern : list) {
matcher = pattern.matcher(phone); //遍历匹配
result |= matcher.matches(); //对所有的匹配结果做或运算。
}
return result;
}
/**
* URL
*
* @param url
* @return
*/
public static Boolean checkUrl(String url) {
List<Pattern> list = new LinkedList<>();
list.add(Pattern.compile("^(http|www|ftp|)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)(/(\\w+(-\\w+)*))*(\\.?(\\w)*)(\\?)?(((\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*)*(\\w*)*)$"));
Matcher matcher;
Boolean result = false;
for (Pattern pattern : list) {
matcher = pattern.matcher(url); //遍历匹配
result |= matcher.matches(); //对所有的匹配结果做或运算。
}
return result;
}
}

@ -0,0 +1,64 @@
package com.wb.excel.api.util;
import com.wb.excel.api.entity.DataVerifyResult;
import com.wb.excel.api.entity.ExcelVerifyEntity;
import com.wb.excel.api.interfaces.IExcelVerifyHandler;
/**
* ***************************************************************
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ***************************************************************
* </pre>
*/
public class VerifyDataUtil {
private final static DataVerifyResult DEFAULT_RESULT = new DataVerifyResult(
true);
private void addVerifyResult(DataVerifyResult hanlderResult,
DataVerifyResult result) {
if (!hanlderResult.isSuccess()) {
result.setSuccess(false);
result.setMsg((StringUtils.isEmpty(result.getMsg()) ? "" : result.getMsg() + " , ")
+ hanlderResult.getMsg());
}
}
public DataVerifyResult verifyData(Object object, Object value, String name, String showName,
ExcelVerifyEntity verify, IExcelVerifyHandler excelVerifyHandler) {
if (verify == null) {
return DEFAULT_RESULT;
}
DataVerifyResult result = new DataVerifyResult(true, "");
if (verify.isNotNull()) {
addVerifyResult(BaseVerifyUtil.notNull(showName, value), result);
}
if (verify.isEmail()) {
addVerifyResult(BaseVerifyUtil.isEmail(showName, value), result);
}
if (verify.isMobile()) {
addVerifyResult(BaseVerifyUtil.isMobile(showName, value), result);
}
if (verify.isTel()) {
addVerifyResult(BaseVerifyUtil.isTel(showName, value), result);
}
if (verify.getMaxLength() != -1) {
addVerifyResult(BaseVerifyUtil.maxLength(showName, value, verify.getMaxLength()), result);
}
if (verify.getMinLength() != -1) {
addVerifyResult(BaseVerifyUtil.minLength(showName, value, verify.getMinLength()), result);
}
if (StringUtils.isNotEmpty(verify.getRegex())) {
addVerifyResult(
BaseVerifyUtil.regex(showName, value, verify.getRegex(), verify.getRegexTip()),
result);
}
if (verify.isInterHandler()) {
addVerifyResult(excelVerifyHandler.verifyHandler(object, name, value), result);
}
return result;
}
}

@ -0,0 +1,109 @@
import com.wb.excel.api.Excel;
import com.wb.excel.api.datatable.DataTable;
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.List;
/**
*
*/
public class ExampleTest {
public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
testExport();
testImport();
}
public static void testExport() {
try {
//第一步,准备数据模型及数据,模型需要打上注解
List<User> pos = new ArrayList();
User user = new User("张三", "zs123", "123123");
user.setSex(YesNo.Y);
pos.add(user);
pos.add(user);
//第二步,初始化数据
DataTable dataTable = new DataTable(pos);
//第三步,初始化Excel
Excel excel = new Excel(dataTable);
//第四步导出xlsx文件
output("user.xlsx", excel.getBytes());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public static void testImport() {
try {
File file = new File("user.xlsx");
FileInputStream stream = new FileInputStream(file);
byte[] bytes = new byte[stream.available()];
stream.read(bytes);
DataTable dataTable = new DataTable(bytes, User.class);
if (dataTable.hasError()) {
Excel excel = new Excel(true, dataTable);
output("user_err.xlsx", excel.getBytes());
} else {
List<User> list = dataTable.transferList(User.class);
System.out.println("本次读取数据" + list.size() + "条!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (TemplateNotMatchException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public static void output(String path, byte[] bytes) {
try {
File file = new File(path);
file.createNewFile();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes);
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,55 @@
import com.wb.excel.api.annotation.Enum;
import com.wb.excel.api.annotation.EnumValue;
import com.wb.excel.api.enumeration.YesNo;
public class User {
private String name;
private String password;
private String qq;
@Enum(target = YesNo.class)
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;
}
public void setSex(YesNo sex) {
this.sex = sex;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Loading…
Cancel
Save

Powered by TurnKey Linux.