Poi导出Excel工具类

一、概述

在工作过程中,都会遇到这样一个需求,就是将相关的数据列表导出成excel,这里写成通用的导出Excel的工具。

二、项目实现

1、构建pom.xml

我的工程是利用Maven来构建的,这里仅给出最核心的包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.11-beta2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11-beta2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.11-beta2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-excelant</artifactId>
    <version>3.11-beta2</version>
</dependency>
 <!--jxi导出-->
<dependency>
     <groupId>net.sourceforge.jexcelapi</groupId>
     <artifactId>jxl</artifactId>
     <version>2.6.12</version>
</dependency>

2、编写PoiUtils类

这个类是整个工具的核心,它实现了Excel文件的导出功能,具体代码如下:

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;



import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @Auther: admin
 * @Date: 2018/10/4 12:54
 * @Description: 导出excel 2003和2007通用工具类
 */
public class ExcelUtils {


    /**
     * 2003                导出Excel
     *
     * @param fileName    文件名
     * @param titles      导出excel标题
     * @param data        需要显示的数据集合
     * @param hashMapKeys 导出excel显示的列头(对应pojo里面的属性)
     * @Description: 2003版本最大支持65536行
     */
    public static void exportExcel2003(String fileName, String[] titles, String[] hashMapKeys,
                                       List<Map> data, HttpServletResponse response) throws IOException{
        // 1.创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 2.在workbook中添加一个sheet,对应Excel文件中的fileName
        HSSFSheet sheet = workbook.createSheet(fileName);

        //样式1:定义列宽
//        for (int i = 0; i < 12; i++) {
//            sheet.setColumnWidth(i, 4000);
//        }

        //样式2:定义第一行单元格样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        // 设置字体
        HSSFFont font = workbook.createFont();
        font.setFontName("微软雅黑");
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 字体大小
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);
        //设置单元格居中
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中

        //样式3:定义标题栏单元格样式
        HSSFCellStyle cellStyle1 = workbook.createCellStyle();
        //设置字体,第一行
        HSSFFont font1 = workbook.createFont();
//        font1.setFontName("微软雅黑");
//        font1.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//        // 字体大小
//        font1.setFontHeightInPoints((short) 12);
//        cellStyle1.setFont(font1);
        //设置单元格居中
        cellStyle1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        cellStyle1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        //设置边框
        cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);  //下边框
        cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);    //左边框
        cellStyle1.setBorderTop(HSSFColor.BLACK.index); //上边框
        cellStyle1.setBorderRight(HSSFColor.WHITE.index); //右边框
        //设置自动换行
        cellStyle1.setWrapText(true);

        //样式4:定义内容栏单元格样式
        HSSFCellStyle cellStyle2 = workbook.createCellStyle();
        HSSFFont font2 = workbook.createFont();
        font2.setFontName("宋体");
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 字体大小
        font2.setFontHeightInPoints((short) 12);
        cellStyle2.setFont(font2);
        //设置单元格内容居左和居上
        cellStyle2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        cellStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
        //设置边框
        cellStyle2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  //下边框
        cellStyle2.setBorderLeft(HSSFCellStyle.BORDER_THIN);    //左边框
        cellStyle2.setBorderTop(HSSFColor.BLACK.index); //上边框
        cellStyle2.setBorderRight(HSSFColor.WHITE.index); //右边框
        //设置自动换行
        cellStyle2.setWrapText(true);

        //样式5:定义尾部栏注释单元格样式
        HSSFCellStyle cellStyle3 = workbook.createCellStyle();
        HSSFFont font3 = workbook.createFont();
        font3.setFontName("楷体");
        font3.setFontHeightInPoints((short) 12);// 字体大小
        font3.setColor(HSSFColor.RED.index);//设置红色
        cellStyle3.setFont(font3);

        //样式6:合并第一行单元格
