easy poi 模板生成多表excel

本文介绍了一个Java服务实现,通过EasyPoi库处理多个查询结果,将数据填充到TCRR_TEMPLATE.xlsx模板中,生成并下载四个并列的Excel表:整体趋势、地理分布、ODM产品和零件保修数据。
摘要由CSDN通过智能技术生成

1. 需求

要求根据查询,在同一个excel sheet中生成如下并列的四个excel表
在这里插入图片描述

2. 模板制作

根据查询字段,制作如下模板(项目/resources/templates/kpi/TCRR_TEMPLATE.xlsx)
在这里插入图片描述

3 代码

3.1 serviceImpl
    /**
     * TCRR 下载后的文件名称
     */
    public static final String TCRR_FILE = "TCRR.xlsx";
      /**
     * TCRR 下载模板名称
     */
    public static final String TCRR_PATH = "templates/kpi/TCRR_TEMPLATE.xlsx";
    /**
     * TCRR excel报表下载
     * 1. 模板包含多张表的数据,先获取多张表的list数据;
     * 2. 组合数据为poi需要的格式;
     * 3. 调用poi接口
     *
     * @param queryParam 查询参数
     * @param response   响应参数
     * @return 下载结果
     * @author: leiming5
     */
    public void downloadExcel(StTcrrQueryParam queryParam, HttpServletResponse response) {

        // 1
        List<OverallTrendVo> overallTrendVoList = getOverallTrend(queryParam);
        List<GeoSerieVo> geoSerieVoList = getGeoByWeekOrMonth(queryParam);
        List<OdmProductVo> odmProductVoList = getODMByWeekOrMonth(queryParam);
        List<PartsWarrantyVo> partsWarrantyVoList = getPartsByWeekOrMonth(queryParam);

        // 2
        JSONObject result = new JSONObject();
        result.put("OverallTCRRTrend", overallTrendVoList);
        result.put("TCRRByGeo", geoSerieVoList);
        result.put("TCRRByODM", odmProductVoList);
        result.put("PartsWarranty", partsWarrantyVoList);

        // 3
        commomExportExcel.commonDownLoad(result, TCRR_PATH, TCRR_FILE, response);
    }
3.2 commomExportExcel
package com.leinovo.qes.portal.modules.report.poi;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * Student导出excel工具类
 */
@Component
public class CommomExportExcel extends AbstractExportTemplate {

    /**
     * map格式数据下载
     *
     * @param excelData 数据
     * @param templatePath 模板存在相对路劲
     * @param downFileName 下载后的文件名称
     * @param response 相应对象
     * @param sheetNum 模板列数
     */
    public void commonDownLoad(Map<String, Object> excelData, String templatePath, String downFileName,
                               HttpServletResponse response, Integer... sheetNum) {

        commonDownLoadExcel(excelData, templatePath, downFileName, response, sheetNum);
    }

    /**
     * 列表下载
     *
     * @param rowList 数据
     * @param templatePath 模板存在相对路劲
     * @param downFileName 下载后的文件名称
     * @param response 相应对象
     */
    public <T> void commonDownLoad(List<T> rowList, String templatePath, String downFileName, HttpServletResponse response) {
        simpleDownLoadExcel(rowList, templatePath, downFileName, response);
    }

    public <T> void commonDownLoad(List<T> rowList, String templatePath, String downFileName, HttpServletResponse response,
                                   Integer... number) {
        simpleDownLoadExcel(rowList, templatePath, downFileName, response, number);
    }
}
3.3 AbstractExportTemplate
package com.leinovo.qes.portal.modules.report.poi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.leinovo.qes.portal.modules.report.utils.CloseableUtils;
import com.leinovo.qes.portal.modules.report.utils.FileUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据模板导出excel抽象父类
 */
@Slf4j
@Getter
@Setter
@ToString
public abstract class AbstractExportTemplate {

    private static final String COMMON_ROWLIST_NAME = "rowList";

    // 导出的模板
    protected String templatePath;

    // 导出的文件名
    protected String downLoadFileName;

    // 导出到excel的数据
    protected Map<String, Object> excelData = new HashMap<>();

