您的位置:首页 > 编程语言 > Java开发

Java导出Excel

2015-09-01 11:24 477 查看
        <!-- 导出Excel -->

        <dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi</artifactId>

            <version>3.9</version>

        </dependency>

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

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.Collection;

import java.util.Date;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.Logger;

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;

/**

 * 利用开源组件POI3.0.2动态导出EXCEL文档!

 *

 * @author leno

 * @version v1.0

 * @param <T>

 *  
4000
          应用泛型,代表任意一个符合javabean风格的类

 *            注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()

 */

public class ExportExcel<T> {

    /**

     * log4j

     */

    private static final Logger logger = Logger.getLogger(ExportExcel.class);

    /**

     * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上

     *

     * @param title

     *            表格标题名

     * @param headers

     *            表格属性列名数组

     * @param dataset

     *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的

     *            javabean属性的数据类型有基本数据类型及String,Date

     * @param out

     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中

     * @param pattern

     *            如果有时间数据,设定输出格式。默认为"yyy-MM-dd"

     * @param noOut

     *            指定不需要输出的属性(数组格式)

     */

    public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern,

            String[] noOut) {

        try {

            // 声明一个工作薄

            HSSFWorkbook workbook = new HSSFWorkbook();

            // 生成一个表格

            HSSFSheet sheet = workbook.createSheet(title);

            sheet.setDefaultColumnWidth(15);

            // 设置表格默认列宽度为15个字节

            // 生成一个样式

            HSSFCellStyle style = workbook.createCellStyle();

            // 设置这些样式

            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            // 生成一个字体

            HSSFFont font = workbook.createFont();

            font.setFontHeightInPoints((short) 12);

            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

            // 把字体应用到当前的样式

            style.setFont(font);

            // 生成并设置另一个样式

            HSSFCellStyle style2 = workbook.createCellStyle();

            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            // 生成另一个字体

            HSSFFont font2 = workbook.createFont();

            font2.setFontHeightInPoints((short) 10);

            font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

            // 把字体应用到当前的样式

            style2.setFont(font2);

            // 产生表格标题行

            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;

            while (it.hasNext()) {

                index++;

                row = sheet.createRow(index);

                T t = (T) it.next();

                // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值

                Field[] fields = t.getClass().getDeclaredFields();

                HSSFCell cell = null;

                int count = 0;

                for (short i = 0; i < fields.length; i++) {

                    Field field = fields[i];

                    String fieldName = field.getName();

                    if ("id".equals(fieldName)) {

                        continue;

                    }

                    boolean flag = false;

                    if (null != noOut && noOut.length > 0) {

                        for (String string : noOut) {

                            if (string.equals(fieldName)) {

                                flag = true;

                                break;

                            } else {

                                cell = row.createCell(count);

                                cell.setCellStyle(style2);

                            }

                        }

                    }

                    if (flag) {

                        continue;

                    }

                    String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

                    Class<?> tCls = t.getClass();

                    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});

                    Object value = getMethod.invoke(t, new Object[] {});

                    // 判断值的类型后进行强制类型转换

                    String textValue = null;

                    if (value instanceof Integer) {

                        int intValue = (Integer) value;

                        cell.setCellValue(intValue);

                    } else if (value instanceof Long) {

                        long longValue = (Long) value;

                        cell.setCellValue(longValue);

                    } else if (value instanceof Date) {

                        Date date = (Date) value;

                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

                        textValue = sdf.format(date);

                    } else {

                        // 其它数据类型都当作字符串简单处理

                        if (value != null)

                            textValue = value.toString();

                        else {

                            textValue = "";

                        }

                    }

                    // 如果不是图片数据,就利用正则表达式判断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 richString = new HSSFRichTextString(textValue);

                            HSSFFont font3 = workbook.createFont();

                            richString.applyFont(font3);

                            cell.setCellValue(richString);

                        }

                    }

                    count++;

                }

            }

            workbook.write(out);

        } catch (SecurityException e) {

            logger.error("导出excel异常!", e);

        } catch (NoSuchMethodException e) {

            logger.error("导出excel异常!", e);

        } catch (IllegalArgumentException e) {

            logger.error("导出excel异常!", e);

        } catch (IllegalAccessException e) {

            logger.error("导出excel异常!", e);

        } catch (InvocationTargetException e) {

            logger.error("导出excel异常!", e);

        } catch (IOException e) {

            logger.error("导出excel异常!", e);

        } catch (Exception e) {

            logger.error("导出excel异常!", e);

        } finally {

            if (null != out) {

                try {

                    out.close();

                } catch (IOException e) {

                    logger.error("关闭OutputStream流异常!", e);

                }

            }

        }

    }

    /**

     * 导出Excel

     *

     * @param title

     *            SheetName

     * @param headers

     *            表格标题行

     * @param keys

     *            取Map中数据的Key

     * @param dataset

     *            原始数据

     * @throws Exception

     */

    public static InputStream exportExcelByMaps(String title, List<String> headers, List<String> keys,

            List<Map<String, Object>> dataMaps) throws Exception {

        ByteArrayOutputStream output = null;

        try {

            // 创建新的Excel工作簿

            HSSFWorkbook workbook = new HSSFWorkbook();

            HSSFSheet sheet = workbook.createSheet();

            // 在Excel工作簿中建一工作表

            if (StringUtils.isNotEmpty(title))

                sheet = workbook.createSheet(title);

            // 设置表格默认列宽度

            sheet.setDefaultColumnWidth(20);

            // 产生表格标题行

            HSSFRow row = sheet.createRow(0);

            HSSFFont font = workbook.createFont();

            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

            HSSFCellStyle style = workbook.createCellStyle();

            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            style.setFont(font);

            for (int i = 0; i < headers.size(); i++) {

                HSSFCell cell = row.createCell(i);

                cell.setCellStyle(style);

                cell.setCellValue(headers.get(i));

            }

            font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

            style.setFont(font);

            // 循环添加数据

            for (int i = 1; null != dataMaps && i <= dataMaps.size(); i++) {

                row = sheet.createRow(i);

                Map<String, Object> dataMap = dataMaps.get(i - 1);

                // 迭代数据

                int c = 0;

                for (String key : keys) {

                    HSSFCell cell = row.createCell(c);

                    String val = "";

                    if (null != dataMap.get(key))

                        val = dataMap.get(key).toString();

                    cell.setCellStyle(style);

                    cell.setCellValue(val);

                    c++;

                }

            }

            if (null == dataMaps || dataMaps.isEmpty()) {

                row = sheet.createRow(1);

                HSSFCell cell = row.createCell(0);

                cell.setCellStyle(style);

                cell.setCellValue("没有查找到对应的数据");

            }

            output = new ByteArrayOutputStream();

            workbook.write(output);

            byte[] ba = output.toByteArray();

            return new ByteArrayInputStream(ba);

        } catch (IOException e) {

            throw new IOException("Excel写到输出流中出现异常!", e);

        } catch (Exception e) {

            throw new IOException("Excel写到输出流中出现异常!", e);

        } finally {

            if (output != null) {

                output.flush();

                output.close();

            }

        }

    }

}

参考:

String[] noOut = { "isExchange", "password", "createTime", "exchangeTime", "flag" };

 response.setContentType("octets/stream");

 response.addHeader("Content-Disposition", "attachment;filename=RedList" + time + ".xls");

String[] headers = { "批次号", "红包兑换码", "金额(元)", "有效天数", "是否兑换", "创建时间", "兑换时间", "兑换方式" };

OutputStream out = null;

out = response.getOutputStream();

ExportExcel<RedEnvelopes> ex = new ExportExcel<RedEnvelopes>();

ex.exportExcel("红包信息", headers, redEnvelopes, out, "yyyy-MM-dd", noOut);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: