java导出excel工具类

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;


import com.zstimes.riskManage.util.excel.annotation.ExcelThead;
import com.zstimes.riskManage.util.excel.exception.FileParseException;
import com.zstimes.util.DateUtil;
/**
 * 
 * @ClassName: ExcelExport 
 * @Description: 将数据(实体类)导出excel
 * @author: liyu
 * @date: 2017年11月10日 下午4:14:51
 */
public class ExcelExport {
public static <T> Workbook workbook(Collection<T> data, Class<T> type) {
HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();
Field[] fields = type.getDeclaredFields();

try {

Row row = sheet.createRow(0); 
for (int i=0;i<fields.length;i++) {
ExcelThead thead = fields[i].getAnnotation(ExcelThead.class);
Cell cell = row.createCell(i);
cell.setCellValue(thead != null ? thead.name() : "未命名");
}

int r = 1;
for (T e: data) {
setCont(sheet, e, fields, r++);
}

} catch (Exception cause) {
throw new FileParseException("数据写入错误", cause);
}
return workbook;

}


private static <T> void setCont(Sheet sheet,T data, Field[] fields, int rownum) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Row cont = sheet.createRow(rownum);
for (int j=0;j<fields.length;j++) {
String fname = fields[j].getName().substring(0, 1).toUpperCase()+fields[j].getName().substring(1);
Method method = data.getClass().getDeclaredMethod("get"+fname, new Class[]{});
Object ret = method.invoke(data, new Object[]{});
Cell cell = cont.createCell(j);
cell.setCellValue(toString(ret));
}
}

private static String toString(Object ret){
if(ret == null){
return "";
}else{
if(ret instanceof Date){
return DateUtil.date2Str((Date)ret, "yyyy-MM-dd");
}else if(ret instanceof BigDecimal)
return ((BigDecimal)ret).setScale(2, BigDecimal.ROUND_UP).toString();
else{
return ret.toString();
}
}
}

}


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelThead {
public String name();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值