Excel导出工具类

该工具类用于导出列表

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * Created Date 2018/7/2 11:28
 * @author Allen
 **/
public class ExportUtil {
    private static Logger logger = LoggerFactory.getLogger(ExportUtil.class);

    /**
     * 导出
     * @param title 导出的表单名称
     * @param colNames 导出excel列名
     * @param colFields 导出字段的get方法
     * @param objects 导出类的list
     * @param cls 导出类
     * @param startTime 导出起始时间
     * @param endTime 导出结束时间
     * @param response response
     */
    public void export(String title, List colNames, List colFields,
            List objects, Class cls, Long startTime, Long endTime,
            HttpServletResponse response) {
        OutputStream output = null;
        response.setHeader("Content-Disposition", "attachment;filename=" +
                System.currentTimeMillis() + ".xlsx");//指定下载的文件名
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            output = response.getOutputStream();
        } catch (IOException e) {
            logger.error("export brand item;" + e.getMessage());
        }


        // 创建工作簿对象
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet(title);
        // 初始化表头
        initExcel(colNames, sheet, startTime, endTime);

        for (int i = 0; i < objects.size(); i++) {
            if (objects.get(i) == null) {
                continue;
            }
            Object obj = objects.get(i);
            XSSFRow row5 = sheet.createRow(i + 4);
            Object keyVal = "";
            Method declaredMethod;
            int j = 0;
            row5.createCell(j).setCellValue(i + 1);
            for (String col : colFields) {
                j++;
                try {
                    declaredMethod = cls.getDeclaredMethod(col);
                    keyVal = declaredMethod.invoke(obj);
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    logger.error("export brand item;" + e.getMessage());
                    e.printStackTrace();
                }
                row5.createCell(j).setCellValue(keyVal + "");

            }
        }
        try {
            if (output != null) {
                output.flush();
                wb.write(output);//写入到流中
                output.close();
            } else {
                logger.warn("nothing to export; brand {} start {} end {}", startTime,
                        endTime);
            }

        } catch (IOException e) {
            logger.error("export brand item;" + e.getMessage());
        }
    }

    private void initExcel(List colNames, XSSFSheet sheet, Long startTime, Long endTime) {
        String beginDate = DateUtil.getOrderDateString(new Date(startTime));
        String endDate = DateUtil.getOrderDateString(new Date(endTime));
        String currDate = DateUtil.getOrderDateString(new Date(System.currentTimeMillis()));
        sheet.setDefaultColumnWidth(20);
        XSSFRow row1 = sheet.createRow(0);  //创建行
        row1.createCell(0).setCellValue("统计起始时间: ");
        row1.createCell(1).setCellValue(beginDate);

        XSSFRow row2 = sheet.createRow(1);  //创建行
        row2.createCell(0).setCellValue("统计结束时间: ");
        row2.createCell(1).setCellValue(endDate);

        XSSFRow row3 = sheet.createRow(2);  //创建行
        row3.createCell(0).setCellValue("导出时间: ");
        row3.createCell(1).setCellValue(currDate);
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 3));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 3));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 3));

        XSSFRow row4 = sheet.createRow(3);  //创建行
        for (int i = 0; i < colNames.size(); i++) {
            row4.createCell(i).setCellValue(colNames.get(i));
        }

    }

}

你可能感兴趣的:(java技术)