您的位置:首页 > 其它

利用注解反射生成导出excel文件

2015-04-21 09:21 447 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">本文实现通过解析注解反射生成excel文件,导出excel使用poi.jar</span>

1,在项目中加入poi.jar。

2,定义注解

/**
* 导出excel注解
* 在成员变量上加该注解,表示需要导出
* name 列标题
* format 对date进行格式化
* cn.com.bizunited.base.utils.ExportUtil 进行解析并生成excel
* @author wish
*
*/
@Target ({ElementType.FIELD})
@Retention (RetentionPolicy.RUNTIME)
public @interface RowTitle {
public String name();
public String format() default "";
}


3,定义导出工具类,用于解析注解,将传入的实体集合转换为excel

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import cn.com.bizunited.base.annotation.RowTitle;

public class ExportUtil {
public static int maxRowNums=50000;//sheet最大行数
/**
* 根据list解析注解生成HSSFWorkbook
* @param list 导出的集合
* @return
* @throws Exception
*/
public static <T> HSSFWorkbook getHSSFWorkbook(List<T> list) throws Exception
{
if(list==null)
{
return null;
}
HSSFWorkbook wb = new HSSFWorkbook();
int sheetNum=(list.size()-1)/maxRowNums+1;//sheet数
HSSFSheet[] sheets=new HSSFSheet[sheetNum];
T t=list.get(0);
Class clazz=t.getClass();
List<String> titles=new ArrayList<String>();
Field[] fields=clazz.getDeclaredFields();
ArrayList<Field> effectFields=new ArrayList<Field>();
for (Field field : fields) {
RowTitle a=field.getAnnotation(RowTitle.class);
if(a!=null)
{
titles.add(a.name());//标题
effectFields.add(field);//要导出的属性
}
}
for (int i=0;i<sheets.length;i++) {
// 创建Excel的工作sheet,对应到一个excel文档的tab
sheets[i] = wb.createSheet("sheet"+(i+1));
HSSFRow rowTitle=sheets[i].createRow(0);
for (int j=0;j<titles.size();j++) {//遍历title,为excel首行设置标题
rowTitle.createCell(j).setCellValue(titles.get(j));
}
}
if(list.size()>0)
{
for (int k=0;k<list.size();k++) {
T l=list.get(k);
int index=k/maxRowNums;
HSSFRow row=sheets[index].createRow(k%maxRowNums+1);
for (int i=0;i<effectFields.size();i++) {
Field field=effectFields.get(i);
setValueToCell(field, l, row, i);
}
}
}
return wb;
}

/**
* 填充内容到单元格
* @param field 属性
* @param l 实体
* @param row 行
* @param cellIndex 列下标
* @throws Exception
*/
private static <T> void setValueToCell(Field field,T l,HSSFRow row,int cellIndex) throws Exception
{
Class clazz=l.getClass();
RowTitle a=field.getAnnotation(RowTitle.class);
if(a==null)//如果没有RowTitle注解,跳过该字段
{
return;
}
Type fieldType=field.getGenericType();
String fieldName=field.getName();
fieldName=fieldName.substring(0, 1).toUpperCase()+fieldName.replaceFirst("\\w","");//将首字母转换为大写
Method method=clazz.getMethod("get"+fieldName);
if(fieldType.toString().equals("class java.lang.Integer")|| fieldType.toString().equals("int"))
{
Integer value=(Integer)method.invoke(l);
if(value!=null)
{
row.createCell(cellIndex).setCellValue(value);
}
}else if(fieldType.toString().equals("class java.lang.String"))
{
String value=(String)method.invoke(l);
if(value!=null)
{
row.createCell(cellIndex).setCellValue(value);
}
}else if(fieldType.toString().equals("class java.lang.Long")||fieldType.toString().equals("long"))
{
Long value=(Long)method.invoke(l);
if(value!=null)
{
row.createCell(cellIndex).setCellValue(value);
}
}else if(fieldType.toString().equals("class java.lang.Float")||fieldType.toString().equals("float"))
{
Float value=(Float)method.invoke(l);
if(value!=null)
{
row.createCell(cellIndex).setCellValue(value);
}
}else if(fieldType.toString().equals("class java.lang.Double")||fieldType.toString().equals("double"))
{
Double value=(Double)method.invoke(l);
if(value==null)
{
return;
}
if(!"".equals(a.format()))
{
DecimalFormat df = new DecimalFormat(a.format());
row.createCell(cellIndex).setCellValue(df.format(value));
}else{
row.createCell(cellIndex).setCellValue(value);
}
}else if(fieldType.toString().equals("class java.util.Date")||
fieldType.toString().equals("class java.sql.Timestamp"))
{	if("".equals(a.format()))
{
Date value=(Date)method.invoke(l);
if(value!=null)
{
row.createCell(cellIndex).setCellValue(value);
}
}else
{
String format=a.format();
SimpleDateFormat sdf=new SimpleDateFormat(format);
Date value=(Date)method.invoke(l);
if(value!=null)
{
row.createCell(cellIndex).setCellValue(sdf.format(value));
}
}
}

}
}


4,测试,在实体上加上注解

import java.util.Date;

public class User {
@RowTitle(name="编号")
private Integer code;
@RowTitle(name="姓名")
private String name;
@RowTitle(name="性别")
private String sex;
@RowTitle(name="百分数(%)",format="##.00%")
private double  percent;
@RowTitle(name="生日",format="yyyy-MM-dd")
private Date birthDate;
}
生成并导出excel
<pre name="code" class="java">@RequestMapping("export")
public void <span style="font-family: Arial, Helvetica, sans-serif;">export</span>
(HttpServletRequest request,HttpServletResponse response,
Integer bscId,String ckNumber,String month) throws Exception
{
List<User> users=userService.getUsers();
HSSFWorkbook wb=ExportUtil.getHSSFWorkbook(users);

String filename = smonth+"用户信息.xls";//设置下载时客户端Excel的名称
if(request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0
||request.getHeader("User-Agent").toLowerCase().indexOf("chrome") > 0)
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
else if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)
filename = URLEncoder.encode(filename, "UTF-8");//IE浏览器
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename=" +filename);
OutputStream os=response.getOutputStream();
wb.write(os);
os.flush();
os.close();
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel 注解 反射
相关文章推荐