poi excel导出

                                                                使用poi导出Excel文件

首先需要导入所需要的jar包:

目前POI的最新发布版本是3.10_FINAL.该版本保护的jar包有:

Maven artifactIdPrerequisitesJAR
poicommons-logging, commons-codec, log4jpoi-version-yyyymmdd.jar
poi-scratchpadpoipoi-scratchpad-version-yyyymmdd.jar
poi-ooxmlpoi, poi-ooxml-schemaspoi-ooxml-version-yyyymmdd.jar
poi-ooxml-schemasxmlbeanspoi-ooxml-schemas-version-yyyymmdd.jar
poi-examplespoi, poi-scratchpad, poi-ooxmlpoi-examples-version-yyyymmdd.jar
ooxml-schemasxmlbeansooxml-schemas-1.1.jar


很多人都困惑POI那么多Jar到底应该导入哪一个。

实际上很多时候我们只利用POI来操作Excel。甚至只用xls这一种格式。

那么就没有必要全部都导入了。具体应该使用哪个JAR包请参考以下内容:

Component Map

The Apache POI distribution consists of support for many document file formats. This support is provided in several Jar files. Not all of the Jars are needed for every format. The following tables show the relationships between POI components, Maven repository tags, and the project's Jar files.

ComponentApplication typeMaven artifactIdNotes
POIFSOLE2 FilesystempoiRequired to work with OLE2 / POIFS based files
HPSFOLE2 Property Setspoi 
HSSFExcel XLSpoiFor HSSF only, if common SS is needed see below
HSLFPowerPoint PPTpoi-scratchpad 
HWPFWord DOCpoi-scratchpad 
HDGFVisio VSDpoi-scratchpad 
HPBFPublisher PUBpoi-scratchpad 
HSMFOutlook MSGpoi-scratchpad 
OpenXML4JOOXMLpoi-ooxml plus one of
poi-ooxml-schemas, ooxml-schemas
Only one schemas jar is needed, see below for differences
XSSFExcel XLSXpoi-ooxml 
XSLFPowerPoint PPTXpoi-ooxml 
XWPFWord DOCXpoi-ooxml 
Common SSExcel XLS and XLSXpoi-ooxmlWorkbookFactory and friends all require poi-ooxml, not just core poi

当我们只要使用xls格式时、只要导入poi-version-yyyymmdd.jar就可以了。

poi-ooxml-version-yyyymmdd.jar。

至于poi-ooxml-schemas-version-yyyymmdd.jar这个jar基本不太会用到的。

poi-scratchpad-version-yyyymmdd.jar。

新建类继承 AbstractExcelView类 实现buildExcelDocument方法

import org.springframework.web.servlet.view.document.AbstractExcelViewpublic class ExcelView extends AbstractExcelView {}

具体使用如下:

package com.app;

import com.app.util.QRCodeUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * Excel视图
 *
 * @author APP TEAM
 * @version 1.0
 */
public class ExcelView extends AbstractExcelView {

    /**
     * 默认日期格式配比
     */
    private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

    private static final String QRCODE_NAME = "qrCode";

    /**
     * 文件名称
     */
    private String filename;

    /**
     * 表名称
     */
    private String sheetName;

    /**
     * 属性
     */
    private String[] properties;

    /**
     * 标题
     */
    private String[] titles;

    /**
     * 列宽
     */
    private Integer[] widths;

    /**
     * 类型转换
     */
    private Converter[] converters;

    /**
     * 数据
     */
    private Collection<?> data;

    /**
     * 附加内容
     */
    private String[] contents;

    static { // 时间转换器,转换当前时间的格式
        DateConverter dateConverter = new DateConverter();
        dateConverter.setPattern(DEFAULT_DATE_PATTERN);
        ConvertUtils.register(dateConverter, Date.class);
    }

    /**
     * @param filename   文件名称
     * @param sheetName  表名称
     * @param properties 属性
     * @param titles     标题
     * @param widths     列宽
     * @param converters 类型转换
     * @param data       数据
     * @param contents   附加内容
     */
    public ExcelView(String filename, String sheetName, String[] properties, String[] titles, Integer[] widths, Converter[] converters, Collection<?> data, String[] contents) {
        this.filename = filename;
        this.sheetName = sheetName;
        this.properties = properties;
        this.titles = titles;
        this.widths = widths;
        this.converters = converters;
        this.data = data;
        this.contents = contents;
    }

