导出到Excel通用类

项目中经常要将数据导出到excel,于是我做了一个通用的类,发出来共享一下,大家用得上的话就好。

 

这个是通用的类代码:

参数1:标题列的数组

参数2:一个集合,也就是你所要导出的内容

参数3:要导出数据的原型实体类

package com.origin.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
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;

public class ExportExcel<T> {
	
	/**
	 * 导出到Excel方法
	 * @param title String[] 标题数组
	 * @param list 需要导出的数据
	 * @param model 
	 */
	public InputStream execute(String[] title,List<T> list,Object model){
		HSSFWorkbook wk=new HSSFWorkbook();
		HSSFSheet sheet=wk.createSheet("sheet1");
		
		HSSFRow row=sheet.createRow(0);
		
		HSSFCell cell;
		
		for(int i=0;i<title.length;i++){
			cell=row.createCell((short)i);
			cell.setCellValue(new HSSFRichTextString(title[i]));
		}
		
		for (int i = 0; i < list.size(); ++i)
		{
			model=list.get(i);
			row=sheet.createRow(i+1);
			Method[] method = model.getClass().getMethods();
			int num=0;
			for(int j=0;j<method.length;j++){			
				if(method[j].getName().substring(0, 3).equals("get") && method[j].getName()!="getClass"){
					Method m;
					try {
						m = model.getClass().getMethod(method[j].getName());
						Object result = m.invoke(model);
						cell=row.createCell((short)num++);
						if(result!=null){
							cell.setCellValue(new HSSFRichTextString(result.toString()));
						}else
						{
							cell.setCellValue(new HSSFRichTextString("-"));
						}
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
			
		}
		ByteArrayOutputStream os=new ByteArrayOutputStream();
		
		try {
			wk.write(os);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		byte[] content=os.toByteArray();
		
		InputStream is=new ByteArrayInputStream(content);
		try {
			os.flush();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return is;
		
	}
}

 

你可能感兴趣的:(java,apache,Excel,OS,J#)