//        Region region1 = new Region(0, (short) 0, 0, (short) (titles.length - 1));
//        sheet.addMergedRegion(region1);

        //2.创建顶行
//        HSSFRow rowhead = sheet.createRow(0);
//        rowhead.setHeight((short) 700);
//        HSSFCell cellhead = rowhead.createCell(0);
//        cellhead.setCellValue(fileName.substring(0, fileName.lastIndexOf(".")));
//        cellhead.setCellStyle(cellStyle);

        //3.创建标题行
        HSSFRow row = sheet.createRow(0);
        // row.setHeight((short) 550);
        for (int i = 0; i < titles.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(cellStyle1);
        }
        //4.创建内容
        for (int i = 0; i < data.size(); i++) {
            HSSFRow rowi = sheet.createRow(i + 1);
            // row.setHeight((short) 550);
            for (int j = 0; j < hashMapKeys.length; j++) {
                HSSFCell celli = rowi.createCell(j);
                celli.setCellStyle(cellStyle2);
                if (data.get(i).get(hashMapKeys[j]) == null) {
                    celli.setCellValue("/");
                } else {
                    celli.setCellValue(data.get(i).get(hashMapKeys[j]).toString());
                }
            }
        }
        //5.创建尾部行
        HSSFRow rowtail = sheet.createRow(data.size() + 4);
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HSSFCell celltaill = rowtail.createCell(0);
        // celltaill.setCellValue("文档创建时间" + formater.format(new Date()));
        celltaill.setCellStyle(cellStyle3);

        //6.输出到Excel表格
        //设置响应头
        if (fileName.endsWith("xlsx")) {
            // response.setContentType("application/vnd.ms-excel");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        } else {
            response.setContentType("application/vnd.ms-excel");
        }

            response.setHeader("content-disposition", "attachment; fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();


    }

