master
wangbing 5 years ago
parent d011846d84
commit 74bae8de71

@ -1,9 +1,9 @@
package com.wb.excel.api;
import com.wb.excel.api.annotation.HeaderDescription;
import com.wb.excel.api.datatable.Cell;
import com.wb.excel.api.datatable.Column;
import com.wb.excel.api.datatable.DataTable;
import com.wb.excel.api.annotation.ColumnDescription;
import com.wb.excel.api.datatable.WCell;
import com.wb.excel.api.datatable.WColumn;
import com.wb.excel.api.datatable.WSheet;
import com.wb.excel.api.enumeration.DataType;
import com.wb.excel.api.enumeration.Status;
import com.wb.excel.api.style.*;
@ -27,7 +27,7 @@ import java.util.Set;
* @author
* @since 0.1.0
*/
public class Excel {
public class WExcel {
/**
* Excel
*/
@ -107,46 +107,35 @@ public class Excel {
/**
* .
*/
public Excel() {
public WExcel() {
init();
}
/**
* DataTableExcel,.<br/>
* .
* {@link Excel#Excel(boolean flag, DataTable... dataTable)}
* {@link WExcel#WExcel(boolean flag, WSheet... dataTable)}
*
* @param tables DataTable
*/
public Excel(DataTable... tables) {
public WExcel(WSheet... tables) {
workbook = this.initExcel(false, tables);
}
/**
* 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) {
public WExcel(boolean flag, WSheet... tables) {
workbook = this.initExcel(flag, tables);
}
public XSSFWorkbook initExcel(boolean flag, DataTable... tables) {
public XSSFWorkbook initExcel(boolean flag, WSheet... tables) {
init();
Set<String> nameSet = new HashSet<>(tables.length);
for (DataTable table : tables) {
for (WSheet table : tables) {
String name = table.getName();
int index = 1;
while (nameSet.contains(name)) {
@ -165,7 +154,7 @@ public class Excel {
if (flag) {
// 检查结果栏
org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(0);
String columnName = DataTable.CHECK_STATUS_NAME;
String columnName = WSheet.CHECK_STATUS_NAME;
firstCell.setCellStyle(headCellStyle);
firstCell.setCellValue(new XSSFRichTextString(columnName));
sheet.setColumnWidth(0, (4 + 8) * 256);
@ -173,8 +162,8 @@ public class Excel {
// 数据栏
int hiddenNumber = 0;
for (int j = 0; j < table.getColumnIndex(); j++) {
Column column = table.getColumns()[j];
if (column.isHidden()) {
WColumn WColumn = table.getWColumns()[j];
if (WColumn.isHidden()) {
hiddenNumber++;
continue;
}
@ -183,9 +172,9 @@ public class Excel {
k++;
}
org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(k);
String columnName = column.getName();
String columnName = WColumn.getName();
XSSFRichTextString textString;
if (column.isRequired()) {
if (WColumn.isRequired()) {
textString = new XSSFRichTextString("*" + columnName);
textString.applyFont(0, 1, redFont);
textString.applyFont(1, textString.length(), normalFont);
@ -194,18 +183,18 @@ public class Excel {
textString.applyFont(normalFont);
}
StringBuilder sb = new StringBuilder();
sb.append(column.getDescription()).append("\n");
if (column.getDataType() != DataType.STRING) {
sb.append(WColumn.getDescription()).append("\n");
if (WColumn.getDataType() != DataType.STRING) {
// 如果数据类型不是字符串类型,添加特殊数据类型的说明信息。
Field[] fields = DataType.class.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(column.getDataType().name())) {
if (field.isAnnotationPresent(HeaderDescription.class)) {
if (field.getName().equals(WColumn.getDataType().name())) {
if (field.isAnnotationPresent(ColumnDescription.class)) {
// 获取声明字段上的Description信息。
HeaderDescription headerDescription = field.getAnnotation(HeaderDescription.class);
if (headerDescription.value() != null) {
sb.append(headerDescription.value());
ColumnDescription columnDescription = field.getAnnotation(ColumnDescription.class);
if (columnDescription.value() != null) {
sb.append(columnDescription.value());
}
}
}
@ -221,13 +210,13 @@ public class Excel {
}
firstCell.setCellValue(textString);
firstCell.setCellStyle(headCellStyle);
sheet.setColumnWidth(k, (4 + column.getCellWidth()) * 256);
sheet.setColumnWidth(k, (4 + WColumn.getCellWidth()) * 256);
}
// 错误消息栏
if (flag) {
org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(table.getColumnIndex() + 1 - hiddenNumber);
String columnName = DataTable.CHECK_STATUS_RESULT;
String columnName = WSheet.CHECK_STATUS_RESULT;
firstCell.setCellStyle(headCellStyle);
firstCell.setCellValue(new XSSFRichTextString(columnName));
sheet.setColumnWidth(table.getColumnIndex() + 1, (4 + 10) * 256);
@ -257,8 +246,8 @@ public class Excel {
int j = 0;
hiddenNumber = 0;
for (; j < table.getColumnIndex(); j++) {
Column column = table.getColumns()[j];
if (column.isHidden()) {
WColumn WColumn = table.getWColumns()[j];
if (WColumn.isHidden()) {
hiddenNumber++;
continue;
}
@ -268,24 +257,23 @@ public class Excel {
}
org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(k);
Cell cell = table.getCell(i, j);
if (null == cell) {
WCell WCell = table.getCell(i, j);
if (null == WCell) {
continue;
}
String value = cell.getValue();
String value = WCell.getValue();
xssfCell.setCellValue(value);
// 如果该列是数字类型,则靠右
if (table.getColumns()[j].getDataType() == DataType.DECIMAL
|| table.getColumns()[j].getDataType() == DataType.NUMBER
|| table.getColumns()[j].getDataType() == DataType.LONG) {
if (flag && !cell.getStatus().equals(Status.PASS)) {
if (table.getWColumns()[j].getDataType() == DataType.DECIMAL
|| table.getWColumns()[j].getDataType() == DataType.NUMBER) {
if (flag && !WCell.getStatus().equals(Status.PASS)) {
xssfCell.setCellStyle(errorNumberCellStyle);
} else {
xssfCell.setCellStyle(normalNumberCellStyle);
}
} else {
if (flag && !cell.getStatus().equals(Status.PASS)) {
if (flag && !WCell.getStatus().equals(Status.PASS)) {
xssfCell.setCellStyle(errorCellStyle);
} else {
xssfCell.setCellStyle(normalCellStyle);
@ -303,18 +291,6 @@ public class Excel {
return workbook;
}
/**
* DataTableExcel
*
* @param table DataTable
* @param flag
* @return ExcelWorkbook
*/
@Deprecated
public XSSFWorkbook initExcel(DataTable table, boolean flag) {
return initExcel(flag, table);
}
/**
* Excel
*

@ -11,7 +11,7 @@ import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HeaderDescription {
public @interface ColumnDescription {
String value() default "";
}

@ -12,7 +12,7 @@ import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HeaderName {
public @interface ColumnName {
String value();
/**

@ -14,6 +14,6 @@ import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Type {
public @interface ColumnType {
public DataType value() default DataType.STRING;
}

@ -11,7 +11,7 @@ import java.util.ArrayList;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -21,7 +21,7 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel
* WExcel
*
* @author JueYue
* @date 2014623 10:46:26

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

@ -3,7 +3,7 @@ package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* Created on 2015/5/28.
*
*
* @author
* @since 2.1.0

@ -0,0 +1,17 @@
package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* <br/>
* Created on 2014/9/24.
*
* @author
* @version v1.0.0.0
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SheetName {
String value();
}

@ -1,60 +0,0 @@
package com.wb.excel.api.datatable;
import com.wb.excel.api.entity.ExcelImportResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* ***************************************************************
* <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);
}
}

@ -1,601 +0,0 @@
package com.wb.excel.api.datatable;
import com.wb.excel.api.annotation.HeaderDescription;
import com.wb.excel.api.annotation.ExcelCollection;
import com.wb.excel.api.annotation.ExcelVerify;
import com.wb.excel.api.annotation.IsDuplicated;
import com.wb.excel.api.entity.*;
import com.wb.excel.api.style.ErrorCellStyle;
import com.wb.excel.api.util.ClassUtil;
import com.wb.excel.api.util.EnumUtil;
import com.wb.excel.api.util.StringUtils;
import com.wb.excel.api.util.VerifyDataUtil;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.wb.excel.api.annotation.HeaderName;
import com.wb.excel.api.annotation.Enum;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* ***************************************************************
* <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);
}
}
}
}

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

@ -12,7 +12,7 @@ import java.io.Serializable;
* @author
* @since 0.1.0
*/
public class Cell implements Serializable {
public class WCell implements Serializable {
/**
*
*/
@ -26,7 +26,7 @@ public class Cell implements Serializable {
/**
* ..
*/
public Cell() {
public WCell() {
this.status = Status.PASS;
this.value = "";
}
@ -36,7 +36,7 @@ public class Cell implements Serializable {
*
* @param value .
*/
public Cell(String value) {
public WCell(String value) {
this.value = value;
this.status = Status.PASS;
}

@ -5,13 +5,14 @@ import com.wb.excel.api.enumeration.DataType;
import com.wb.excel.api.util.StringUtil;
import java.io.Serializable;
import java.lang.reflect.Field;
/**
* DataTable<br/>
*
* Created by edward on 9/19/14.
*/
public class Column implements Serializable {
public class WColumn implements Serializable {
/**
*
*/
@ -37,7 +38,9 @@ public class Column implements Serializable {
*/
private DataType dataType;
public Column() {
private Field field;
public WColumn() {
this.name = "";
this.cellWidth = 1;
this.isHidden = false;
@ -46,7 +49,7 @@ public class Column implements Serializable {
this.dataType = DataType.STRING;
}
public Column(String name) {
public WColumn(String name) {
this.name = name;
this.cellWidth = 1;
this.isHidden = false;
@ -67,6 +70,14 @@ public class Column implements Serializable {
this.name = name;
}
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
public int getCellWidth() {
return cellWidth;
}

@ -10,5 +10,5 @@ import java.util.HashMap;
* @author
* @since 0.1.0
*/
public class DataRow extends HashMap<String, Cell> implements Serializable {
public class WRow extends HashMap<String, WCell> implements Serializable {
}

@ -26,6 +26,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
/**
* <br/>
@ -34,7 +35,7 @@ import java.util.*;
* @author
* @since 0.1.0
*/
public class DataTable<T> implements Serializable, Cloneable {
public class WSheet<T> implements Serializable, Cloneable {
public final static String CHECK_STATUS_NAME = "检查状态";
public final static String CHECK_STATUS_RESULT = "结果消息";
@ -57,7 +58,7 @@ public class DataTable<T> implements Serializable, Cloneable {
/**
*
*/
private Column[] columns;
private WColumn[] WColumns;
/**
*
@ -68,7 +69,7 @@ public class DataTable<T> implements Serializable, Cloneable {
/**
*
*/
private Cell[][] data;
private WCell[][] data;
/**
* Table
@ -87,8 +88,8 @@ public class DataTable<T> implements Serializable, Cloneable {
rowIndex = 0;
columnIndex = 0;
columns = new Column[MAX_COLUMN_NUMBER];
data = new Cell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER];
WColumns = new WColumn[MAX_COLUMN_NUMBER];
data = new WCell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER];
errorList = new ArrayList<>();
errorLists = new ArrayList<>(MAX_ROW_NUMBER);
@ -100,7 +101,7 @@ public class DataTable<T> implements Serializable, Cloneable {
/**
*
*/
public DataTable() {
public WSheet() {
init();
}
@ -109,9 +110,9 @@ public class DataTable<T> implements Serializable, Cloneable {
*
* @param clazz
*/
public DataTable(Class<T> clazz) {
public WSheet(Class<T> clazz) {
init();
setColumns(clazz);
initColumns(clazz);
}
/**
@ -120,45 +121,53 @@ public class DataTable<T> implements Serializable, Cloneable {
* @param clazz
* @return @NameSet
*/
private Set<Field> setColumns(Class<?> clazz) {
HeaderName tempHeaderName = clazz.getAnnotation(HeaderName.class);
ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class);
boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value();
if (tempHeaderName != null) {
this.setName(tempHeaderName.value());
private WColumn[] initColumns(Class<?> clazz) {
//获取工作簿名称,没有则以类名为默认工作簿名称
SheetName sheetName = clazz.getAnnotation(SheetName.class);
if (sheetName != null) {
this.setName(sheetName.value());
} else {
this.setName(clazz.getName());
}
//Field [] fields = clazz.getDeclaredFields();
//是否关注父类属性
boolean parentFirst = clazz.isAnnotationPresent(ParentFirst.class) && clazz.getAnnotation(ParentFirst.class).value();
Field[] fields = ClassUtil.getFields(clazz, parentFirst);
Set<Field> set = new HashSet<>();
for (Field field : fields) {
set.add(field);
Column column = null;
if (!field.isAnnotationPresent(HeaderName.class)) {
String name = field.getName();
column = new Column(name);
WColumn WColumn = new WColumn();
WColumn.setField(field);
if (field.isAnnotationPresent(Ignore.class) && field.getAnnotation(Ignore.class).value()) {
WColumn.setHidden(true);
}
//获取列名称
if (!field.isAnnotationPresent(ColumnName.class)) {
WColumn.setName(field.getName());
} else {
HeaderName columnHeaderName = field.getAnnotation(HeaderName.class);
column = new Column(columnHeaderName.value());
ColumnName columnColumnName = field.getAnnotation(ColumnName.class);
WColumn.setName(columnColumnName.value());
}
//获取列填写说明或描述
if (field.isAnnotationPresent(ColumnDescription.class)) {
WColumn.setDescription(field.getAnnotation(ColumnDescription.class).value());
}
//列填写标志(是否必填)
if (field.isAnnotationPresent(NotNull.class)) {
column.setRequired(true);
WColumn.setRequired(true);
}
if (field.isAnnotationPresent(Type.class)) {
Type type = field.getAnnotation(Type.class);
column.setDataType(type.value());
//获取列类型
if (field.isAnnotationPresent(ColumnType.class)) {
ColumnType columnType = field.getAnnotation(ColumnType.class);
WColumn.setDataType(columnType.value());
} else {
column.setDataType(DataType.STRING);
WColumn.setDataType(DataType.STRING);
}
if (field.isAnnotationPresent(HeaderDescription.class)) {
column.setDescription(field.getAnnotation(HeaderDescription.class).value());
}
this.addColumn(column);
this.addColumn(WColumn);
}
return set;
return this.WColumns;
}
/**
@ -170,75 +179,45 @@ public class DataTable<T> implements Serializable, Cloneable {
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public DataTable(List<T> list)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
public WSheet(List<T> list) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
init();
if (list == null || list.size() == 0) {
throw new IllegalParameterException("不允许传入空的列表");
}
if (list.size() > 0) {
T tClass = list.get(0);
Set<Field> set = setColumns(tClass.getClass());
WColumn[] WColumns = initColumns(tClass.getClass());
for (T t : list) {
DataRow row = new DataRow();
for (Field field : set) {
// 获取字段上的名称注解(作为列名使用)
String HeaderName = "";
HeaderName fieldHeaderName = field.getAnnotation(HeaderName.class);
if (fieldHeaderName == null) {
HeaderName = field.getName();
} else {
HeaderName = fieldHeaderName.value();
WRow row = new WRow();
for (WColumn WColumn : WColumns) {
if (WColumn == null) {
continue;
}
Field field = WColumn.getField();
String att = StringUtil.upperFirstWord(field.getName());
Method method = t.getClass().getMethod("get" + att);
Object value = method.invoke(t);
if (null == value) {
row.put(fieldHeaderName.value(), new Cell());
row.put(WColumn.getName(), new WCell());
} else {
if (field.isAnnotationPresent(Type.class)) {
Type type = field.getAnnotation(Type.class);
switch (type.value()) {
case DATE: {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
value = sdf.format(date);
break;
}
case DATETIME: {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
value = sdf.format(date);
break;
}
case DATEMINUTE: {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
value = sdf.format(date);
break;
}
case NUMBER:
value = StringUtil.transferInteger(value.toString());
break;
case LONG:
value = StringUtil.transferLong(value.toString());
break;
case BOOLEAN:
value = StringUtil.transferBoolean(value.toString());
break;
default:
break;
}
}
// 如果该变量包含枚举标签,处理枚举
if (field.isAnnotationPresent(Enum.class)) {
if (field.getType() == Date.class) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
value = sdf.format(date);
} else if (field.getType() == java.sql.Date.class) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
value = sdf.format(date);
} else if (field.getType() == Boolean.class) {
value = StringUtil.transferBoolean(value.toString());
} else if (field.getType() == Boolean.class) {
value = StringUtil.transferBoolean(value.toString());
} else if (field.isAnnotationPresent(Enum.class)) {
Enum e = field.getAnnotation(Enum.class);
value = EnumUtil.getValue(e.target(), value.toString());
}
row.put(HeaderName, new Cell(value.toString()));
row.put(WColumn.getName(), new WCell(value.toString()));
}
}
this.addRow(row);
@ -254,7 +233,7 @@ public class DataTable<T> implements Serializable, Cloneable {
* 1.Workbook
*/
@Deprecated
public DataTable(byte[] bytes) throws IOException, TemplateNotMatchException {
public WSheet(byte[] bytes) throws IOException, TemplateNotMatchException {
init();
InputStream inputStream = null; //文件输入流
Workbook workbook = null; //导入的文档
@ -291,21 +270,21 @@ public class DataTable<T> implements Serializable, Cloneable {
int columnNum = headRow.getPhysicalNumberOfCells();
for (int i = 0; i < columnNum; i++) {
org.apache.poi.ss.usermodel.Cell cell = headRow.getCell(i);
Column column = new Column();
column.setName(ExcelUtil.getValue(cell));
this.addColumn(column);
WColumn WColumn = new WColumn();
WColumn.setName(ExcelUtil.getValue(cell));
this.addColumn(WColumn);
}
/* 逐行读取导入文件的数据从1开始是因为第0行为表头 */
int rowNumber = sheet.getLastRowNum();
for (int i = 1; i <= rowNumber; i++) {
Row inputRow = sheet.getRow(i);
DataRow row = new DataRow();
WRow row = new WRow();
if (null != inputRow) {
for (int j = 0; j < columnNum; j++) {
org.apache.poi.ss.usermodel.Cell excelCell = inputRow.getCell(j);
if (null != excelCell) {
row.put(this.getColumns()[j].getName(), new Cell(ExcelUtil.getValue(excelCell)));
row.put(this.getWColumns()[j].getName(), new WCell(ExcelUtil.getValue(excelCell)));
}
}
}
@ -324,7 +303,7 @@ public class DataTable<T> implements Serializable, Cloneable {
* @throws TemplateNotMatchException <br/>1:Excel - Excel<br/>
* 2: - <br/>
*/
public DataTable(byte[] bytes, Class<T> clazz) throws IOException, TemplateNotMatchException {
public WSheet(byte[] bytes, Class<T> clazz) throws IOException, TemplateNotMatchException {
init();
Workbook workbook = null;
InputStream is = null;
@ -356,11 +335,11 @@ public class DataTable<T> implements Serializable, Cloneable {
String tableName = sheet.getSheetName(); //DataTable的名字
/* 获取指定类所有带有Name注解的属性集合 */
HeaderName classHeaderName = clazz.getAnnotation(HeaderName.class); //该类所声明的名字
ColumnName classColumnName = clazz.getAnnotation(ColumnName.class); //该类所声明的名字
ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class);
boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value();
if (classHeaderName != null) {
tableName = classHeaderName.value();
if (classColumnName != null) {
tableName = classColumnName.value();
}
this.setName(tableName); //将类名设为表名如果类名不存在将Excel表名设为表名
@ -368,7 +347,7 @@ public class DataTable<T> implements Serializable, Cloneable {
Field[] fields = ClassUtil.getFields(clazz, parentFirst); //该类所声明的全部属性
Set<Field> set = new HashSet<>(); //用于保存所有带有Name注解的属性
for (Field field : fields) {
if (field.isAnnotationPresent(HeaderName.class)) {
if (field.isAnnotationPresent(ColumnName.class)) {
set.add(field);
}
}
@ -380,7 +359,7 @@ public class DataTable<T> implements Serializable, Cloneable {
/* 为Excel表中的每一列分配空间 */
List<Set<String>> sets = new ArrayList<>();
Type[] types = new Type[columnSum];
ColumnType[] columnTypes = new ColumnType[columnSum];
Enum[] enums = new Enum[columnSum];
Split[] splits = new Split[columnSum];
Length[] lengths = new Length[columnSum];
@ -388,7 +367,7 @@ public class DataTable<T> implements Serializable, Cloneable {
Substring[] substrings = new Substring[columnSum];
DecimalMin[] decimalMins = new DecimalMin[columnSum];
DecimalMax[] decimalMaxs = new DecimalMax[columnSum];
HeaderDescription[] headerDescriptions = new HeaderDescription[columnSum];
ColumnDescription[] columnDescriptions = new ColumnDescription[columnSum];
IsDuplicated[] isDuplicateds = new IsDuplicated[columnSum];
boolean[] matchFlag = new boolean[set.size()]; //保存字段是否出现在Excel文件中。
@ -405,10 +384,10 @@ public class DataTable<T> implements Serializable, Cloneable {
int tempFieldIndex = 0; //字段的编号,临时变量
for (Field field : set) {
HeaderName fieldHeaderName = field.getAnnotation(HeaderName.class);
if (headValue.equals(fieldHeaderName.value())) { //如果Excel列名与Class属性名相一致
ColumnName fieldColumnName = field.getAnnotation(ColumnName.class);
if (headValue.equals(fieldColumnName.value())) { //如果Excel列名与Class属性名相一致
columnMatchNumber++; //标记该列的存在
types[i] = field.getAnnotation(Type.class);
columnTypes[i] = field.getAnnotation(ColumnType.class);
enums[i] = field.getAnnotation(Enum.class);
splits[i] = field.getAnnotation(Split.class);
lengths[i] = field.getAnnotation(Length.class);
@ -416,7 +395,7 @@ public class DataTable<T> implements Serializable, Cloneable {
substrings[i] = field.getAnnotation(Substring.class);
decimalMins[i] = field.getAnnotation(DecimalMin.class);
decimalMaxs[i] = field.getAnnotation(DecimalMax.class);
headerDescriptions[i] = field.getAnnotation(HeaderDescription.class);
columnDescriptions[i] = field.getAnnotation(ColumnDescription.class);
isDuplicateds[i] = field.getAnnotation(IsDuplicated.class);
matchFlag[tempFieldIndex] = true;
@ -424,18 +403,18 @@ public class DataTable<T> implements Serializable, Cloneable {
}
tempFieldIndex++;
}
Column column = new Column();
column.setName(ExcelUtil.getValue(cell));
if (headerDescriptions[i] != null) {
column.setDescription(headerDescriptions[i].value());
WColumn WColumn = new WColumn();
WColumn.setName(ExcelUtil.getValue(cell));
if (columnDescriptions[i] != null) {
WColumn.setDescription(columnDescriptions[i].value());
}
if (types[i] != null) {
column.setDataType(types[i].value());
if (columnTypes[i] != null) {
WColumn.setDataType(columnTypes[i].value());
}
if (notNulls[i] != null) {
column.setRequired(true);
WColumn.setRequired(true);
}
this.addColumn(column);
this.addColumn(WColumn);
}
/* 如果文件不匹配 */
@ -446,7 +425,7 @@ public class DataTable<T> implements Serializable, Cloneable {
if (matchFlag[tempIndex++]) {
continue;
}
templateExcept.append(field.getAnnotation(HeaderName.class).value()).append("栏;");
templateExcept.append(field.getAnnotation(ColumnName.class).value()).append("栏;");
}
throw new TemplateNotMatchException("不匹配的Excel文件没有" + templateExcept.toString());
}
@ -455,7 +434,7 @@ public class DataTable<T> implements Serializable, Cloneable {
/* 逐行读取导入文件的数据 */
for (int i = 0; i < maxRowNumber; i++) {
Row inputRow = sheet.getRow(i + 1); //Excel中的一行数据第0行为表头所以要加1
DataRow row = new DataRow(); //DataTable中的一行
WRow row = new WRow(); //DataTable中的一行
this.addRow(row);
if (null != inputRow) {
@ -463,8 +442,8 @@ public class DataTable<T> implements Serializable, Cloneable {
/* 取得当前格子的值 */
org.apache.poi.ss.usermodel.Cell excelCell = inputRow.getCell(j);
Cell cell = new Cell();
this.setCell(i, columns[j].getName(), cell);
WCell WCell = new WCell();
this.setCell(i, WColumns[j].getName(), WCell);
String value = "";
if (null != excelCell) {
@ -483,7 +462,7 @@ public class DataTable<T> implements Serializable, Cloneable {
value = StringUtil.substring(value, substrings[j].start(), substrings[j].end());
}
cell.setValue(value);
WCell.setValue(value);
/* 如果要求非空 */
if (null != notNulls[j]) {
@ -512,8 +491,8 @@ public class DataTable<T> implements Serializable, Cloneable {
}
/* 如果对类型有要求 */
if (cellFlag && null != types[j] && !types[j].value().equals(DataType.STRING)) {
if (!DataType.check(types[j].value(), cell, value)) {
if (cellFlag && null != columnTypes[j] && !columnTypes[j].value().equals(DataType.STRING)) {
if (!DataType.check(columnTypes[j].value(), WCell, value)) {
this.setStatus(i, j, Status.FORMAT);
cellFlag = false;
}
@ -560,8 +539,8 @@ public class DataTable<T> implements Serializable, Cloneable {
*
* @return
*/
public Column[] getColumns() {
return this.columns;
public WColumn[] getWColumns() {
return this.WColumns;
}
/**
@ -573,7 +552,7 @@ public class DataTable<T> implements Serializable, Cloneable {
* @throws IndexOutOfBoundsException
* @throws ColumnNameNotExistException
*/
public Cell getCell(int rowNumber, String columnName)
public WCell getCell(int rowNumber, String columnName)
throws IndexOutOfBoundsException, ColumnNameNotExistException {
int columnNumber = getColumnIndex(columnName);
return getCell(rowNumber, columnNumber);
@ -586,7 +565,7 @@ public class DataTable<T> implements Serializable, Cloneable {
* @param columnNumber
* @throws IndexOutOfBoundsException
*/
public final Cell getCell(int rowNumber, int columnNumber) throws IndexOutOfBoundsException {
public final WCell getCell(int rowNumber, int columnNumber) throws IndexOutOfBoundsException {
if (rowNumber > this.rowIndex || rowNumber < 0) {
throw new IndexOutOfBoundsException("不存在的行坐标: " + rowNumber);
}
@ -601,18 +580,18 @@ public class DataTable<T> implements Serializable, Cloneable {
*
* @param rowNumber
* @param columnNumber
* @param cell
* @param WCell
* @throws IndexOutOfBoundsException
*/
public void setCell(int rowNumber, int columnNumber, Cell cell) throws IndexOutOfBoundsException {
public void setCell(int rowNumber, int columnNumber, WCell WCell) throws IndexOutOfBoundsException {
if (rowNumber > this.rowIndex || rowNumber < 0) {
throw new IndexOutOfBoundsException("不存在的行坐标: " + rowNumber);
}
if (columnNumber > this.columnIndex || columnNumber < 0) {
throw new IndexOutOfBoundsException("不存在的列坐标: " + columnNumber);
}
data[rowNumber][columnNumber] = cell;
this.setStatus(rowNumber, columnNumber, cell.getStatus());
data[rowNumber][columnNumber] = WCell;
this.setStatus(rowNumber, columnNumber, WCell.getStatus());
}
/**
@ -620,14 +599,14 @@ public class DataTable<T> implements Serializable, Cloneable {
*
* @param rowIndex
* @param columnName
* @param cell
* @param WCell
* @throws IndexOutOfBoundsException
* @throws ColumnNameNotExistException
*/
public void setCell(int rowIndex, String columnName, Cell cell)
public void setCell(int rowIndex, String columnName, WCell WCell)
throws IndexOutOfBoundsException, ColumnNameNotExistException {
int columnNumber = getColumnIndex(columnName);
this.setCell(rowIndex, columnNumber, cell);
this.setCell(rowIndex, columnNumber, WCell);
}
/**
@ -640,14 +619,14 @@ public class DataTable<T> implements Serializable, Cloneable {
*/
public void setStatus(int rowNumber, int columnNumber, Status status) throws IndexOutOfBoundsException {
if (!status.equals(Status.PASS)) {
Cell cell = this.getCell(rowNumber, columnNumber);
if (null == cell) {
cell = new Cell();
this.setCell(rowNumber, columnNumber, cell);
WCell WCell = this.getCell(rowNumber, columnNumber);
if (null == WCell) {
WCell = new WCell();
this.setCell(rowNumber, columnNumber, WCell);
}
cell.setStatus(status);
WCell.setStatus(status);
StringBuilder message = new StringBuilder(this.getColumns()[columnNumber].getName());
StringBuilder message = new StringBuilder(this.getWColumns()[columnNumber].getName());
message.append("栏");
switch (status) {
case NOTEXIST:
@ -692,7 +671,7 @@ public class DataTable<T> implements Serializable, Cloneable {
private int getColumnIndex(String columnName) throws ColumnNameNotExistException {
int columnIndex = -1;
for (int i = 0; i < this.getColumnIndex(); i++) {
if (this.getColumns()[i].getName().equals(columnName)) {
if (this.getWColumns()[i].getName().equals(columnName)) {
columnIndex = i;
break;
}
@ -723,16 +702,16 @@ public class DataTable<T> implements Serializable, Cloneable {
*
* @return
*/
public DataRow[] getDataRows() {
DataRow[] dataRows = new DataRow[this.rowIndex];
public WRow[] getDataRows() {
WRow[] wRows = new WRow[this.rowIndex];
for (int i = 0; i < this.rowIndex; i++) {
DataRow row = new DataRow();
WRow row = new WRow();
for (int j = 0; j < this.columnIndex; j++) {
row.put(this.columns[j].getName(), this.data[i][j]);
row.put(this.WColumns[j].getName(), this.data[i][j]);
}
dataRows[i] = row;
wRows[i] = row;
}
return dataRows;
return wRows;
}
/**
@ -740,14 +719,14 @@ public class DataTable<T> implements Serializable, Cloneable {
*
* @return Map
*/
public HashMap<String, List<Cell>> getDataColumns() {
HashMap<String, List<Cell>> columns = new HashMap<>();
public HashMap<String, List<WCell>> getDataColumns() {
HashMap<String, List<WCell>> columns = new HashMap<>();
for (int i = 0; i < this.columnIndex; i++) {
List<Cell> list = new ArrayList<>();
List<WCell> list = new ArrayList<>();
for (int j = 0; j < this.rowIndex; j++) {
list.add(data[j][i]);
}
columns.put(this.columns[i].getName(), list);
columns.put(this.WColumns[i].getName(), list);
}
return columns;
}
@ -757,21 +736,21 @@ public class DataTable<T> implements Serializable, Cloneable {
*
* @param row
*/
public void addRow(DataRow row) {
public void addRow(WRow row) {
/* 如果占用了一半以上,进行扩容 */
if (this.rowIndex >= MAX_ROW_NUMBER / 2) {
expandRow();
}
for (int i = 0; i < this.columnIndex; i++) {
Cell cell = row.get(this.columns[i].getName());
if (null != cell) {
this.setCell(this.rowIndex, i, cell);
int width = StringUtil.getByteLength(cell.getValue());
if (width > this.getColumns()[i].getCellWidth()) {
WCell WCell = row.get(this.WColumns[i].getName());
if (null != WCell) {
this.setCell(this.rowIndex, i, WCell);
int width = StringUtil.getByteLength(WCell.getValue());
if (width > this.getWColumns()[i].getCellWidth()) {
if (width > 100) {
width = 100;
}
this.getColumns()[i].setCellWidth(width);
this.getWColumns()[i].setCellWidth(width);
}
}
}
@ -781,25 +760,25 @@ public class DataTable<T> implements Serializable, Cloneable {
/**
* ,1.5
*
* @param column
* @param WColumn
*/
public void addColumn(Column column) {
public void addColumn(WColumn WColumn) {
/* 如果占用了一半以上,进行扩容 */
if (this.columnIndex >= MAX_COLUMN_NUMBER / 2) {
expandColumn();
}
boolean exist = false;
column.setName(column.getName().replace("*", "")); //删除标题中的星号
column.setName(column.getName().replace(" ", "")); //删除标题中的空格
WColumn.setName(WColumn.getName().replace("*", "")); //删除标题中的星号
WColumn.setName(WColumn.getName().replace(" ", "")); //删除标题中的空格
for (int i = 0; i < this.columnIndex; i++) {
if (column.getName().equals(this.getColumns()[i].getName())) {
if (WColumn.getName().equals(this.getWColumns()[i].getName())) {
exist = true;
}
}
if (!exist) {
this.columns[this.columnIndex++] = column;
this.WColumns[this.columnIndex++] = WColumn;
} else {
throw new ExistedColumnNameException("已存在名称为" + column.getName() + "的列");
throw new ExistedColumnNameException("已存在名称为" + WColumn.getName() + "的列");
}
}
@ -809,9 +788,9 @@ public class DataTable<T> implements Serializable, Cloneable {
protected void expandColumn() {
MAX_COLUMN_NUMBER *= (3 / 2) + 1;
/* 扩展表头 */
Column[] temp = new Column[MAX_COLUMN_NUMBER];
System.arraycopy(columns, 0, temp, 0, columns.length);
columns = temp;
WColumn[] temp = new WColumn[MAX_COLUMN_NUMBER];
System.arraycopy(WColumns, 0, temp, 0, WColumns.length);
WColumns = temp;
expand();
}
@ -832,7 +811,7 @@ public class DataTable<T> implements Serializable, Cloneable {
* data
*/
protected void expand() {
Cell[][] temp = new Cell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER];
WCell[][] temp = new WCell[MAX_ROW_NUMBER][MAX_COLUMN_NUMBER];
for (int i = 0; i < data.length; i++) {
System.arraycopy(data[i], 0, temp[i], 0, data[0].length);
}
@ -855,35 +834,32 @@ public class DataTable<T> implements Serializable, Cloneable {
T object = clazz.newInstance();
ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class);
boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value();
//Field[] fields = clazz.getDeclaredFields();
Field[] fields = ClassUtil.getFields(clazz, parentFirst);
Set<Field> set = new HashSet<>();
for (Field field : fields) {
if (field.isAnnotationPresent(HeaderName.class)) {
set.add(field);
}
set.add(field);
}
for (int j = 0; j < this.getColumnIndex(); j++) {
if (this.getColumns()[j].isHidden()) {
if (this.getWColumns()[j].isHidden()) {
continue;
}
String key = this.getColumns()[j].getName();
String key = this.getWColumns()[j].getName();
if (key.equals(CHECK_STATUS_NAME) || key.equals(CHECK_STATUS_RESULT)) {
continue;
}
for (Field field : set) {
HeaderName fieldHeaderName = field.getAnnotation(HeaderName.class);
ColumnName fieldColumnName = field.getAnnotation(ColumnName.class);
if (key.equals(fieldHeaderName.value())) {
if (key.equals(fieldColumnName.value())) {
String att = StringUtil.upperFirstWord(field.getName());
String value;
Cell cell = this.getCell(rowIndex, j);
if (null != cell) {
value = cell.getValue();
WCell WCell = this.getCell(rowIndex, j);
if (null != WCell) {
value = WCell.getValue();
Method method = clazz.getMethod("set" + att, field.getType());
if (field.isAnnotationPresent(Enum.class)) {
Enum e = field.getAnnotation(Enum.class);
@ -893,43 +869,22 @@ public class DataTable<T> implements Serializable, Cloneable {
} else {
method.invoke(object, EnumUtil.valueOf(e.target(), sValue));
}
} else if (field.isAnnotationPresent(Type.class)) {
Type type = field.getAnnotation(Type.class);
switch (type.value()) {
case DATETIME:
case DATE: {
Date date = TransferUtil.transferDate(value);
method.invoke(object, date);
break;
}
case DATEMINUTE: {
Date date = TransferUtil.transferDateminute(value);
method.invoke(object, date);
break;
}
case DECIMAL:
Double d = TransferUtil.transferDouble(value);
method.invoke(object, d);
break;
case NUMBER:
Integer integer = TransferUtil.transferInteger(value);
method.invoke(object, integer);
break;
case BOOLEAN:
Boolean b = TransferUtil.transferBoolean(value);
method.invoke(object, b);
break;
case LONG:
Long l = TransferUtil.transferLong(value);
method.invoke(object, l);
break;
default:
method.invoke(object, value);
break;
}
} else if (field.getType() == Date.class || field.getType() == java.sql.Date.class) {
Date date = TransferUtil.transferDate(value);
method.invoke(object, date);
} else if (field.getType() == Double.class || field.getType() == double.class
|| field.getType() == Float.class || field.getType() == float.class) {
Double d = TransferUtil.transferDouble(value);
method.invoke(object, d);
} else if (field.getType() == Integer.class || field.getType() == int.class
|| field.getType() == Long.class || field.getType() == long.class
|| field.getType() == Short.class || field.getType() == short.class
|| field.getType() == Byte.class || field.getType() == byte.class) {
Integer integer = TransferUtil.transferInteger(value);
method.invoke(object, integer);
} else if (field.getType() == Boolean.class || field.getType() == boolean.class) {
Boolean b = TransferUtil.transferBoolean(value);
method.invoke(object, b);
} else {
method.invoke(object, value);
}
@ -948,7 +903,7 @@ public class DataTable<T> implements Serializable, Cloneable {
*
*
* @return T
* @see Column
* @see WColumn
*/
public List<T> transferList(Class<T> clazz)
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
@ -1000,23 +955,22 @@ public class DataTable<T> implements Serializable, Cloneable {
public final String toCSV() {
StringBuilder sb = new StringBuilder();
for (Column column : this.getColumns()) {
if (column != null) {
sb.append(column.getName()).append(",");
for (WColumn WColumn : this.getWColumns()) {
if (WColumn != null) {
sb.append(WColumn.getName()).append(",");
}
}
sb.append("\n");
for (int i = 0; i < this.getRowIndex(); i++) {
for (int j = 0; j < this.getColumnIndex(); j++) {
Cell cell = this.getCell(i, j);
if (this.getColumns()[j].getDataType().equals(DataType.STRING)
|| this.getColumns()[j].getDataType().equals(DataType.DATE)
|| this.getColumns()[j].getDataType().equals(DataType.DATETIME)
|| this.getColumns()[j].getDataType().equals(DataType.DATEMINUTE)) {
sb.append("\"\t").append(cell.getValue()).append("\",");
WCell WCell = this.getCell(i, j);
if (this.getWColumns()[j].getDataType().equals(DataType.STRING)
|| this.getWColumns()[j].getDataType().equals(DataType.DATE)
|| this.getWColumns()[j].getDataType().equals(DataType.DATETIME)) {
sb.append("\"\t").append(WCell.getValue()).append("\",");
} else {
sb.append(cell.getValue()).append(",");
sb.append(WCell.getValue()).append(",");
}
}
sb.append("\n");
@ -1030,11 +984,11 @@ public class DataTable<T> implements Serializable, Cloneable {
for (int i = 0; i < columnIndex; i++) {
for (int j = 0; j < rowIndex; j++) {
int length = StringUtil.getByteLength(this.getCell(j, i).getValue());
if (columns[i].getCellWidth() < length) {
if (WColumns[i].getCellWidth() < length) {
if (length > 100) {
length = 100;
}
columns[i].setCellWidth(length);
WColumns[i].setCellWidth(length);
}
}
}
@ -1044,19 +998,19 @@ public class DataTable<T> implements Serializable, Cloneable {
/* 打印表头 */
for (int i = 0; i < this.getColumnIndex(); i++) {
Column column = this.getColumns()[i];
int width = column.getCellWidth() - StringUtil.getByteLength(column.getName()) + 4;
WColumn WColumn = this.getWColumns()[i];
int width = WColumn.getCellWidth() - StringUtil.getByteLength(WColumn.getName()) + 4;
int left = width / 2;
int right = width - left;
for (int j = 0; j < left; j++) {
sb.append(" ");
}
sb.append(column.getName());
sb.append(WColumn.getName());
for (int j = 0; j < right; j++) {
sb.append(" ");
}
sumWidth += column.getCellWidth();
sumWidth += WColumn.getCellWidth();
}
sb.append(CHECK_STATUS_NAME);
@ -1071,15 +1025,15 @@ public class DataTable<T> implements Serializable, Cloneable {
/* 打印数据 */
for (int i = 0; i < this.getRowIndex(); i++) {
for (int j = 0; j < this.getColumnIndex(); j++) {
int cellWidth = this.getColumns()[j].getCellWidth();
Cell cell = null;
int cellWidth = this.getWColumns()[j].getCellWidth();
WCell WCell = null;
try {
cell = this.getCell(i, j);
WCell = this.getCell(i, j);
} catch (Exception e) {
e.printStackTrace();
}
if (null != cell) {
Object obj = cell.getValue();
if (null != WCell) {
Object obj = WCell.getValue();
int width = cellWidth - StringUtil.getByteLength(obj.toString()) + 4;
int left = width / 2;
int right = width - left;
@ -1088,7 +1042,7 @@ public class DataTable<T> implements Serializable, Cloneable {
sb.append(" ");
}
sb.append(obj);
if (Status.PASS != cell.getStatus()) {
if (Status.PASS != WCell.getStatus()) {
sb.append("*");
if (right > 1) {
right--;

@ -7,7 +7,7 @@ import java.io.Serializable;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -7,7 +7,7 @@ import java.util.Map;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:Excel
* ColumnDescription:WExcel
* ***************************************************************
* </pre>
*/
@ -17,7 +17,7 @@ public class ExcelCollectionEntity {
*/
private String name;
/**
* Excel
* WExcel
*/
private String excelName;
/**

@ -8,7 +8,7 @@ import java.util.List;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -5,7 +5,7 @@ package com.wb.excel.api.entity;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -15,7 +15,7 @@ import java.util.Map;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -1,7 +1,7 @@
package com.wb.excel.api.entity;
/**
* Excel
* WExcel
*/
public class ExcelVerifyEntity {

@ -1,8 +1,8 @@
package com.wb.excel.api.enumeration;
import com.wb.excel.api.annotation.HeaderDescription;
import com.wb.excel.api.annotation.HeaderName;
import com.wb.excel.api.datatable.Cell;
import com.wb.excel.api.annotation.ColumnDescription;
import com.wb.excel.api.annotation.ColumnName;
import com.wb.excel.api.datatable.WCell;
import com.wb.excel.api.util.EnumUtil;
import com.wb.excel.api.util.StringUtil;
import com.wb.excel.api.util.ValidationUtil;
@ -16,98 +16,62 @@ import com.wb.excel.api.util.ValidationUtil;
* @version v1.0.0.0
*/
public enum DataType {
@HeaderName("字符型")
@HeaderDescription("普通的字符串类型例如abc123.,!@#")
@ColumnName("字符型")
@ColumnDescription("普通的字符串类型例如abc123.,!@#")
STRING,
@HeaderName("整数型")
@HeaderDescription("整数类型,小数点后的数字会被抹去(不是四舍五入),例如112004000")
@ColumnName("整数型")
@ColumnDescription("整数类型,小数点后的数字会被抹去(不是四舍五入),例如112004000")
NUMBER,
@HeaderName("数字类型")
@HeaderDescription("可以带小数点的数字类型例如1.001.01")
@ColumnName("数字类型")
@ColumnDescription("可以带小数点的数字类型例如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")
@ColumnName("日期型")
@ColumnDescription("普通的日期类型例如2014-10-01")
DATE,
@HeaderName("时间日期型(秒)")
@HeaderDescription("时间精确到秒的日期类型例如2014-10-01 10:30:00")
@ColumnName("时间日期型(秒)")
@ColumnDescription("时间精确到秒的日期类型例如2014-10-01 10:30:00")
DATETIME,
@HeaderName("时间日期型(分钟)")
@HeaderDescription("时间精确到分钟的日期类型例如2014-10-01 10:30")
DATEMINUTE,
@HeaderName("是否型")
@HeaderDescription("指定是或者否的类型,例如:是,否")
BOOLEAN,
@HeaderName("大数型")
@HeaderDescription("用于较大的数字类型,会忽略小数点以后的内容")
LONG;
@ColumnName("是否型")
@ColumnDescription("指定是或者否的类型,例如:是,否")
BOOLEAN;
/**
* .
*
* @param type
* @param cell
* @param WCell
* @param value
* @return truefalse
*/
public static boolean check(DataType type, Cell cell, String value) {
public static boolean check(DataType type, WCell WCell, String value) {
boolean typeFlag = true;
if (value.length() > 0) {
switch (type) {
case EMAIL:
typeFlag = ValidationUtil.checkEmail(value);
break;
case PHONE:
typeFlag = ValidationUtil.checkPhone(value);
break;
case URL:
typeFlag = ValidationUtil.checkUrl(value);
break;
case DECIMAL:
typeFlag = ValidationUtil.checkDouble(value);
break;
case NUMBER:
typeFlag = ValidationUtil.checkInteger(value);
if (typeFlag) {
cell.setValue(StringUtil.transferInteger(value));
WCell.setValue(StringUtil.transferInteger(value));
}
break;
case DATE:
typeFlag = ValidationUtil.checkDate(value);
if (typeFlag) {
cell.setValue(StringUtil.transferDate(value));
WCell.setValue(StringUtil.transferDate(value));
}
break;
case DATETIME:
typeFlag = ValidationUtil.checkDatetime(value);
if (typeFlag) {
cell.setValue(StringUtil.transferDatetime(value));
}
break;
case DATEMINUTE:
typeFlag = ValidationUtil.checkDatetime(value);
if (typeFlag) {
cell.setValue(StringUtil.transferDateminute(value));
WCell.setValue(StringUtil.transferDatetime(value));
}
break;
case BOOLEAN:
typeFlag = EnumUtil.check(YesNo.class, value);
if (typeFlag) {
cell.setValue(StringUtil.transferBoolean(value));
}
break;
case LONG:
typeFlag = ValidationUtil.checkLong(value);
if (typeFlag) {
cell.setValue(StringUtil.transferLong(value));
WCell.setValue(StringUtil.transferBoolean(value));
}
break;
default:

@ -10,7 +10,7 @@ import java.util.regex.Pattern;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -15,6 +15,13 @@ import java.util.*;
*/
public class ClassUtil {
/**
*
*
* @param clazz
* @param parentFirst
* @return
*/
public static Field[] getFields(Class clazz, boolean parentFirst) {
List<Field> returnList = new ArrayList<>();
Set<String> nameSet = new HashSet<>();

@ -7,7 +7,7 @@ import org.apache.poi.hpsf.Constants;
* <p>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -9,7 +9,7 @@ import com.wb.excel.api.interfaces.IExcelVerifyHandler;
* <p/>
* <pre>
* Copyright (c) 2014
* HeaderDescription:
* ColumnDescription:
* ***************************************************************
* </pre>
*/

@ -1,11 +1,12 @@
import com.wb.excel.api.Excel;
import com.wb.excel.api.datatable.DataTable;
import com.wb.excel.api.WExcel;
import com.wb.excel.api.datatable.WSheet;
import com.wb.excel.api.enumeration.YesNo;
import com.wb.excel.api.exception.TemplateNotMatchException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
@ -24,19 +25,23 @@ public class ExampleTest {
//第一步,准备数据模型及数据,模型需要打上注解
List<User> pos = new ArrayList();
User user = new User("张三", "zs123", "123123");
User user = new User();
user.setName("张三");
user.setDate(new Date());
user.setSqlDate(new java.sql.Date(new Date().getTime()));
user.setAge(20);
user.setSex(YesNo.Y);
pos.add(user);
pos.add(user);
//第二步,初始化数据
DataTable dataTable = new DataTable(pos);
WSheet WSheet = new WSheet(pos);
//第三步,初始化Excel
Excel excel = new Excel(dataTable);
WExcel WExcel = new WExcel(false, WSheet);
//第四步导出xlsx文件
output("user.xlsx", excel.getBytes());
output("user.xlsx", WExcel.getBytes());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IOException e) {
@ -46,7 +51,6 @@ public class ExampleTest {
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public static void testImport() {
@ -57,13 +61,13 @@ public class ExampleTest {
byte[] bytes = new byte[stream.available()];
stream.read(bytes);
DataTable dataTable = new DataTable(bytes, User.class);
WSheet WSheet = new WSheet(bytes, User.class);
if (dataTable.hasError()) {
Excel excel = new Excel(true, dataTable);
output("user_err.xlsx", excel.getBytes());
if (WSheet.hasError()) {
WExcel WExcel = new WExcel(true, WSheet);
output("user_err.xlsx", WExcel.getBytes());
} else {
List<User> list = dataTable.transferList(User.class);
List<User> list = WSheet.transferList(User.class);
System.out.println("本次读取数据" + list.size() + "条!");
}

@ -1,26 +1,28 @@
import com.wb.excel.api.annotation.ColumnName;
import com.wb.excel.api.annotation.Enum;
import com.wb.excel.api.annotation.EnumValue;
import com.wb.excel.api.annotation.SheetName;
import com.wb.excel.api.enumeration.YesNo;
import javax.validation.constraints.NotNull;
import java.sql.Date;
@SheetName("用户")
public class User {
@NotNull
@ColumnName("姓名")
private String name;
private String password;
private String qq;
@ColumnName("出生日期时间")
private java.util.Date date;
@ColumnName("出生日期")
private Date sqlDate;
@ColumnName("年纪")
private int age;
@Enum(target = YesNo.class)
@ColumnName("性别")
private YesNo sex;
public User() {
}
public User(String name, String password, String qq) {
this.name = name;
this.password = password;
this.qq = qq;
}
public YesNo getSex() {
return sex;
}
@ -29,14 +31,6 @@ public class User {
this.sex = sex;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getName() {
return name;
}
@ -45,11 +39,28 @@ public class User {
this.name = name;
}
public String getPassword() {
return password;
public java.util.Date getDate() {
return date;
}
public void setPassword(String password) {
this.password = password;
public void setDate(java.util.Date date) {
this.date = date;
}
public Date getSqlDate() {
return sqlDate;
}
public void setSqlDate(Date sqlDate) {
this.sqlDate = sqlDate;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Loading…
Cancel
Save

Powered by TurnKey Linux.