master
wangbing 5 years ago
parent 74bae8de71
commit fe30568e63

@ -8,6 +8,7 @@ import com.wb.excel.api.exception.*;
import com.wb.excel.api.exception.Error;
import com.wb.excel.api.util.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
@ -121,7 +122,8 @@ public class WSheet<T> implements Serializable, Cloneable {
* @param clazz
* @return @NameSet
*/
private WColumn[] initColumns(Class<?> clazz) {
private List<WColumn> initColumns(Class<?> clazz) {
List<WColumn> result = new ArrayList();
//获取工作簿名称,没有则以类名为默认工作簿名称
SheetName sheetName = clazz.getAnnotation(SheetName.class);
if (sheetName != null) {
@ -166,8 +168,9 @@ public class WSheet<T> implements Serializable, Cloneable {
}
this.addColumn(WColumn);
result.add(WColumn);
}
return this.WColumns;
return result;
}
/**
@ -186,11 +189,11 @@ public class WSheet<T> implements Serializable, Cloneable {
}
if (list.size() > 0) {
T tClass = list.get(0);
WColumn[] WColumns = initColumns(tClass.getClass());
List<WColumn> wColumns = initColumns(tClass.getClass());
for (T t : list) {
WRow row = new WRow();
for (WColumn WColumn : WColumns) {
for (WColumn WColumn : wColumns) {
if (WColumn == null) {
continue;
}
@ -330,33 +333,41 @@ public class WSheet<T> implements Serializable, Cloneable {
if (!flag) {
throw new TemplateNotMatchException("不支持的文件类型");
}
//第一张Sheet表
Sheet sheet = workbook.getSheetAt(0);
//获取Sheet名称
SheetName sheetName = clazz.getAnnotation(SheetName.class);
if (sheetName != null) {//如果模板存在注解则使用注解名称
this.setName(sheetName.value());
} else {//将类名设为表名如果类名不存在将Excel表名设为表名
this.setName(sheet.getSheetName());
}
Sheet sheet = workbook.getSheetAt(0); //处理第一张Sheet表
String tableName = sheet.getSheetName(); //DataTable的名字
//读取表头
Row headRow = sheet.getRow(0);
//获取Excel列的总数
int columnSum = headRow.getPhysicalNumberOfCells();
//匹配列的数量。用于判断Excel是否包含所有必须列。
int columnMatchNumber = 0;
//检查列数量
List<WColumn> list = initColumns(clazz);
if (list.size() != columnSum) {
throw new TemplateNotMatchException("与模板列数量不同。");
} else {
for (int i = 0; i < list.size(); i++) {
WColumn wColumn = list.get(i);
Cell cell = headRow.getCell(i);
String headValue = ExcelUtil.getValue(cell);
headValue = headValue.replace("*", "");
headValue = headValue.replace(" ", "");
/* 获取指定类所有带有Name注解的属性集合 */
ColumnName classColumnName = clazz.getAnnotation(ColumnName.class); //该类所声明的名字
ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class);
boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value();
if (classColumnName != null) {
tableName = classColumnName.value();
if (!wColumn.getName().equals(headValue)) {
throw new TemplateNotMatchException("第" + (i + 1) + "项,不匹配的列名," + wColumn.getName() + "和" + headValue);
}
this.setName(tableName); //将类名设为表名如果类名不存在将Excel表名设为表名
//Field[] fields = clazz.getDeclaredFields(); //该类所声明的全部属性
Field[] fields = ClassUtil.getFields(clazz, parentFirst); //该类所声明的全部属性
Set<Field> set = new HashSet<>(); //用于保存所有带有Name注解的属性
for (Field field : fields) {
if (field.isAnnotationPresent(ColumnName.class)) {
set.add(field);
}
}
/* 读取表头 */
Row headRow = sheet.getRow(0);
int columnSum = headRow.getPhysicalNumberOfCells(); //获取Excel列的总数
int columnMatchNumber = 0; //匹配列的数量。用于判断Excel是否包含所有必须列。
/* 为Excel表中的每一列分配空间 */
List<Set<String>> sets = new ArrayList<>();
ColumnType[] columnTypes = new ColumnType[columnSum];
@ -370,66 +381,6 @@ public class WSheet<T> implements Serializable, Cloneable {
ColumnDescription[] columnDescriptions = new ColumnDescription[columnSum];
IsDuplicated[] isDuplicateds = new IsDuplicated[columnSum];
boolean[] matchFlag = new boolean[set.size()]; //保存字段是否出现在Excel文件中。
/* 查找匹配列的数量 */
for (int i = 0; i < columnSum; i++) {
sets.add(new HashSet<String>());
org.apache.poi.ss.usermodel.Cell cell = headRow.getCell(i);
String headValue = ExcelUtil.getValue(cell); //获取列名
headValue = headValue.replace("*", "");
headValue = headValue.replace(" ", "");
int tempFieldIndex = 0; //字段的编号,临时变量
for (Field field : set) {
ColumnName fieldColumnName = field.getAnnotation(ColumnName.class);
if (headValue.equals(fieldColumnName.value())) { //如果Excel列名与Class属性名相一致
columnMatchNumber++; //标记该列的存在
columnTypes[i] = field.getAnnotation(ColumnType.class);
enums[i] = field.getAnnotation(Enum.class);
splits[i] = field.getAnnotation(Split.class);
lengths[i] = field.getAnnotation(Length.class);
notNulls[i] = field.getAnnotation(NotNull.class);
substrings[i] = field.getAnnotation(Substring.class);
decimalMins[i] = field.getAnnotation(DecimalMin.class);
decimalMaxs[i] = field.getAnnotation(DecimalMax.class);
columnDescriptions[i] = field.getAnnotation(ColumnDescription.class);
isDuplicateds[i] = field.getAnnotation(IsDuplicated.class);
matchFlag[tempFieldIndex] = true;
break;
}
tempFieldIndex++;
}
WColumn WColumn = new WColumn();
WColumn.setName(ExcelUtil.getValue(cell));
if (columnDescriptions[i] != null) {
WColumn.setDescription(columnDescriptions[i].value());
}
if (columnTypes[i] != null) {
WColumn.setDataType(columnTypes[i].value());
}
if (notNulls[i] != null) {
WColumn.setRequired(true);
}
this.addColumn(WColumn);
}
/* 如果文件不匹配 */
if (columnMatchNumber != set.size()) {
StringBuilder templateExcept = new StringBuilder();
int tempIndex = 0;
for (Field field : set) {
if (matchFlag[tempIndex++]) {
continue;
}
templateExcept.append(field.getAnnotation(ColumnName.class).value()).append("栏;");
}
throw new TemplateNotMatchException("不匹配的Excel文件没有" + templateExcept.toString());
}
int maxRowNumber = sheet.getLastRowNum(); //Excel文件的总行数
/* 逐行读取导入文件的数据 */
for (int i = 0; i < maxRowNumber; i++) {
@ -441,7 +392,7 @@ public class WSheet<T> implements Serializable, Cloneable {
for (int j = 0; j < columnSum; j++) { //逐格扫描
/* 取得当前格子的值 */
org.apache.poi.ss.usermodel.Cell excelCell = inputRow.getCell(j);
Cell excelCell = inputRow.getCell(j);
WCell WCell = new WCell();
this.setCell(i, WColumns[j].getName(), WCell);
@ -869,7 +820,7 @@ public class WSheet<T> implements Serializable, Cloneable {
} else {
method.invoke(object, EnumUtil.valueOf(e.target(), sValue));
}
} else if (field.getType() == Date.class || field.getType() == java.sql.Date.class) {
} else if (field.getType() == Date.class) {
Date date = TransferUtil.transferDate(value);
method.invoke(object, date);
} else if (field.getType() == Double.class || field.getType() == double.class
@ -905,8 +856,7 @@ public class WSheet<T> implements Serializable, Cloneable {
* @return T
* @see WColumn
*/
public List<T> transferList(Class<T> clazz)
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
public List<T> transferList(Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
List<T> list = new ArrayList<>();
for (int i = 0; i < this.getRowIndex(); i++) {

@ -1,7 +1,11 @@
package com.wb.excel.api.util;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Excel.
* Created on 2014/9/1.
@ -21,9 +25,13 @@ public class ExcelUtil {
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型的值
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC && !HSSFDateUtil.isCellDateFormatted(cell)) {
// 返回数值类型的值
return String.valueOf(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(cell)) {
// 返回数值类型的值
Date value = cell.getDateCellValue();
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
} else {
// 返回字符串类型的值
return String.valueOf(cell.getStringCellValue());

@ -15,37 +15,26 @@ import java.util.Date;
*/
public class TransferUtil {
public static Date transferDate(String value) {
if (value == null) {
return null;
}
Date date = null;
try {
if (value.length() == 10) {
value = value.trim();
if (value.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.parse(value);
} else if (value.length() > 10) {
return sdf.parse(value);
} else if (value.matches("[0-9]{4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(value);
} else if (value.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = sdf.parse(value);
}
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static Date transferDatetime(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
} else if (value.matches("[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日 [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static Date transferDateminute(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = null;
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}

@ -2,6 +2,7 @@ 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 jdk.nashorn.internal.parser.JSONParser;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
@ -15,7 +16,7 @@ import java.util.List;
public class ExampleTest {
public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
testExport();
// testExport();
testImport();
}
@ -28,7 +29,6 @@ public class ExampleTest {
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);
@ -69,6 +69,9 @@ public class ExampleTest {
} else {
List<User> list = WSheet.transferList(User.class);
System.out.println("本次读取数据" + list.size() + "条!");
for (User user : list) {
System.out.println(user);
}
}
} catch (FileNotFoundException e) {

@ -1,11 +1,11 @@
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;
import java.text.SimpleDateFormat;
import java.util.Date;
@SheetName("用户")
public class User {
@ -14,23 +14,13 @@ public class User {
@ColumnName("姓名")
private String name;
@ColumnName("出生日期时间")
private java.util.Date date;
@ColumnName("出生日期")
private Date sqlDate;
private Date date;
@ColumnName("年纪")
private int age;
@Enum(target = YesNo.class)
@ColumnName("性别")
private YesNo sex;
public YesNo getSex() {
return sex;
}
public void setSex(YesNo sex) {
this.sex = sex;
}
public String getName() {
return name;
}
@ -39,22 +29,14 @@ public class User {
this.name = name;
}
public java.util.Date getDate() {
public Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
public void setDate(Date date) {
this.date = date;
}
public Date getSqlDate() {
return sqlDate;
}
public void setSqlDate(Date sqlDate) {
this.sqlDate = sqlDate;
}
public int getAge() {
return age;
}
@ -63,4 +45,16 @@ public class User {
this.age = age;
}
public YesNo getSex() {
return sex;
}
public void setSex(YesNo sex) {
this.sex = sex;
}
@Override
public String toString() {
return "" + name + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + age + sex;
}
}

Loading…
Cancel
Save

Powered by TurnKey Linux.