Java技术文章java专题Java学习笔记

给大家分享一个自己用的POI工具

2017-02-21  本文已影响418人  H_Man

最近业务涉及到了POI,特地总结了一份靠谱的POI导出Excel的工具,给大家分享一下

package com.meinong.util;
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.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
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;

/**
 * 利用开源组件POI3.0.2动态导出EXCEL文档 转载时请保留以下信息,注明出处!
 * 
 * @author h_man
 * @version v1.0
 * @param <T>
 *            应用泛型,代表任意一个符合javabean风格的类
 *            注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
 */
public class ExportExcel<T>
{
    public void exportExcel(String title ,String[] headers,Collection<T> dataset, OutputStream out)
    {
        exportExcel(title, headers, dataset,"yyyy-MM-dd HH:mm:ss", out, new ArrayList<String>());
    }
    public void exportExcel(String title ,String[] headers,Collection<T> dataset,String pattern, OutputStream out)
    {
        exportExcel(title, headers, dataset,pattern, out, new ArrayList<String>());
    }
    public void exportExcel(String title ,String[] headers,String pattern,Collection<T> dataset, OutputStream out,String notExpStr)
    {
        List<String> li = new ArrayList<String>();
        li.add(notExpStr);
        exportExcel(title, headers, dataset,pattern,out, li);
    }


    /**
     * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
     * 
     * @param title
     *            表格标题名
     * @param headers
     *            表格属性列名数组
     * @param dataset
     *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
     *            javabean属性的数据类型有基本数据类型及String,Date
     * @param out
     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd HH:mm:ss"
     * @param List<String> notExpStrs 不导出字段 集合         
     *             
     */
    @SuppressWarnings("unchecked")
    public void exportExcel(String title, String[] headers,
            Collection<T> dataset, String pattern, OutputStream out,List<String> li)
    {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.WHITE.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);
        //生成数据区域样式
        HSSFCellStyle style1 = workbook.createCellStyle();
        // 设置这些样式
        style1.setFillForegroundColor(HSSFColor.WHITE.index);
//      style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//      style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//      style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//      style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
//      style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 生成一个字体
//      HSSFFont font1 = workbook.createFont();
//              font.setColor(HSSFColor.VIOLET.index);
//      font.setFontHeightInPoints((short) 12);
//      font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
//      style.setFont(font);
        //-----
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++)
        {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        HSSFFont font3 = workbook.createFont();
        while (it.hasNext())
        {   
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            List<String> strFields = new ArrayList<String>();
            for(Field f :fields){
                if(!li.contains(f.getName()))
                    strFields.add(f.getName());
            }
            for (int i = 0; i < strFields.size(); i++)
            {
                HSSFCell cell = row.createCell(i);
//              cell.setCellStyle(style2);
//              Field field = fields[i];
                String fieldName = strFields.get(i);
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try
                {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName,
                            new Class[]
                            {});
                    Object value = getMethod.invoke(t, new Object[]
                    {});
                    String textValue =null;
                    // 判断值的类型后进行强制类型转换
                    if(value!=null){
                        if(value.toString().length()>=2)
                            if(value.toString().substring(0, 2).equals("0E"))
                                value = "0.00";
                        if (value instanceof Date)  
                        {   style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                            Date date = (Date) value;  
                            SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
                            textValue = sdf.format(date);  
                        } 
                        else
                            textValue = value.toString();
                    }
                    //利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null)
                    {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches())
                        {
                            style1.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
                            // 是数字当作double处理
                            cell.setCellStyle(style1);
                            cell.setCellValue(Double.parseDouble(textValue));
                        }
                        else
                        {
                            HSSFRichTextString richString = new HSSFRichTextString(
                                    textValue);
                            
//                          font3.setColor(HSSFColor.BLUE.index);
                            style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                            richString.applyFont(font3);
                            cell.setCellStyle(style1);
                            cell.setCellValue(richString);
                        }
                    }
                }
                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
        {
            workbook.write(out);
            workbook.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
//  private Field[] delNotExpStr(Field[] fields , String[] notExpStr){
//      if(notExpStr==null)
//          return fields;
//      else{
//          
//          return null;
//      }
//          
//  }

}
上一篇 下一篇

猜你喜欢

热点阅读