导出excel

package com.poi.excel;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.apache.poi.hssf.util.HSSFColor;



/**
 * 这是一个通用的excel导出帮助类,通过javabean反射
 * @author Mr.zhang
 *
 * @param <T>
 */
public class ExcelUtil<T> {

    public ExcelUtil(String title,String [] heads,List<T> dataSet,OutputStream out,String pattern){
        exportExcel(title, heads, dataSet, out,pattern);
    }

    public ExcelUtil(){}


    /**
     * 
     * @param tital
     *          表格文件名
     * @param heads
     *          表格标题
     * @param dataSet
     *          数据集
     * @param out
     *          输出IO
     * @param pattern
     *          格式化日期格式
     */
    @SuppressWarnings("unchecked")
    public void exportExcel(String title,String [] heads,List<T> dataSet,OutputStream out,String pattern){
        //新建一个book
        HSSFWorkbook book = new HSSFWorkbook();
        //新建一个sheet
        HSSFSheet sheet = book.createSheet(title);
        //设置表格默认列宽度为15个字符
        sheet.setDefaultColumnWidth(15);
        //新建标题行
        HSSFRow row = sheet.createRow((int)0);
        //新建单元格样式
        HSSFCellStyle style = book.createCellStyle();

        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 = book.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //将字体设置到样式中
        style.setFont(font);







        HSSFCellStyle style2 = book.createCellStyle();
        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 = book.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);



        for(int i=0;i<heads.length;i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(heads[i]);//将标题内容进行转换
            cell.setCellValue(text);
        }

        //开始将dataSet 放到表格中
        for(int k=0;k<dataSet.size();k++){
            row = sheet.createRow(k+1);
            T t = dataSet.get(k);
            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            for(int j=0;j<fields.length;j++){
                HSSFCell cell = row.createCell(j);
                cell.setCellStyle(style2);
                Field field = fields[j];
                String fieldName = field.getName();//得到属性名
                String getMethodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);//得到每个属性的get方法
                String textValue = null;
                try {
                    Class  tclass = t.getClass();
                    Method getMethod = tclass.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    if(value instanceof Date){
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        textValue = sdf.format(date);
                    }else if(value==null||value==""){
                        textValue = "";
                    }else{
                        // 其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                    }
                    // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
                    if(textValue!=null){
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if(matcher.matches()){
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        }else{
                            HSSFRichTextString text = new HSSFRichTextString(textValue);
                            cell.setCellValue(text);
                        }
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }

            }

        }
        try {
            book.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值