master
wangbing 5 years ago
parent fe30568e63
commit 43fe35cf1f

@ -1,4 +1,4 @@
package com.wb.excel.api.datatable;
package com.wb.excel.api;
import com.wb.excel.api.enumeration.Status;

@ -1,7 +1,7 @@
package com.wb.excel.api.datatable;
package com.wb.excel.api;
import com.wb.excel.api.enumeration.DataType;
import com.wb.excel.api.converter.Converter;
import com.wb.excel.api.util.StringUtil;
import java.io.Serializable;
@ -34,9 +34,9 @@ public class WColumn implements Serializable {
*/
private String description;
/**
*
*
*/
private DataType dataType;
private Converter converter;
private Field field;
@ -46,7 +46,6 @@ public class WColumn implements Serializable {
this.isHidden = false;
this.isRequired = false;
this.description = "";
this.dataType = DataType.STRING;
}
public WColumn(String name) {
@ -55,7 +54,6 @@ public class WColumn implements Serializable {
this.isHidden = false;
this.isRequired = false;
this.description = "";
this.dataType = DataType.STRING;
}
//----------- getter & setter --------------
@ -110,11 +108,11 @@ public class WColumn implements Serializable {
this.description = description;
}
public DataType getDataType() {
return dataType;
public Converter getConverter() {
return converter;
}
public void setDataType(DataType dataType) {
this.dataType = dataType;
public void setConverter(Converter converter) {
this.converter = converter;
}
}

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

@ -1,4 +1,4 @@
package com.wb.excel.api.datatable;
package com.wb.excel.api;
import java.io.Serializable;
import java.util.HashMap;

@ -0,0 +1,636 @@
package com.wb.excel.api;
import com.wb.excel.api.annotation.*;
import com.wb.excel.api.converter.*;
import com.wb.excel.api.converter.Converter;
import com.wb.excel.api.enumeration.Status;
import com.wb.excel.api.exception.IllegalParameterException;
import com.wb.excel.api.exception.TemplateNotMatchException;
import com.wb.excel.api.style.*;
import com.wb.excel.api.util.ClassUtil;
import com.wb.excel.api.util.ExcelUtil;
import com.wb.excel.api.util.StringUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* <br/>
* Created on 2014/09/19.
*
* @author
* @since 0.1.0
*/
public class WSheet<T> implements Serializable, Cloneable {
/**
*
*/
private String name;
/**
*
*/
private List<WColumn> columnList = new ArrayList<>();
/**
*
*/
private List<WRow> rowList = new ArrayList<>();
/**
*
*/
public WSheet(Class<T> tClass) {
initColumns(tClass);
}
/**
* DataTable
*
* @return @NameSet
*/
private List<WColumn> initColumns(Class<?> clazz) {
//获取工作簿名称,没有则以类名为默认工作簿名称
SheetName sheetName = clazz.getAnnotation(SheetName.class);
if (sheetName != null) {
this.setName(sheetName.value());
} else {
this.setName(clazz.getName());
}
//是否关注父类属性
boolean parentFirst = clazz.isAnnotationPresent(ParentFirst.class) && clazz.getAnnotation(ParentFirst.class).value();
Field[] fields = ClassUtil.getFields(clazz, parentFirst);
for (Field field : fields) {
WColumn WColumn = new WColumn();
WColumn.setField(field);
if (field.isAnnotationPresent(Ignore.class) && field.getAnnotation(Ignore.class).value()) {
WColumn.setHidden(true);
}
//获取列名称
if (!field.isAnnotationPresent(ColumnName.class)) {
WColumn.setName(field.getName());
} else {
ColumnName columnColumnName = field.getAnnotation(ColumnName.class);
WColumn.setName(columnColumnName.value());
}
//获取列填写说明或描述
if (field.isAnnotationPresent(ColumnDescription.class)) {
WColumn.setDescription(field.getAnnotation(ColumnDescription.class).value());
}
//列填写标志(是否必填)
if (field.isAnnotationPresent(NotNull.class)) {
WColumn.setRequired(true);
}
//获取列类型
if (field.isAnnotationPresent(com.wb.excel.api.annotation.Converter.class)) {
com.wb.excel.api.annotation.Converter converter = field.getAnnotation(com.wb.excel.api.annotation.Converter.class);
Class target = converter.target();
try {
WColumn.setConverter((Converter) target.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
if (field.getType() == boolean.class || field.getType() == Boolean.class) {
WColumn.setConverter(new BooleanConverter());
} else if (field.getType() == byte.class || field.getType() == Byte.class) {
WColumn.setConverter(new ByteConverter());
} else if (field.getType() == char.class || field.getType() == Character.class) {
WColumn.setConverter(new CharacterConverter());
} else if (field.getType() == short.class || field.getType() == Short.class) {
WColumn.setConverter(new ShortConverter());
} else if (field.getType() == int.class || field.getType() == Integer.class) {
WColumn.setConverter(new IntegerConverter());
} else if (field.getType() == long.class || field.getType() == Long.class) {
WColumn.setConverter(new LongConverter());
} else if (field.getType() == float.class || field.getType() == Float.class) {
WColumn.setConverter(new FloatConverter());
} else if (field.getType() == double.class || field.getType() == Double.class) {
WColumn.setConverter(new DoubleConverter());
} else if (field.getType() == Date.class) {
WColumn.setConverter(new DateConverter());
} else if (field.getType() == String.class) {
WColumn.setConverter(new StringConverter());
} else {
throw new RuntimeException("Can not find Converter");
}
}
columnList.add(WColumn);
}
return columnList;
}
/**
* <br/>
*
*
* @param list
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public WSheet(List<T> list) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
if (list == null || list.size() == 0) {
throw new IllegalParameterException("不允许传入空的列表");
}
if (list.size() > 0) {
List<WColumn> wColumns = initColumns(list.get(0).getClass());
for (T t : list) {
WRow row = new WRow();
for (WColumn column : wColumns) {
if (column == null) {
continue;
}
Field field = column.getField();
String att = StringUtil.upperFirstWord(field.getName());
Method method = null;
try {
// 尝试获取get方法
method = t.getClass().getMethod("get" + att);
} catch (NoSuchMethodException e) {
// 尝试获取is方法工具生成布尔值可能是is而不是get
method = t.getClass().getMethod("is" + att);
}
Object value = method.invoke(t);
if (null == value) {
row.put(column.getName(), new WCell());
} else {
row.put(column.getName(), new WCell(column.getConverter().string(value)));
}
}
this.rowList.add(row);
}
}
}
/**
* Excel<br/>
* <br/>
*
* @param bytes Excel
* @param clazz
* @throws IOException <br/>1:Excel - bytes <br/>
* 2:<br/>
* @throws TemplateNotMatchException <br/>1:Excel - Excel<br/>
* 2: - <br/>
*/
public WSheet(byte[] bytes, Class<T> clazz) throws IOException, TemplateNotMatchException {
Workbook workbook = null;
InputStream is = null;
boolean flag;
try {
flag = true;
is = new ByteArrayInputStream(bytes); //读取文件流
workbook = new HSSFWorkbook(is);
} catch (Exception e) {
flag = false;
}
if (!flag) {
try {
flag = true;
is = new ByteArrayInputStream(bytes); //读取文件流
workbook = new XSSFWorkbook(is);
} catch (Exception e) {
flag = false;
}
}
if (is != null) {
is.close();
}
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());
}
//读取表头
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(" ", "");
if (!wColumn.getName().equals(headValue)) {
throw new TemplateNotMatchException("第" + (i + 1) + "项,不匹配的列名," + wColumn.getName() + "和" + headValue);
}
}
}
int maxRowNumber = sheet.getLastRowNum(); //Excel文件的总行数
/* 逐行读取导入文件的数据 */
for (int i = 0; i < maxRowNumber; i++) {
Row inputRow = sheet.getRow(i + 1); //Excel中的一行数据第0行为表头所以要加1
WRow row = new WRow();
rowList.add(row);
if (null != inputRow) {
for (int j = 0; j < columnList.size(); j++) {
WColumn wcolumn = columnList.get(j);
/* 取得当前格子的值 */
Cell excelCell = inputRow.getCell(j);
WCell WCell = new WCell();
row.put(wcolumn.getName(), WCell);
String value = "";
if (null != excelCell) {
value = ExcelUtil.getValue(excelCell);
}
value = value.trim();
WCell.setValue(value);
// 检查是否必须项
if (wcolumn.isRequired()) {
if (value.length() == 0) {
WCell.setStatus(Status.EMPTY);
}
}
// 检查长度是否合法
// if (wcolumn) {
// if (value.length() > lengths[j].max() || value.length() < lengths[j].min()) {
// this.setStatus(i, j, Status.LENGTH);
// cellFlag = false;
// }
// }
// 检查字符是否符合正则表达式
// if (cellFlag && null != columnTypes[j] && !columnTypes[j].value().equals(DataType.STRING)) {
// if (!DataType.check(columnTypes[j].value(), WCell, value)) {
// this.setStatus(i, j, Status.FORMAT);
// cellFlag = false;
// }
// }
}
}
}
}
// /**
// * 能过列名取得列下标。
// *
// * @param columnName 列名
// * @return 该列对应的下标
// * @throws ColumnNameNotExistException
// */
// private int getColumnIndex(String columnName) throws ColumnNameNotExistException {
// int columnIndex = -1;
// for (int i = 0; i < this.getColumnIndex(); i++) {
// if (this.columnList.get(i).getName().equals(columnName)) {
// columnIndex = i;
// break;
// }
// }
// if (columnIndex == -1) {
// throw new ColumnNameNotExistException("不存在的列名:" + columnName);
// }
// return columnIndex;
// }
/**
*
*
* @param clazz
* @param rowIndex
* @return
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public T transferOneObject(Class<T> clazz, int rowIndex)
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
T object = clazz.newInstance();
ParentFirst parentFirstAnnotation = clazz.getAnnotation(ParentFirst.class);
boolean parentFirst = parentFirstAnnotation != null && parentFirstAnnotation.value();
Field[] fields = ClassUtil.getFields(clazz, parentFirst);
Set<Field> set = new HashSet<>();
for (Field field : fields) {
set.add(field);
}
for (int j = 0; j < this.columnList.size(); j++) {
WColumn wColumn = this.columnList.get(0);
if (wColumn.isHidden()) {
continue;
}
String key = this.columnList.get(j).getName();
for (WColumn column : columnList) {
Field field = column.getField();
ColumnName fieldColumnName = field.getAnnotation(ColumnName.class);
if (key.equals(fieldColumnName.value())) {
String att = StringUtil.upperFirstWord(field.getName());
WCell WCell = this.rowList.get(rowIndex).get(column.getName());
if (null != WCell) {
String value = WCell.getValue();
Method method = clazz.getMethod("set" + att, field.getType());
//获取转换器
Converter converter = column.getConverter();
method.invoke(object, converter.convert(value));
}
break;
}
}
}
return object;
}
/**
* DataTableTList<br/><br/>
* ,@Name<br/>
* DataTable<br/>
*
*
* @return T
* @see WColumn
*/
public List<T> transferList(Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
List<T> list = new ArrayList<>();
for (int i = 0; i < this.rowList.size(); i++) {
T object = transferOneObject(clazz, i);
list.add(object);
}
return list;
}
/**
*
*
* @return
*/
public String getName() {
return name;
}
/**
*
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
//
// public final String toCSV() {
// StringBuilder sb = new StringBuilder();
//
// for (WColumn WColumn : this.getWColumns()) {
// if (WColumn != null) {
// sb.append(WColumn.getName()).append(",");
// }
// }
// sb.append("\n");
//
// for (int i = 0; i < this.getRowIndex(); i++) {
// for (int j = 0; j < this.getColumnIndex(); j++) {
// WCell WCell = this.getCell(i, j);
// if (this.columnList.get(j).getDataType().equals(DataType.STRING)
// || this.columnList.get(j).getDataType().equals(DataType.DATE)
// || this.columnList.get(j).getDataType().equals(DataType.DATETIME)) {
// sb.append("\"\t").append(WCell.getValue()).append("\",");
// } else {
// sb.append(WCell.getValue()).append(",");
// }
// }
// sb.append("\n");
// }
//
// return sb.toString();
// }
/**
* DataTable
*
* @return .
*/
public final boolean hasError() {
for (WRow wRow : rowList) {
Iterator<WCell> iterator = wRow.values().iterator();
while (iterator.hasNext()) {
WCell next = iterator.next();
if (next.getStatus().name() != Status.PASS.name()) {
return true;
}
}
}
return false;
}
/**
* Excel
*
* @return
* @throws IOException
*/
public byte[] getBytes() throws IOException {
XSSFWorkbook workbook = getExcel(false);
if (workbook != null) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
return outputStream.toByteArray();
}
return null;
}
public XSSFWorkbook getExcel(boolean flag) {
XSSFWorkbook workbook = new XSSFWorkbook();
//---------- 创建样式 ------------------
CellStyle headCellStyle = new HeadCellStyle(workbook).getStyle();
CellStyle errorCellStyle = new ErrorCellStyle(workbook).getStyle();
CellStyle errorNumberCellStyle = new ErrorNumberCellStyle(workbook).getStyle();
CellStyle normalCellStyle = new NormalCellStyle(workbook).getStyle();
CellStyle normalNumberCellStyle = new NormalNumberCellStyle(workbook).getStyle();
CellStyle checkMessageCellStyle = new CheckMessageCellStyle(workbook).getStyle();
CellStyle checkFailureCellStyle = new CheckFailureCellStyle(workbook).getStyle();
CellStyle checkSuccessCellStyle = new CheckSuccessCellStyle(workbook).getStyle();
//----------- 创建字体 ----------------
Font normalFont = new NormalFont(workbook).getFont();
Font redFont = new RedFont(workbook).getFont();
//创建一个Sheet表
XSSFSheet sheet = workbook.createSheet(name);
sheet.setDefaultRowHeightInPoints(20);
Row firstRow = sheet.createRow(0); // 下标为0的行开始
XSSFDrawing drawing = sheet.createDrawingPatriarch();
//----------------表头--------------------
// if (flag) {
// // 检查结果栏
// org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(0);
// String columnName = WSheet.CHECK_STATUS_NAME;
// firstCell.setCellStyle(headCellStyle);
// firstCell.setCellValue(new XSSFRichTextString(columnName));
// sheet.setColumnWidth(0, (4 + 8) * 256);
// }
// 数据栏
int hiddenNumber = 0;
for (int j = 0; j < this.columnList.size(); j++) {
WColumn column = this.columnList.get(j);
Field field = column.getField();
if (column.isHidden()) {
hiddenNumber++;
continue;
}
int k = j - hiddenNumber;
if (flag) {
k++;
}
org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(k);
String columnName = column.getName();
XSSFRichTextString textString;
if (column.isRequired()) {
textString = new XSSFRichTextString("*" + columnName);
textString.applyFont(0, 1, redFont);
textString.applyFont(1, textString.length(), normalFont);
} else {
textString = new XSSFRichTextString(columnName);
textString.applyFont(normalFont);
}
StringBuilder sb = new StringBuilder();
sb.append(column.getDescription()).append("\n");
// 添加数据说明信息。
if (field.isAnnotationPresent(ColumnDescription.class)) {
// 获取声明字段上的Description信息。
ColumnDescription columnDescription = field.getAnnotation(ColumnDescription.class);
sb.append(columnDescription.value());
sb.append("\n");
}
// 如果填写了注释信息
if (sb.length() > 1) {
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6);
XSSFComment comment = drawing.createCellComment(anchor);
comment.setString(sb.toString());
firstCell.setCellComment(comment);
}
firstCell.setCellValue(textString);
firstCell.setCellStyle(headCellStyle);
sheet.setColumnWidth(k, (4 + column.getCellWidth()) * 256);
}
// 错误消息栏
// if (flag) {
// org.apache.poi.ss.usermodel.Cell firstCell = firstRow.createCell(table.getColumnIndex() + 1 - hiddenNumber);
// String columnName = WSheet.CHECK_STATUS_RESULT;
// firstCell.setCellStyle(headCellStyle);
// firstCell.setCellValue(new XSSFRichTextString(columnName));
// sheet.setColumnWidth(table.getColumnIndex() + 1, (4 + 10) * 256);
// }
// 冻结第一行
//sheet.createFreezePane(255,1);
//------------------数据--------------------
for (int i = 0; i < this.rowList.size(); i++) {
Row row = sheet.createRow(i + 1);
boolean rowFlag = true;
//如果该行有错误
// if (flag) {
// org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(0);
// if (table.getRowError(i) != null) {
// rowFlag = false;
// xssfCell.setCellValue("不通过");
// xssfCell.setCellStyle(checkFailureCellStyle);
// } else {
// xssfCell.setCellValue("通过");
// xssfCell.setCellStyle(checkSuccessCellStyle);
// }
// }
int j = 0;
hiddenNumber = 0;
for (; j < this.columnList.size(); j++) {
WColumn column = this.columnList.get(j);
if (column.isHidden()) {
hiddenNumber++;
continue;
}
int k = j - hiddenNumber;
if (flag) {
k++;
}
org.apache.poi.ss.usermodel.Cell xssfCell = row.createCell(k);
WCell WCell = this.rowList.get(i).get(column.getName());
if (null == WCell) {
continue;
}
String value = WCell.getValue();
xssfCell.setCellValue(value);
// 如果该列是数字类型,则靠右
// if (table.getWColumns()[j].getDataType() == DataType.DECIMAL
// || table.getWColumns()[j].getDataType() == DataType.NUMBER) {
// if (flag && !WCell.getStatus().equals(Status.PASS)) {
// xssfCell.setCellStyle(errorNumberCellStyle);
// } else {
// xssfCell.setCellStyle(normalNumberCellStyle);
// }
// } else {
// if (flag && !WCell.getStatus().equals(Status.PASS)) {
// xssfCell.setCellStyle(errorCellStyle);
// } else {
// xssfCell.setCellStyle(normalCellStyle);
// }
// }
}
// if (flag && !rowFlag) {
// Cell xssfCell = row.createCell(j + 1 - hiddenNumber);
// xssfCell.setCellValue(table.getRowError(i));
// xssfCell.setCellStyle(checkMessageCellStyle);
// }
}
return workbook;
}
}

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

