private List<String> titleList = new ArrayList<String>();
private List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
public Collection<T> importExcel(InputStream in, String... pattern) {
Collection<T> dist = new ArrayList();
try {
/**
* 类反射得到调用方法
*/
// 得到目标目标类的所有的字段列表
Field filed[] = clazz.getDeclaredFields();
// 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
Map fieldmap = new HashMap();
// 循环读取所有字段
for (int i = 0; i < filed.length; i++) {
Field f = filed[i];
// 得到单个字段上的Annotation
ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
// 如果标识了Annotationd的话
if (exa != null) {
// 构造设置了Annotation的字段的Setter方法
String fieldname = f.getName();
String setMethodName = "set"
+ fieldname.substring(0, 1).toUpperCase()
+ fieldname.substring(1);
// 构造调用的method,
Method setMethod = clazz.getMethod(setMethodName,
new Class[] { f.getType() });
// 将这个method以Annotaion的名字为key来存入。
fieldmap.put(exa.exportName(), setMethod);
}
}
/**
* excel的解析开始
*/
// 将传入的File构造为FileInputStream;
//FileInputStream in = new FileInputStream(file);
// // 得到工作表
HSSFWorkbook book = new HSSFWorkbook(in);
// // 得到第一页
HSSFSheet sheet = book.getSheetAt(0);
// // 得到第一面的所有行
Iterator<Row> row = sheet.rowIterator();
/**
* 标题解析
*/
// 得到第一行,也就是标题行
Row title = row.next();
// 得到第一行的所有列
Iterator<Cell> cellTitle = title.cellIterator();
// 将标题的文字内容放入到一个map中。
Map titlemap = new HashMap();
// 从标题第一列开始
int i = 0;
// 循环标题所有的列
while (cellTitle.hasNext()) {
Cell cell = cellTitle.next();
String value = cell.getStringCellValue();
titlemap.put(i, value);
i = i + 1;
}
/**
* 解析内容行
*/
while (row.hasNext()) {
// 标题下的第一行
Row rown = row.next();
// 行的所有列
Iterator<Cell> cellbody = rown.cellIterator();
// 得到传入类的实例
T tObject = clazz.newInstance();
int k = 0;
// 遍历一行的列
while (cellbody.hasNext()) {
Cell cell = cellbody.next();
// 这里得到此列的对应的标题
String titleString = (String) titlemap.get(k);
// 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
if (fieldmap.containsKey(titleString)) {
Method setMethod = (Method) fieldmap.get(titleString);
// 得到setter方法的参数
Type[] ts = setMethod.getGenericParameterTypes();
// 只要一个参数
String xclass = ts[0].toString();
String value = cell.getStringCellValue();
//根据替换规则替换相关值,如男->1
for(int m=0;m<titleList.size();m++)
{
String tmpTitle = titleList.get(m);
if(titleString.equals(tmpTitle))
{
String key = value;
value = String.valueOf(mapList.get(m).get(key));
}
}
this.invokeMethod(setMethod, tObject, xclass, value);
}
// 下一列
k = k + 1;
}
dist.add(tObject);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dist;
}
private void invokeMethod(Method setMethod, Object tObject, String xclass,
String value) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, ParseException {
if (xclass.equals("class java.lang.String")) {
setMethod.invoke(tObject, value);
} else if (xclass.equals("class java.util.Date")) {
// 用来格式化日期的DateFormat
SimpleDateFormat sf;
sf = new SimpleDateFormat("yyyy-MM-dd");
setMethod.invoke(tObject, sf.parse(value));
} else if (xclass.equals("class java.lang.Boolean")) {
Boolean boolname = true;
if (value.equals("否")) {
boolname = false;
}
setMethod.invoke(tObject, boolname);
} else if (xclass.equals("class java.lang.Integer")) {
setMethod.invoke(tObject, new Integer(value));
} else if (xclass.equals("class java.lang.Short")) {
setMethod.invoke(tObject, Short.valueOf(value));
}
else if (xclass.equals("class java.lang.Long")) {
setMethod.invoke(tObject, new Long(value));
}
}
public List<String> getTitleList() {
return titleList;
}
public void setTitleList(List<String> titleList) {
this.titleList = titleList;
}
public List<Map<String, Object>> getMapList() {
return mapList;
}
public void setMapList(List<Map<String, Object>> mapList) {
this.mapList = mapList;
}
} POI帮助我们能够利用java来处理excel,为了便于减少代码的重复性,我们将对excel的操作全部提取出来进行再度封装,能够方便调用。
主要分为五个java类:ExcelAnnotation.java;ExcelExport.java;ExcelStyle.java;ImportExcel.java;Testpojo.java
ExcelAnnotation.java:
ExcelExport.java
/**
* 作者:eya;QQ:1371392495,email:eya@eya.cc
* 欢迎转载;转载时请著名出处
* 导出List数据为excel
*/
public class ExcelExport<T> {
//格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private List<String> titleList = new ArrayList<String>();
private List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
/**
*
* @param title 标题
* @param dataset 集合
* @param out 输出流
*/
public void exportExcel(String title, Collection<T> dataset,
OutputStream out) {
// 声明一个工作薄
try {
//首先检查数据看是否是正确的
Iterator<T> its = dataset.iterator();
if (dataset == null || !its.hasNext() || title == null
|| out == null) {
throw new Exception("传入的数据不对!");
}
//取得实际泛型类
T ts = (T) its.next();
Class tCls = ts.getClass();
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short)15);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置标题样式
style = ExcelStyle.setHeadStyle(workbook, style);
// 得到所有字段
Field filed[] = ts.getClass().getDeclaredFields();
// 标题
List<String> exportfieldtile = new ArrayList<String>();
// 导出的字段的get方法
List<Method> methodObj = new ArrayList<Method>();
// 遍历整个filed
for (int i = 0; i < filed.length; i++) {
Field f = filed[i];
ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
// 如果设置了annottion
if (exa != null) {
String exprot = exa.exportName();
// 添加到标题
exportfieldtile.add(exprot);
// 添加到需要导出的字段的方法
String fieldname = f.getName();
String getMethodName = "get"
+ fieldname.substring(0, 1).toUpperCase()
+ fieldname.substring(1);
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
methodObj.add(getMethod);
}
}
// 产生表格标题行
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < exportfieldtile.size(); i++) {
HSSFCell cell = row.createCell((short)i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(
exportfieldtile.get(i));
cell.setCellValue(text);
}
int index = 0;
// 循环整个集合
while (its.hasNext()) {
//从第二行开始写,第一行是标题
index++;
row = sheet.createRow(index);
T t = (T) its.next();
for (int k = 0; k < methodObj.size(); k++) {
HSSFCell cell = row.createCell((short)k);
Method getMethod = methodObj.get(k);
Object value = getMethod.invoke(t, new Object[] {});
String textValue = getValue(value);
String titleString = (String) exportfieldtile.get(k);
//根据替换规则替换相关值,如1->男
for(int m=0;m<titleList.size();m++)
{
String tmpTitle = titleList.get(m);
if(titleString.equals(tmpTitle))
{
String key = textValue;
textValue = String.valueOf(mapList.get(m).get(key));
}
}
cell.setCellValue(textValue);
}
}
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getValue(Object value) {
return String.valueOf(value);
}
public List<String> getTitleList() {
return titleList;
}
public void setTitleList(List<String> titleList) {
this.titleList = titleList;
}
public List<Map<String, Object>> getMapList() {
return mapList;
}
public void setMapList(List<Map<String, Object>> mapList) {
this.mapList = mapList;
}
}
ExcelStyle.java
ImportExcel.java
private List<String> titleList = new ArrayList<String>();
private List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
public Collection<T> importExcel(InputStream in, String... pattern) {
Collection<T> dist = new ArrayList();
try {
/**
* 类反射得到调用方法
*/
// 得到目标目标类的所有的字段列表
Field filed[] = clazz.getDeclaredFields();
// 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
Map fieldmap = new HashMap();
// 循环读取所有字段
for (int i = 0; i < filed.length; i++) {
Field f = filed[i];
// 得到单个字段上的Annotation
ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
// 如果标识了Annotationd的话
if (exa != null) {
// 构造设置了Annotation的字段的Setter方法
String fieldname = f.getName();
String setMethodName = "set"
+ fieldname.substring(0, 1).toUpperCase()
+ fieldname.substring(1);
// 构造调用的method,
Method setMethod = clazz.getMethod(setMethodName,
new Class[] { f.getType() });
// 将这个method以Annotaion的名字为key来存入。
fieldmap.put(exa.exportName(), setMethod);
}
}
/**
* excel的解析开始
*/
// 将传入的File构造为FileInputStream;
//FileInputStream in = new FileInputStream(file);
// // 得到工作表
HSSFWorkbook book = new HSSFWorkbook(in);
// // 得到第一页
HSSFSheet sheet = book.getSheetAt(0);
// // 得到第一面的所有行
Iterator<Row> row = sheet.rowIterator();
/**
* 标题解析
*/
// 得到第一行,也就是标题行
Row title = row.next();
// 得到第一行的所有列
Iterator<Cell> cellTitle = title.cellIterator();
// 将标题的文字内容放入到一个map中。
Map titlemap = new HashMap();
// 从标题第一列开始
int i = 0;
// 循环标题所有的列
while (cellTitle.hasNext()) {
Cell cell = cellTitle.next();
String value = cell.getStringCellValue();
titlemap.put(i, value);
i = i + 1;
}
/**
* 解析内容行
*/
while (row.hasNext()) {
// 标题下的第一行
Row rown = row.next();
// 行的所有列
Iterator<Cell> cellbody = rown.cellIterator();
// 得到传入类的实例
T tObject = clazz.newInstance();
int k = 0;
// 遍历一行的列
while (cellbody.hasNext()) {
Cell cell = cellbody.next();
// 这里得到此列的对应的标题
String titleString = (String) titlemap.get(k);
// 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
if (fieldmap.containsKey(titleString)) {
Method setMethod = (Method) fieldmap.get(titleString);
// 得到setter方法的参数
Type[] ts = setMethod.getGenericParameterTypes();
// 只要一个参数
String xclass = ts[0].toString();
String value = cell.getStringCellValue();
//根据替换规则替换相关值,如男->1
for(int m=0;m<titleList.size();m++)
{
String tmpTitle = titleList.get(m);
if(titleString.equals(tmpTitle))
{
String key = value;
value = String.valueOf(mapList.get(m).get(key));
}
}
this.invokeMethod(setMethod, tObject, xclass, value);
}
// 下一列
k = k + 1;
}
dist.add(tObject);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dist;
}
private void invokeMethod(Method setMethod, Object tObject, String xclass,
String value) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, ParseException {
if (xclass.equals("class java.lang.String")) {
setMethod.invoke(tObject, value);
} else if (xclass.equals("class java.util.Date")) {
// 用来格式化日期的DateFormat
SimpleDateFormat sf;
sf = new SimpleDateFormat("yyyy-MM-dd");
setMethod.invoke(tObject, sf.parse(value));
} else if (xclass.equals("class java.lang.Boolean")) {
Boolean boolname = true;
if (value.equals("否")) {
boolname = false;
}
setMethod.invoke(tObject, boolname);
} else if (xclass.equals("class java.lang.Integer")) {
setMethod.invoke(tObject, new Integer(value));
} else if (xclass.equals("class java.lang.Short")) {
setMethod.invoke(tObject, Short.valueOf(value));
}
else if (xclass.equals("class java.lang.Long")) {
setMethod.invoke(tObject, new Long(value));
}
}
public List<String> getTitleList() {
return titleList;
}
public void setTitleList(List<String> titleList) {
this.titleList = titleList;
}
public List<Map<String, Object>> getMapList() {
return mapList;
}
public void setMapList(List<Map<String, Object>> mapList) {
this.mapList = mapList;
}
}
Testpojo.java
/**
* 作者:eya;QQ:1371392495,email:eya@eya.cc
* 欢迎转载;转载时请著名出处
*
*/
public class Testpojo {
//@ExcelAnnotation用来设置导出时候的列名,如果没有设置该列将不会被导出
@ExcelAnnotation(exportName = "用户名")
String username;
@ExcelAnnotation(exportName = "登录名")
String loginname;
@ExcelAnnotation(exportName = "年龄")
Integer age;
@ExcelAnnotation(exportName = "收入")
Long money;
@ExcelAnnotation(exportName = "时间")
Date createtime;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Long getMoney() {
return money;
}
public void setMoney(Long money) {
this.money = money;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}