    private InputStream buildExcelInputStream(Map<String, Object> excelData, Integer... sheetNum) {
        Workbook workbook = null;
        ByteArrayOutputStream outputStream = null;
        ByteArrayInputStream inputStream = null;
        try {
            TemplateExportParams params = new TemplateExportParams(templatePath, sheetNum);
            workbook = ExcelExportUtil.exportExcel(params, excelData);

            // 获取excel输出流
            outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);

            // 根据输出流程获取excel的输入流
            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        } catch (IOException e) {
            log.error("导出excel出错", e);
        } finally {
            CloseableUtils.close(outputStream, workbook);
        }
        return inputStream;
    }

    /**
     * 給excel设置数据
     *
     * @param
     * @param sourceListData
     * @return
     */
    public <T> void setRowList(List<T> sourceListData) {
        this.excelData.put(COMMON_ROWLIST_NAME, sourceListData);
    }

    /**
     * 下载方式一:这种方式适用于下载列表数据
     *
     * @param sourceListData
     * @param templatePath
     * @param downFileName
     * @param response
     * @param <T>
     */
    protected <T> void simpleDownLoadExcel(List<T> sourceListData, String templatePath, String downFileName, HttpServletResponse response) {
        setRowList(sourceListData);
        this.commonDownLoadExcel(this.excelData, templatePath, downFileName, response);
    }

    protected <T> void simpleDownLoadExcel(List<T> sourceListData, String templatePath, String downFileName,
                                           HttpServletResponse response,Integer... number) {
        setRowList(sourceListData);
        this.commonDownLoadExcel(this.excelData, templatePath, downFileName, response, number);
    }
    /**
     * 下载方式二:这种方式,需要子类封装好下载的Map数据
     */
    protected void commonDownLoadExcel(Map<String, Object> excelData, String templatePath, String downFileName,
                                       HttpServletResponse response, Integer... sheetNum) {
        this.excelData = excelData;
        this.templatePath = templatePath;
        this.downLoadFileName = downFileName;

        InputStream inputStream = null;
        try {
            setExcelData();
            inputStream = buildExcelInputStream(this.excelData, sheetNum);
            FileUtils.writeToResponse(response, inputStream, downFileName);
        } finally {
            CloseableUtils.close(inputStream);
        }
    }

    /**
     * 模板方法,子类设置excel中需要展示的数据
     */
    protected void setExcelData() {
        // 设置excelData
    }

}
3.4 FileUtils

package com.leinovo.qes.portal.modules.report.utils;

import org.apache.commons.compress.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public final class FileUtils {
    /**
     * 下载文件到浏览器
     *
     * @param response
     * @param inputStream
     * @param fileName 浏览器下载的文件名称
     */
    public static void writeToResponse(HttpServletResponse response, InputStream inputStream, String fileName) {
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("浏览器下载文件出错, fileName:{}", fileName, e);
        } finally {
            // close stream
            CloseableUtils.close(inputStream, outputStream);
        }
    }

    /**
     * 删除本地文件
     *
     * @param filePath
     */
    public static void deleteLocalFile(String filePath) {
        File file = new File(filePath);
        file.delete();
    }
}
3.5 CloseableUtils
package com.leinovo.qes.portal.modules.report.utils;


import java.io.Closeable;
import java.io.IOException;

/**
 * Created by kongkp on 16-8-26.
 */
public final class CloseableUtils {

    private CloseableUtils() {
    }

    public static void close(Closeable... closables) {
        if (closables == null || closables.length == 0) {
            return;
        }

        for (Closeable closable : closables) {
            try {
                if (closable != null) {
                    closable.close();
                }
            } catch (IOException e) {
                System.err.println("Close resource exception:" + e.getStackTrace());
            }
        }
    }
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用POI的HYPERLINK生成模板Excel超链接地址,需要按照以下步骤进行: 1. 创建一个Workbook对象,并创建一个Sheet对象。 2. 在Sheet对象中创建一个Row对象,并在该Row对象中创建一个Cell对象。 3. 创建一个Hyperlink对象,并将其设置为该Cell对象的超链接。 4. 将超链接地址设置为Hyperlink对象的地址。 5. 设置该Cell对象的值为超链接文本。 6. 将Workbook对象写入到文件或输出流中,即可生成带有超链接的Excel模板。 以下是一个示例代码: ``` import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; public class HyperlinkExample { public static void main(String[] args) throws IOException { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("Hyperlink Example"); Row row = sheet.createRow(0); Cell cell = row.createCell(0); Hyperlink link = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); link.setAddress("https://www.example.com"); cell.setHyperlink(link); cell.setCellValue("Click here to visit example.com"); FileOutputStream outputStream = new FileOutputStream("hyperlink_example.xls"); workbook.write(outputStream); workbook.close(); } } ``` 该代码将创建一个带有超链接的Excel模板,超链接地址为 https://www.example.com,超链接文本为 Click here to visit example.com。生成Excel文件名为 hyperlink_example.xls。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值