2007Excel工具类

 /**
     * @param fileName 表格的名称
     * @param titles   标题名称(表格第一行中文标题)
     * @param data 需要显示的数据集合
     * @param hashMapKeys 导出excel显示的列头(对应pojo里面的属性)
     * @Description: 2007导出excel通用工具类
     */
    public static void exportExcel2007(String fileName, String[] titles, String[] hashMapKeys, List<Map> data, HttpServletResponse response) {

        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(fileName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(15);

        // 生成表格中非标题栏的样式
        XSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.WHITE.index);//背景色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成表格中非标题栏的字体
        XSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        // 把字体应用到当前的样式
        style.setFont(font);

        // 设置表格标题栏的样式
        XSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(BorderStyle.THIN);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置标题栏字体
        XSSFFont titleFont = workbook.createFont();
        titleFont.setColor(HSSFColor.WHITE.index);
        titleFont.setFontHeightInPoints((short) 12);
        titleFont.setBold(true);
        // 把字体应用到当前的样式
        titleStyle.setFont(titleFont);

        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        for (short i = 0; i < titles.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellStyle(titleStyle);
            XSSFRichTextString text = new XSSFRichTextString(titles[i]);
            cell.setCellValue(text);
        }
        //4.遍历集合数据,产生数据行
        for (int i = 0; i < data.size(); i++) {
            XSSFRow rowi = sheet.createRow(i + 1);
            // row.setHeight((short) 550);
            for (int j = 0; j < hashMapKeys.length; j++) {
                XSSFCell celli = rowi.createCell(j);
                celli.setCellStyle(style);
                if (data.get(i).get(hashMapKeys[j]) == null) {
                    // celli.setCellValue("/");
                } else {
                    celli.setCellValue(data.get(i).get(hashMapKeys[j]).toString());
                }
            }
        }
        //5.创建尾部行
        XSSFRow rowtail = sheet.createRow(data.size() + 4);
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        XSSFCell celltaill = rowtail.createCell(0);
        // celltaill.setCellValue("文档创建时间" + formater.format(new Date()));
        celltaill.setCellStyle(style);

        //6.输出到Excel表格
        //设置响应头
        if (fileName.endsWith("xlsx")) {
            //response.setContentType("application/vnd.ms-excel");
           response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        } else {
            response.setContentType("application/vnd.ms-excel");
        }
        try {
            response.setHeader("content-disposition", "attachment; fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2007动态导出Excel工具类

 /**
     * @param : response
     * @param : data        数据源
     * @param : filename    文件名,如20150703.xls
     * @param : columns     列名称集合,例如(姓名,年龄)
     * @return : void
     * @date : 2018/12/11 20:52
     * @Description: 2007动态导出excel工具类
     */
    public static void publicExportExcel2007(HttpServletResponse response, List<Map<String, Object>> data, String filename, List<String> columns) {
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(filename);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(15);
        // 生成表格中非标题栏的样式
        XSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.WHITE.index);// 背景色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成表格中非标题栏的字体
        XSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 设置表格标题栏的样式
        XSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(BorderStyle.THIN);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置标题栏字体
        XSSFFont titleFont = workbook.createFont();
        titleFont.setColor(HSSFColor.WHITE.index);
        titleFont.setFontHeightInPoints((short) 12);
        titleFont.setBold(true);
        // 把字体应用到当前的样式
        titleStyle.setFont(titleFont);
        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        if (columns != null && columns.size() > 0) {
            for (short i = 0; i < columns.size(); i++) {
                XSSFCell cell = row.createCell(i);
                cell.setCellStyle(titleStyle);
                XSSFRichTextString text = new XSSFRichTextString(columns.get(i));
                cell.setCellValue(text);
            }
        }
        // 4.遍历集合数据,产生数据行
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                XSSFRow rowi = sheet.createRow(i + 1);
                for (int j = 0; j < columns.size(); j++) {
                    XSSFCell celli = rowi.createCell(j);
                    celli.setCellStyle(style);
                    if (data.get(i).get(columns.get(j)) == "") {
                        // celli.setCellValue("/");
                    } else {
                        celli.setCellValue(data.get(i).get(columns.get(j)).toString());
                    }
                }
            }
        }
        // 5.输出Excel表格,设置响应头
        if (filename.endsWith("xlsx")) {
            response.setContentType("application/msexcel");
        } else {
            response.setContentType("application/vnd.ms-excel");

        }
        OutputStream out = null;
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param : [result, map]
     * @return : java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @date : 2018/12/11 20:55
     * @exception:
     * @Description: 2007动态导出excel工具类数据封装
     */
    public static List<Map<String, Object>> assembelDats(List<Map> result, LinkedHashMap map) {
        // 整合内容
        List<Map<String, Object>> daList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            Map<String, Object> tempMap = new HashMap();
            for (Object key : result.get(i).keySet()) {
                tempMap.put((String) map.get(key), result.get(i).get(key));
            }
            daList.add(tempMap);
        }
        return daList;
    }

 

 

三,Controller

 /**
     * @param : [map, response]
     * @return : void
     * @date : 2018/10/26 20:25
     * @exception:
     * @Description: ExcelUtils通用导出测试
     */
    @RequestMapping("/export.do")
    public void export( HttpServletResponse response) throws Exception {
        //获取数据
        String[] titles = new String[]{"名称", "性别", "年龄", "学校", "班级"};
        String[] hashMapKeys = new String[]{"name", "sex", "age", "school", "grade"};
        String fileName = "报表.xlsx";
        List<Map> data = new ArrayList<>();
        //使用LinkedHashMap保证有序,即标题和数据对应上
        Map<String, Object> maps = new LinkedHashMap();
        maps.put("name", "张三");
        maps.put("sex", "男");
        maps.put("age", 23);
        maps.put("school", "清华");
        maps.put("grade", "51155");
        data.add(maps);

        try {
            ExcelUtils.exportExcel2003(fileName,titles,hashMapKeys,data,response);
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

4.效果如下

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章