@ -3,15 +3,14 @@ package com.wb.excel.api.annotation;
import java.lang.annotation.*;
/**
* Created on 2014/9/24.
* target
*
* @author
* @version v1.0.0.0
* @author
* @version v0.0.1
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoRepeat {
String value() default "";
public @interface Converter {
Class target();
}

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

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

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

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

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

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

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class BooleanConverter implements Converter<Boolean> {
@Override
public Boolean convert(String var) {
try {
return Boolean.parseBoolean(var);
} catch (Exception e) {
return false;
}
}
@Override
public String string(Boolean var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class ByteConverter implements Converter<Byte> {
@Override
public Byte convert(String var) {
try {
return Byte.parseByte(var);
} catch (Exception e) {
return 0;
}
}
@Override
public String string(Byte var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class CharacterConverter implements Converter<Character> {
@Override
public Character convert(String var) {
if (var == null || var.equals("")) {
return '0';
} else {
return var.charAt(0);
}
}
@Override
public String string(Character var) {
if (var == null) {
return "";
}
return String.valueOf(var).trim();
}
}

@ -0,0 +1,9 @@
package com.wb.excel.api.converter;
public interface Converter<T> {
T convert(String var);
String string(T var);
}

@ -0,0 +1,44 @@
package com.wb.excel.api.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<Date> {
@Override
public Date convert(String var) {
if (var == null) {
return null;
}
Date date = null;
try {
var = var.trim();
if (var.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(var);
} else if (var.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(var);
} else if (var.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(var);
} else if (var.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(var);
}
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
@Override
public String string(Date var) {
if (var == null) {
return "";
}
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(var);
}
}

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class DoubleConverter implements Converter<Double> {
@Override
public Double convert(String var) {
try {
return Double.parseDouble(var);
} catch (Exception e) {
return 0d;
}
}
@Override
public String string(Double var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class FloatConverter implements Converter<Float> {
@Override
public Float convert(String var) {
try {
return Float.parseFloat(var);
} catch (Exception e) {
return 0f;
}
}
@Override
public String string(Float var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class IntegerConverter implements Converter<Integer> {
@Override
public Integer convert(String var) {
try {
return Integer.parseInt(var);
} catch (Exception e) {
return 0;
}
}
@Override
public String string(Integer var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class LongConverter implements Converter<Long> {
@Override
public Long convert(String var) {
try {
return Long.parseLong(var);
} catch (Exception e) {
return 0L;
}
}
@Override
public String string(Long var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,21 @@
package com.wb.excel.api.converter;
public class ShortConverter implements Converter<Short> {
@Override
public Short convert(String var) {
try {
return Short.parseShort(var);
} catch (Exception e) {
return 0;
}
}
@Override
public String string(Short var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

@ -0,0 +1,17 @@
package com.wb.excel.api.converter;
public class StringConverter implements Converter<String> {
@Override
public String convert(String var) {
return var;
}
@Override
public String string(String var) {
if (var == null) {
return "";
}
return String.valueOf(var);
}
}

File diff suppressed because it is too large Load Diff

@ -1,83 +0,0 @@
package com.wb.excel.api.enumeration;
import com.wb.excel.api.annotation.ColumnDescription;
import com.wb.excel.api.annotation.ColumnName;
import com.wb.excel.api.datatable.WCell;
import com.wb.excel.api.util.EnumUtil;
import com.wb.excel.api.util.StringUtil;
import com.wb.excel.api.util.ValidationUtil;
/**
* DataTable11<br/>
* DataTable
* Created on 2014/9/19/.
*
* @author
* @version v1.0.0.0
*/
public enum DataType {
@ColumnName("字符型")
@ColumnDescription("普通的字符串类型例如abc123.,!@#")
STRING,
@ColumnName("整数型")
@ColumnDescription("整数类型,小数点后的数字会被抹去(不是四舍五入),例如112004000")
NUMBER,
@ColumnName("数字类型")
@ColumnDescription("可以带小数点的数字类型例如1.001.01")
DECIMAL,
@ColumnName("日期型")
@ColumnDescription("普通的日期类型例如2014-10-01")
DATE,
@ColumnName("时间日期型(秒)")
@ColumnDescription("时间精确到秒的日期类型例如2014-10-01 10:30:00")
DATETIME,
@ColumnName("是否型")
@ColumnDescription("指定是或者否的类型,例如:是,否")
BOOLEAN;
/**
* .
*
* @param type
* @param WCell
* @param value
* @return truefalse
*/
public static boolean check(DataType type, WCell WCell, String value) {
boolean typeFlag = true;
if (value.length() > 0) {
switch (type) {
case DECIMAL:
typeFlag = ValidationUtil.checkDouble(value);
break;
case NUMBER:
typeFlag = ValidationUtil.checkInteger(value);
if (typeFlag) {
WCell.setValue(StringUtil.transferInteger(value));
}
break;
case DATE:
typeFlag = ValidationUtil.checkDate(value);
if (typeFlag) {
WCell.setValue(StringUtil.transferDate(value));
}
break;
case DATETIME:
typeFlag = ValidationUtil.checkDatetime(value);
if (typeFlag) {
WCell.setValue(StringUtil.transferDatetime(value));
}
break;
case BOOLEAN:
typeFlag = EnumUtil.check(YesNo.class, value);
if (typeFlag) {
WCell.setValue(StringUtil.transferBoolean(value));
}
break;
default:
break;
}
}
return typeFlag;
}
}

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

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

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

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

