java 导出excel工具类

1.PoiExportsUtil类

package com.*.*.util;

import com.*.core.annotation.IsNeeded;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 导出excel工具类
 *
 */
public class PoiExportsUtil<T> {


    // 2007 版本以上 最大支持1048576行
    private  final static String  EXCEl_FILE_2007 = "2007";
    // 2003 版本 最大支持65536 行
    private final static String  EXCEL_FILE_2003 = "2003";
    /*// 要导出的报表名
    private String fileName = "申请护照表";*/

    public PoiExportsUtil() {}

    /**
     * <p>
     * 导出无头部标题行Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     *
     * @param title 表格标题
     * @param dataset 数据集合
     * @param response 浏览器响应
     * @param version 2003 或者 2007,不传时默认生成2003版本
     */
    public void exportExcel(String title, List<T> dataset, HttpServletResponse response, String version) throws IOException {
        if(StringUtils.isBlank(version) || EXCEl_FILE_2007.equals(version.trim())){
            exportExcel2007(title, dataset, response, "yyyy-MM-dd");
        }else{
            exportExcel2003(title, dataset, response, "yyyy-MM-dd");
        }
    }

    /**
     * @param title   表格标题名
     * @param dataset 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *                JavaBean属性的数据类型有基本数据类型及String,Date
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private void exportExcel2007(String title, List<T> dataset, HttpServletResponse response, String pattern) throws IOException {
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        XSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
        style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        XSSFFont font = workbook.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        font.setFontName("宋体");
        font.setColor(new XSSFColor(java.awt.Color.BLACK));
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        XSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
        style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
        style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        XSSFFont font2 = workbook.createFont();
        font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        if (dataset == null || dataset.size() == 0) {
            return;
        }
        //取当前时间为字符串 (20180628)
        SimpleDateFormat sdf1 =   new SimpleDateFormat( " yyyyMMdd " );
        String curTime = sdf1.format(new Date());
        //设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition","attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8")+".xlsx");
//        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
        OutputStream out = response.getOutputStream();

        T tempT = dataset.get(0);
        Field[] fields = tempT.getClass().getDeclaredFields();
        List<String> fileList = getFiledList(fields);
        List<Field> filedTypes = getFiledType(fields);

        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        XSSFCell cellHeader;
        for (int i = 0; i < fileList.size(); i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            XSSFRichTextString text = new XSSFRichTextString(fileList.get(i));
            cellHeader.setCellValue(text);
        }

        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
        XSSFCell cell;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = it.next();
            // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
            for (int i = 0; i < filedTypes.size(); i++) {
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                Field field = filedTypes.get(i);
                String fieldName = field.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName);
                    Object value = getMethod.invoke(t);
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf(value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf(value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "是";
                        if (!(Boolean) value) {
                            textValue = "否";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            XSSFRichTextString richString = new XSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    /**
     * @param title   表格标题名
     * @param dataset 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *                JavaBean属性的数据类型有基本数据类型及String,Date
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private void exportExcel2003(String title, List<T> dataset, HttpServletResponse response, String pattern) throws IOException {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth((short) 20);

        // 生成一个样式并设置样式
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.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.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontName("宋体");
        font.setColor(HSSFColor.WHITE.index);
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style.setFont(font);

        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.WHITE.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 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
        HSSFCell cell;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        if (dataset.size() == 0) {
            return;
        }
        //设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8") + ".xls");
        OutputStream out = response.getOutputStream();

        T tempT = dataset.get(0);
        Field[] fields = tempT.getClass().getDeclaredFields();
        List<String> fileList = getFiledList(fields);
        List<Field> filedTypes = getFiledType(fields);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cellHeader;
        for (int i = 0; i < fileList.size(); i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(fileList.get(i));
            cellHeader.setCellValue(text);
        }

        try {while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                row.setHeightInPoints(120);
                T t = it.next();
                // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
                for (int i = 0; i < filedTypes.size(); i++) {
                    cell = row.createCell(i);
                    cell.setCellStyle(style2);
                    Field field = filedTypes.get(i);
                    String fieldName = field.getName();
                    String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                            + fieldName.substring(1);

                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName);
                    Object value = getMethod.invoke(t);
                    if(i == filedTypes.size()-1){
                        if(value!=null){
                            FileOutputStream fileOut = null;
                            String path = value.toString();
                            BufferedImage bufferImg = null;//图片
                            String picType=path.substring(path.lastIndexOf(".")+1);
                            // 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
                            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                            //将图片读到BufferedImage
                            bufferImg = ImageIO.read(new File(path));
                            // 将图片写入流中
                            ImageIO.write(bufferImg, picType, byteArrayOut);
                            // 利用HSSFPatriarch将图片写入EXCEL
                            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                            //图片导出到单元格中
                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 8, index, (short) 9 , index+1);
                            // 插入图片
                            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
                        }
                    }else {
                        // 判断值的类型后进行强制类型转换
                        String textValue = null;
                        if (value instanceof Integer) {
                            cell.setCellValue((Integer) value);
                        } else if (value instanceof Float) {
                            textValue = String.valueOf(value);
                            cell.setCellValue(textValue);
                        } else if (value instanceof Double) {
                            textValue = String.valueOf(value);
                            cell.setCellValue(textValue);
                        } else if (value instanceof Long) {
                            cell.setCellValue((Long) value);
                        }
                        if (value instanceof Boolean) {
                            textValue = "是";
                            if (!(Boolean) value) {
                                textValue = "否";
                            }
                        } else if (value instanceof Date) {
                            textValue = sdf.format((Date) value);
                        } else {
                            // 其它数据类型都当作字符串简单处理
                            if (value != null) {
                                textValue = value.toString();
                            }
                        }
                        if (textValue != null) {
                            Matcher matcher = p.matcher(textValue);
                            if (matcher.matches()) {
                                // 是数字当作double处理
                                cell.setCellValue(Double.parseDouble(textValue));
                            } else {
                                HSSFRichTextString richString = new HSSFRichTextString(textValue);
                                cell.setCellValue(richString);
                            }
                        }
                    }
                }
            }
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    //==========================本类私有方法=========================//

    /**
     * 获取参与操作的实体类字段
     */
    private List<String> getFiledList(Field[] fields) {
        List<String> fileList = new ArrayList<>();

        //获取字段注解的表头
        for (Field field1 : fields) {
            if (field1.isAnnotationPresent(IsNeeded.class)){
                IsNeeded isNeeded = (IsNeeded) field1.getAnnotations()[0];
                String head = isNeeded.head();
                fileList.add(head);
            }
        }
        return fileList;
    }

    private List<Field> getFiledType(Field[] fields) {
        List<Field> fileTypes = new ArrayList<>();

        //获取字段注解的表头
        for (Field field1 : fields) {
            if (field1.isAnnotationPresent(IsNeeded.class)){
                fileTypes.add(field1);

            }
        }
        return fileTypes;
    }
}

2.IsNeed.java
package com.*.core.annotation;


import java.lang.annotation.*;

/**
 * 是否需要从解析excel赋值
 * 因为再实体类里面并不是所有的属性都要参与excel的导入,给需要参与导入的属性加上此注解
 *
 */
@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE})
public @interface IsNeeded {

    /**
     * 是否需要从解析excel赋值
     * @return
     * true:需要  false:不需要
     */
    boolean isNeeded() default true;
    String head() default "";
}

3.实体类,加入注解

@IsNeeded(head = "手机号")
@ApiModelProperty(value = "手机号")
@TableField("phone")
private String phone;

4.controller类

PoiExportsUtil<T> poiExportsUtil = new PoiExportsUtil();
poiExportsUtil.exportExcel(sheetName,list,resp,"2003");//2003版本

猜你喜欢

转载自blog.csdn.net/lsy_know/article/details/86511481