    /**
     * @param properties 属性
     * @param titles     标题
     * @param data       数据
     * @param contents   附加内容
     */
    public ExcelView(String[] properties, String[] titles, Collection<?> data, String[] contents) {
        this.properties = properties;
        this.titles = titles;
        this.data = data;
        this.contents = contents;
    }

    /**
     * @param properties 属性
     * @param titles     标题
     * @param data       数据
     */
    public ExcelView(String[] properties, String[] titles, Collection<?> data) {
        this.properties = properties;
        this.titles = titles;
        this.data = data;
    }

    /**
     * @param filename   文件名称
     * @param properties 属性
     * @param titles     标题
     * @param data       数据
     */
    public ExcelView(String filename, String[] properties, String[] titles, Collection<?> data) {
        this.filename = filename;
        this.properties = properties;
        this.titles = titles;
        this.data = data;
    }

    /**
     * @param properties 属性
     * @param data       数据
     */
    public ExcelView(String[] properties, Collection<?> data) {
        this.properties = properties;
        this.data = data;
    }

    /**
     * 生成Excel文档
     *
     * @param model    数据
     * @param workbook workbook
     * @param request  request
     * @param response response
     */

                                            //创建一个webbook,对于一个Excel文件 HSSFWorkbook workbook
    public void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        /**
         *   判断属性是否为空,下面那个就是属性 跟标题对应
         *   String[] properties = new String[]{"index", "city", "totalCompanyPay", "totalUserPay", "synthesise", "agentCommission", "saleCommission", "recommenderCommission"};
         *   String[] titles = new String[]{"序号", "地区", "企业消费", "个人消费", "综合消费", "代理商提成", "业务员提成", "推荐人提成"};
         * */
        Assert.notEmpty(properties);

