您的位置:首页 > 其它

Excle导入导出简单的封装

2018-02-07 11:34 337 查看
package com.peng.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;

import com.peng.bean.book;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

//excle通用导入导出
public class ExcleUtil {
//导出  将一个List导出到str路径下
public void excleOut(ArrayList ar,String str) {
WritableWorkbook book=null;
try {
book=Workbook.createWorkbook(new File(str));
WritableSheet sheet=book.createSheet("sheet", 0);
for(int i=0;i<ar.size();i++) {
Object ob=ar.get(i);
Class cl=ob.getClass();
Field[] fi=cl.getDeclaredFields();
for(int j=0;j<fi.length;j++) {
fi[j].setAccessible(true);
Label la=new Label(j,i,String.valueOf(fi[j].get(ob)));
sheet.addCell(la);
}

}
book.write();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
book.close();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

//导入Class需要一个实体类,str为路径
public ArrayList excleIn(Class cl,String str) {
ArrayList ar=new ArrayList();
Workbook book=null;
try {
book=Workbook.getWorkbook(new File(str));
Sheet sheet=book.getSheet(0);
Field[] fi=cl.getDeclaredFields();
for(int i=0;i<sheet.getRows();i++) {
Object ob=cl.newInstance();//创建实例化对象
for(int j=0;j<fi.length;j++) {
fi[j].setAccessible(true);
String con=sheet.getCell(j,i).getContents();
if(fi[j].getType().toString().equals("class java.lang.String")) {
fi[j].set(ob,con);
}else if(fi[j].getType().toString().equals("int")) {
fi[j].setInt(ob, Integer.valueOf(con));
}
}
ar.add(ob);

}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
book.close();
}
return ar;
}

//测试代码
public static void main(String[] args) {
ArrayList<book> ar=new ArrayList<book>();
book book=new book();
book.setId(1);
book.setName("斗破苍穹wwww");
book.setType("玄幻");
ar.add(book);
book book2=new book();
book2.setId(2);
book2.setName("天珠变qqq");
book2.setType("玄幻");
ar.add(book2);
ExcleUtil exc=new ExcleUtil();
exc.excleOut(ar, "e:/book1.xls");
ExcleUtil exc1=new ExcleUtil();
ArrayList<book> ar1=exc1.excleIn(book.class,"e:/book1.xls");

for(book bo2:ar1) {
System.out.println(bo2.getId()+bo2.getName()+bo2.getType());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: