master
wangbing 5 years ago
parent d011846d84
commit 74bae8de71

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

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

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

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

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

@ -21,7 +21,7 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
/** /**
* Excel * WExcel
* *
* @author JueYue * @author JueYue
* @date 2014623 10:46:26 * @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.*; import java.lang.annotation.*;
/** /**
* Created on 2015/5/28. *
* *
* @author * @author
* @since 2.1.0 * @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 * @author
* @since 0.1.0 * @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.status = Status.PASS;
this.value = ""; this.value = "";
} }
@ -36,7 +36,7 @@ public class Cell implements Serializable {
* *
* @param value . * @param value .
*/ */
public Cell(String value) { public WCell(String value) {
this.value = value; this.value = value;
this.status = Status.PASS; this.status = Status.PASS;
} }

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

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

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

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

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

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

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

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

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

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

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

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

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

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