        //在webbook中添加一个sheet(表),对应Excel文件中的sheet(表)
        HSSFSheet sheet;
        //判断表名是否为空
        if (StringUtils.isNotEmpty(sheetName)) {
        //表名不为空,添加表名
            sheet = workbook.createSheet(sheetName);
        } else {
        //否则不添加
            sheet = workbook.createSheet();
        }
        int rowNumber = 0;
        //循环表头的字段长度
        // String[] titles = new String[]{"序号", "地区", "企业消费", "个人消费", "综合消费", "代理商提成", "业务员提成", "推荐人提成"};
        if (titles != null && titles.length > 0) {
            //创建Excel工作表的行
            HSSFRow header = sheet.createRow(rowNumber);
            //设置行高
            header.setHeight((short) 400);
            for (int i = 0; i < properties.length; i++) {
                //根据i来创建自定的单元格
                HSSFCell cell = header.createCell(i);
                //创建单元格样式
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                //添加背景颜色 具体颜色样式 请看样式对照表
                cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
                //设置填充模式
                cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                //左右居中
                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                //垂直居中
                cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                //添加字体样式
                HSSFFont font = workbook.createFont();
                //字号(大小)
                font.setFontHeightInPoints((short) 11);
                //加粗
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                //字体样式生效
                cellStyle.setFont(font);
                //居中,颜色 等等--样式生效
                cell.setCellStyle(cellStyle);
                if (titles.length > i && titles[i] != null) {
                    //对应title中的每个单元格插入值
                    cell.setCellValue(titles[i]);
                } else {
                    cell.setCellValue(properties[i]);
                }
                if (widths != null && widths.length > i && widths[i] != null) {
                    //如果有设置列宽 根据下标I 来设置列宽
                    sheet.setColumnWidth(i, widths[i]);
                } else {
                    //否则 自动根据长度调整单元格长度
                    sheet.autoSizeColumn(i);
                }
            }
            rowNumber++;
        }
        // 导出的Excel中带有图片的方法如下, 没有图片可以忽略以下代码
        // 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        if (data != null) {
            for (Object item : data) {
                HSSFRow row = sheet.createRow(rowNumber);
                //判断是否是有导出二位图片
                Boolean isExportQrCode = false;
                for (int i = 0; i < properties.length; i++) {
                    HSSFCell cell = row.createCell(i);
                    if (converters != null && converters.length > i && converters[i] != null) {
                        Class<?> clazz = PropertyUtils.getPropertyType(item, properties[i]);
                        ConvertUtils.register(converters[i], clazz);
                        cell.setCellValue(BeanUtils.getProperty(item, properties[i]));
                        ConvertUtils.deregister(clazz);
                        if (clazz.equals(Date.class)) {
                            DateConverter dateConverter = new DateConverter();
                            dateConverter.setPattern(DEFAULT_DATE_PATTERN);
                            ConvertUtils.register(dateConverter, Date.class);
                        }
                    } else {
                        if (QRCODE_NAME.equals(properties[i])) {
                            BufferedImage bufferImg = ImageIO.read(QRCodeUtils.createQRCodeFile(BeanUtils.getProperty(item, properties[i]), null, null));//图片一
                            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                            ImageIO.write(bufferImg, "png", byteArrayOut);
                            //anchor主要用于设置图片的属性
                            HSSFClientAnchor anchor = new HSSFClientAnchor(25, 25, 255, 255, (short) 3, rowNumber, (short) 10, rowNumber + 20);
                            anchor.setAnchorType(3);
                            //插入图片
                            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
                            isExportQrCode = true;
                        } else {
                            cell.setCellValue(BeanUtils.getProperty(item, properties[i]));
                        }

                    }

                    if (widths != null && widths.length > i && widths[i] != null) {
                        //如果有设置列宽 根据下标I 来设置列宽
                        sheet.setColumnWidth(i, widths[i]);
                    } else {
                        //否则 自动根据长度调整单元格长度
                        sheet.autoSizeColumn(i);
                    }
                }
                if (isExportQrCode) {
                    rowNumber = rowNumber + 21;
                } else {
                    rowNumber++;
                }
            }
        }

        //附加内容
        if (contents != null && contents.length > 0) {
            rowNumber++;
            for (String content : contents) {
                HSSFRow row = sheet.createRow(rowNumber);
                HSSFCell cell = row.createCell(0);
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                HSSFFont font = workbook.createFont();
                font.setColor(HSSFColor.GREY_50_PERCENT.index);
                cellStyle.setFont(font);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(content);
                rowNumber++;
            }
        }
        //二、为了防止客户端浏览器直接打开目标文件(例如在装了MS Office套件的Windows中的IE浏览器可能就会直接在IE浏览器中打开你想下载的doc或者xls文件)
        // ,你必须在响应头里加入强制下载的MIME类型,设置为下载application/force-download
        response.setContentType("application/force-download");
        if (StringUtils.isNotEmpty(filename)) {
            //当Content-Type 的值设置为text/html和text/plain时,前者会让浏览器把接收到的实体内容以HTML格式解析,后者会让浏览器以普通文本解析
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        } else {
            response.setHeader("Content-disposition", "attachment");
        }
    }

    /**
     * 获取文件名称
     *
     * @return 文件名称
     */
    public String getFileName() {
        return filename;
    }

    /**
     * 设置文件名称
     *
     * @param filename 文件名称
     */
    public void setFileName(String filename) {
        this.filename = filename;
    }

    /**
     * 获取表名称
     *
     * @return 表名称
     */
    public String getSheetName() {
        return sheetName;
    }

    /**
     * 设置表名称
     *
     * @param sheetName 表名称
     */
    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }

    /**
     * 获取属性
     *
     * @return 属性
     */
    public String[] getProperties() {
        return properties;
    }

    /**
     * 设置属性
     *
     * @param properties 属性
     */
    public void setProperties(String[] properties) {
        this.properties = properties;
    }

    /**
     * 获取标题
     *
     * @return 标题
     */
    public String[] getTitles() {
        return titles;
    }

    /**
     * 设置标题
     *
     * @param titles 标题
     */
    public void setTitles(String[] titles) {
        this.titles = titles;
    }

    /**
     * 获取列宽
     *
     * @return 列宽
     */
    public Integer[] getWidths() {
        return widths;
    }

    /**
     * 设置列宽
     *
     * @param widths 列宽
     */
    public void setWidths(Integer[] widths) {
        this.widths = widths;
    }

    /**
     * 获取类型转换
     *
     * @return 类型转换
     */
    public Converter[] getConverters() {
        return converters;
    }

    /**
     * 设置类型转换
     *
     * @param converters 类型转换
     */
    public void setConverters(Converter[] converters) {
        this.converters = converters;
    }

    /**
     * 获取数据
     *
     * @return 数据
     */
    public Collection<?> getData() {
        return data;
    }

    /**
     * 设置数据
     *
     * @param data 数据
     */
    public void setData(Collection<?> data) {
        this.data = data;
    }

    /**
     * 获取附加内容
     *
     * @return 附加内容
     */
    public String[] getContents() {
        return contents;
    }

    /**
     * 设置附加内容
     *
     * @param contents 附加内容
     */
    public void setContents(String[] contents) {
        this.contents = contents;
    }

}






