一般情况下只需要简单的三步,就可以实现导入和导出了,要是你使用了hibernate,就会发现太方便了
一:
构造输入输出流 如: OutputStream out = new FileOutputStream("D://testOne.xls");
二,构造导入导出对象 如: ExcelExport<Testpojo> ex = new ExcelExport<Testpojo>();
三,操作 ex.exportExcel("测试", list, out);
当然,因为操作数据都是Connection接口的,所以,你可以在导入
导出之前对数据进行过滤、排序、分组等,到时候动态的传进去就可以了,实在非常的方便,废话不多说,直接上代码:
package com.yingchao.kgou.controller;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
public class ExcelStyle {
public static HSSFCellStyle setHeadStyle(HSSFWorkbook workbook ,HSSFCellStyle style)
{
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样样式
style.setFont(font);
return style;
}
public static HSSFCellStyle setbodyStyle(HSSFWorkbook workbook ,HSSFCellStyle style2)
{
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成字体
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样样式
style2.setFont(font2);
return style2;
}
}
package com.yingchao.kgou.controller;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import com.yingchao.kgou.bean.ExcelAnnotation;
import com.yingchao.kgou.entity.Item;
@Controller
public class ExportExcel<T> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化日期
/**
* 导出excel
* @param title标题
* @param dataset集合
* @param out输出流
* @return
* @throws Exception
*/
/**
*
* @param title 标题
* @param dataset 集合
* @param out 输出流
*/
public void exportExcel(String title, Collection<T> dataset,
OutputStream out) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化日期
// 声明一个工作薄
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);
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
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(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(exportfieldtile.get(i));
cell.setCellValue(text);
}
int index = 0;
// 循环整个集合
its = dataset.iterator();
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(k);
Method getMethod=methodObj.get(k);
Object value = getMethod.invoke(t, new Object[] {});
String textValue = getValue(value);
cell.setCellValue(textValue);
}
}
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "static-access" })
private String getValue(Object value) throws ParseException{
String textValue = "";
if(null == value){
return textValue;
}
if(value instanceof Boolean){
boolean bValue = (Boolean)value;
textValue = "是";
if(!bValue){
textValue="否";
}
}else if(value instanceof GregorianCalendar){
GregorianCalendar calendar = (GregorianCalendar)value;
Date d = calendar.getTime();
textValue = sdf.format(d);
}else{
textValue = value.toString();
}
return textValue;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
//构造一个模拟的List来测试,实际使用时,这个集合是从数据库中查出来的
List<Item> list = new ArrayList<Item>();
for (int i = 0; i < 10; i++) {
Item item = new Item();
item.setTitle("商品"+i);
item.setItemcode(String.valueOf(i));
item.setItemdesc("描述"+i);
item.setCreated(Calendar.getInstance());
item.setDelistTime(Calendar.getInstance());
item.setListTime(Calendar.getInstance());
item.setModified(Calendar.getInstance());
item.setPrice(100d);
item.setMarketprice(100d);
item.setSellprice(100d);
item.setScore(5f);
item.setItempoint(1000);
item.setIsTiming(Boolean.TRUE);
item.setStorecount(Long.valueOf(i));
item.setAdminUid(Long.valueOf(i));
item.setAdminUpt(Long.valueOf(i));
item.setPicUrl("ff");
item.setState(i);
list.add(item);
}
//构造输出对象,可以从response输出,直接向用户提供下载
OutputStream out = new FileOutputStream("E:\\testOne.xls");
//开始时间
Long l = System.currentTimeMillis();
//注意
new ExportExcel().exportExcel("测试",list, out);
out.close();
//结束时间
Long s = System.currentTimeMillis();
System.out.println("总共耗时:"+(s-l));
}
}
package com.yingchao.kgou.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import com.yingchao.kgou.bean.ExcelAnnotation;
import com.yingchao.kgou.entity.Item;
public class ImportExcel<T> {
private Class<T> classzz;
public ImportExcel(Class<T> classzz){
this.classzz=classzz;
}
/**
* 导入excel
* @param file
* @param pattern
* @return
*/
public Collection<T> importExcel(InputStream in,String...pattern){
Collection<T> dist = new ArrayList<T>();
try {
/*
* 类反射得到调用方法
*/
//得到目标类的所有字段列表
Field[] field = classzz.getDeclaredFields();
//将所有标有annotation的字段,也就是允许导入数据的字段,放入到一个中
Map fieldMap = new HashMap();
//循环读取所有字段
for (int i = 0; i < field.length; i++) {
Field f = field[i];
//得到单个字段上的Annotation
ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
//如果标识了Annotation的话
if(null != exa){
//构造设置了Annotation的字段的setter方法
String fieldName = f.getName();
String setMethodName = "set"+fieldName.substring(0,1).toUpperCase()
+fieldName.substring(1);
//构造调用的method
Method method = classzz.getMethod(setMethodName, new Class[]{
f.getType()
});
//将这个method以annotation的名字为key来存入
fieldMap.put(exa.exportName(), method);
}
}
/*
* excel的解析开始
*/
//得到工作表
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++;
}
/*
* 解析内容行
*/
//用来格式化日期的DateFormat
SimpleDateFormat sf;
if (pattern.length < 1) {
sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else
sf = new SimpleDateFormat(pattern[0]);
while(row.hasNext()){
//标题下的第一行
Row rown = row.next();
//行的所有列
Iterator<Cell> cellBody = rown.cellIterator();
//得到传入类的实例
T tObject = classzz.newInstance();
int k = 0;
//遍历一行的列
while(cellBody.hasNext()){
Cell cell = cellBody.next();
//这里得到此列对应的标题
String titleString = (String)titleMap.get(k);
//如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的setter方法,进行设值
if(fieldMap.containsKey(titleString)){
Method setMethod = (Method)fieldMap.get(titleString);
//得到setter方法的参数
Type[] ts = setMethod.getGenericParameterTypes();
//只要一个参数
String xClass = ts[0].toString();
//判断参数类型
if(xClass.equals("class java.lang.String")){
setMethod.invoke(tObject, cell.getStringCellValue());
}else if(xClass.equals("class java.util.Calendar")){
Calendar c = new GregorianCalendar();
Date d = sf.parse(cell.getStringCellValue());
c.setTime(d);
setMethod.invoke(tObject, c);
}else if(xClass.equals("class java.lang.Boolean")){
Boolean boolName = true;
if(cell.getStringCellValue().equals("否")){
boolName = false;
}
setMethod.invoke(tObject, boolName);
}else if(xClass.equals("class java.lang.Integer")){
setMethod.invoke(tObject, new Integer(cell.getStringCellValue()));
}else if(xClass.equals("class java.lang.Long")){
setMethod.invoke(tObject, new Long(cell.getStringCellValue()));
}else if(xClass.equals("class java.lang.Double")){
setMethod.invoke(tObject, new Double(cell.getStringCellValue()));
}
}
//下一列
k++;
}
dist.add(tObject);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dist;
}
public static void main(String[] args) throws FileNotFoundException {
// ImportExcel<Item> test = new ImportExcel<Item>(Item.class);
// File file = new File("E:\\testOne.xls");
// Long befor = System.currentTimeMillis();
// final List<Item> result = (ArrayList<Item>)test.importExcel(new FileInputStream(file));
// Long after = System.currentTimeMillis();
// System.out.println("此次操作共耗时:"+(after-befor));
//
// new Thread(){
// public void run() {
// for (int i = 0; i < result.size(); i++) {
// final Item item = result.get(i);
// System.out.println("导入的信息为:"+item.getTitle()+"\t"+new SimpleDateFormat("yyyy-MM-ss HH:mm:ss").format(item.getListTime().getInstance().getTime()));
// }
// };
// }.start();
//
}
}