@ -1,7 +1,5 @@
package com.wb.excel.api.util;
import org.apache.poi.hpsf.Constants;
/**
* ***************************************************************
* <p>
@ -39,6 +37,7 @@ public class StringUtils {
}
return true;
}
public static boolean isNotEmpty(String value) {
int strLen;
if (value == null || (strLen = value.length()) == 0) {

@ -1,8 +1,5 @@
package com.wb.excel.api.util;
import com.wb.excel.api.enumeration.YesNo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@ -63,17 +60,6 @@ public class TransferUtil {
}
}
public static Boolean transferBoolean(String value) {
String key = EnumUtil.getKey(YesNo.class, value);
if (key.equals("Y")) {
return true;
} else if (key.equals("N")) {
return false;
} else {
return null;
}
}
public static Long transferLong(String value) {
try {
Double d = Double.parseDouble(value);

@ -1,16 +1,12 @@
package com.wb.excel.api.util;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@ -1,8 +1,5 @@
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.WSheet;
import com.wb.excel.api.exception.TemplateNotMatchException;
import jdk.nashorn.internal.parser.JSONParser;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
@ -16,10 +13,20 @@ import java.util.List;
public class ExampleTest {
public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
// testExport();
testTemplate();
testExport();
testImport();
}
public static void testTemplate() {
try {
WSheet WSheet = new WSheet<>(User.class);
output("user_template.xlsx", WSheet.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testExport() {
try {
@ -27,21 +34,24 @@ public class ExampleTest {
List<User> pos = new ArrayList();
User user = new User();
user.setName("张三");
user.setWz("张三");
user.setDate(new Date());
user.setAge(20);
user.setSex(YesNo.Y);
user.setBr(true);
user.setBt((byte) 1);
user.setZf('A');
user.setDzs((short) 1);
user.setZs(1);
user.setCzs((long) 1);
user.setFd(1.0f);
user.setSjd(1.0);
pos.add(user);
pos.add(user);
//第二步,初始化数据
WSheet WSheet = new WSheet(pos);
//第三步,初始化Excel
WExcel WExcel = new WExcel(false, WSheet);
WSheet<User> WSheet = new WSheet<>(pos);
//第四步导出xlsx文件
output("user.xlsx", WExcel.getBytes());
output("user.xlsx", WSheet.getBytes());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IOException e) {
@ -64,8 +74,8 @@ public class ExampleTest {
WSheet WSheet = new WSheet(bytes, User.class);
if (WSheet.hasError()) {
WExcel WExcel = new WExcel(true, WSheet);
output("user_err.xlsx", WExcel.getBytes());
// WExcel WExcel = new WExcel(true, WSheet);
// output("user_err.xlsx", WExcel.getBytes());
} else {
List<User> list = WSheet.transferList(User.class);
System.out.println("本次读取数据" + list.size() + "条!");
@ -113,4 +123,5 @@ public class ExampleTest {
}
}
}

@ -1,32 +1,38 @@
import com.wb.excel.api.annotation.ColumnName;
import com.wb.excel.api.annotation.Enum;
import com.wb.excel.api.annotation.SheetName;
import com.wb.excel.api.enumeration.YesNo;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
@SheetName("用户")
public class User {
@NotNull
@ColumnName("姓名")
private String name;
@ColumnName("出生日期时间")
@ColumnName("文字")
private String wz;
@ColumnName("日期时间")
private Date date;
@ColumnName("年纪")
private int age;
@Enum(target = YesNo.class)
@ColumnName("性别")
private YesNo sex;
@ColumnName("布尔")
private boolean br;
@ColumnName("比特")
private byte bt;
@ColumnName("字符")
private char zf;
@ColumnName("短整数")
private short dzs;
@ColumnName("整数")
private int zs;
@ColumnName("长整数")
private long czs;
@ColumnName("浮点")
private float fd;
@ColumnName("双精度")
private double sjd;
public String getName() {
return name;
public String getWz() {
return wz;
}
public void setName(String name) {
this.name = name;
public void setWz(String wz) {
this.wz = wz;
}
public Date getDate() {
@ -37,24 +43,72 @@ public class User {
this.date = date;
}
public int getAge() {
return age;
public boolean isBr() {
return br;
}
public void setAge(int age) {
this.age = age;
public void setBr(boolean br) {
this.br = br;
}
public YesNo getSex() {
return sex;
public byte getBt() {
return bt;
}
public void setSex(YesNo sex) {
this.sex = sex;
public void setBt(byte bt) {
this.bt = bt;
}
public char getZf() {
return zf;
}
public void setZf(char zf) {
this.zf = zf;
}
public short getDzs() {
return dzs;
}
public void setDzs(short dzs) {
this.dzs = dzs;
}
public int getZs() {
return zs;
}
public void setZs(int zs) {
this.zs = zs;
}
public long getCzs() {
return czs;
}
public void setCzs(long czs) {
this.czs = czs;
}
public float getFd() {
return fd;
}
public void setFd(float fd) {
this.fd = fd;
}
public double getSjd() {
return sjd;
}
public void setSjd(double sjd) {
this.sjd = sjd;
}
@Override
public String toString() {
return "" + name + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + age + sex;
return String.valueOf(this.zf);
}
}

Loading…
Cancel
Save

Powered by TurnKey Linux.