Controller 操作属性 :

private ModelAndView summationExport(String companyName,Date startDay,Date endDay) { //页面可带参数过来
        //根据ID查询出想要的数据
        List list = areaSaleService.getAreaSummation(id);
        List<Map> mapList = new ArrayList<>();
        //文件名
        String filename = "销售分析—汇总.xls";
        //表名
        String sheetName = null;
        //属性
        String[] properties = new String[]{"index", "city", "totalCompanyPay", "totalUserPay", "synthesise", "agentCommission", "saleCommission", "recommenderCommission"};
        //表头
        String[] titles = new String[]{"序号", "地区", "企业消费", "个人消费", "综合消费", "代理商提成", "业务员提成", "推荐人提成"};
        //列宽
        Integer[] widths = null;
        Converter[] converters = null;
        String[] contents = null;// 附加内容
        if (CollectionUtils.isEmpty(list)) {
            return new ModelAndView(new ExcelView(filename, sheetName, properties, titles, widths, converters, mapList, contents), model);
        }
        for (int i = 0; i < list.size(); i++) {
            //将查出的数据用Map接受,  如果查出结果是一个对象,可以直接用对象
            // 列如 User user = areaSaleService.getAreaSummation(id);
            //  map.put("city",user.getCity);
            Map<String, Object> map = (Map<String, Object>) list.get(i);
            //将值于属性对上
            map.put("index",i+1);
            map.put("city", map.get("city"));
            map.put("totalCompanyPay", map.get("totalCompanyPay"));
            map.put("totalUserPay",map.get("totalUserPay"));
            map.put("synthesise",map.get("synthesise"));
            map.put("agentCommission",map.get("agentCommission"));
            map.put("saleCommission", map.get("saleCommission"));
            map.put("recommenderCommission",map.get("recommenderCommission"));
            mapList.add(map);
        }
        //返回视图
        return new ModelAndView(new ExcelView(filename, sheetName, properties, titles, widths, converters, mapList, contents), model);
        }


前端跳转 :

  <span class="input-icon">
         <a class="btn btn-info btn-sm" href="javascript:;" data-bind="click:Export">导出</a>
  </span>

<form id="exportExcel" action="/admin/reports/sales/companyExport.jhtml">  //必须通过form提交才能使用,不能使用ajax
    //可带参数
    <input id="companyName" name="companyName" type="hidden"/>
    <input id="startDayData" name="startDay" type="hidden"/>
    <input id="endDayData" name="endDay" type="hidden"/>
    <input id="province" name="province" type="hidden"/>
    <input id="city" name="city" type="hidden"/>
    <input id="district" name="area" type="hidden"/>
    <input id="type" name="type" type="hidden"/>
    <input id="superObjectId" name="superObjectId" type="hidden"/>
</form>

JS :

Export: function () {
        //想要带过去的参数
        $("#type").val(superObjectType);
        $("#superObjectId").val(userId);
        $("#startDayData").val(startDay);
        $("#endDayData").val(endDay);
        $("#companyName").val(companyName);
        //form
        var exportFrom = $("#exportExcel");
        //提交form
        exportFrom.submit();
        }

poi的一些文档
一些样式演示






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值