easypoi excel导出

本文介绍如何使用Easypoi简化Java项目中Excel的导入导出操作。包括添加依赖、实现文件下载功能、定义Excel实体类及具体的服务层实现等步骤。

easypoi相对于poi多了一个easy,顾名思义就是更简单了,具体复杂的操作,比如模板导出什么的可以看官网,这里分享一个常规操作
1、加入依赖

<!--easypoi-->
        <dependency>
            <groupId>org.jeecg</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>2.4.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jeecg/easypoi-annotation -->
        <dependency>
            <groupId>org.jeecg</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>2.4.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jeecg/easypoi-base -->
        <dependency>
            <groupId>org.jeecg</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>2.4.0</version>
        </dependency>

2、加入自己的一个文件下载类

package com.dpy.platform.common.util;

import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author zhuenbang
 * @description
 * @date 2018/7/26 14:42
 */
public class FileDownload {
    public static void fileDownload(final HttpServletResponse response, byte[] file, String fileName) throws Exception {
        byte[] data = file;
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();

    }

    public static byte[] getBytes(Workbook workbook) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        return os.toByteArray();
    }
}

3、加入导出excel的实体类

package com.dpy.platform.common.vo.nature;

import com.dpy.platform.common.entity.nature.NatureInvoice;
import com.dpy.platform.common.enums.nature.InvoiceEnums;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecgframework.poi.excel.annotation.ExcelTarget;

/**
 * @author zhuenbang
 * @description
 * @date 2018/7/26 16:36
 */
@ExcelTarget(value = "natureInvoiceExcel")
public class NatureInvoiceExcel {
    @Excel(name = "订单号",width = 30)
    private String orderId;//订单id
    @Excel(name = "发票介质",width = 30)
    private String invoiceType;//0纸质发票1电子发票
    @Excel(name = "发票内容",width = 30)
    private String invoiceContent;//发票内容
    @Excel(name = "发票抬头",width = 30)
    private String invoiceBelong;//0企业1个人
    //private String invoiceLookUp;//发票抬头名称
    @Excel(name = "收票人",width = 30)
    private String invoiceRecipient;//收件人
    @Excel(name = "收票地址/邮箱",width = 30)
    private String invoiceAddres;//邮件地址
    //private String invoiceTaxNo;// 纳税号
    //private String invoicePhoneNumber;//联系号码
    // private String invoiceEmail;//邮箱
    @Excel(name = "发票状态",width = 30)
    private String invoiceFlag;//是否开发票
    @Excel(name = "商家",width = 30)
    private String merchants = "得便宜";//商家

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public String getInvoiceType() {
        return invoiceType;
    }

    public void setInvoiceType(String invoiceType) {
        this.invoiceType = invoiceType;
    }

    public String getInvoiceContent() {
        return invoiceContent;
    }

    public void setInvoiceContent(String invoiceContent) {
        this.invoiceContent = invoiceContent;
    }

    public String getInvoiceBelong() {
        return invoiceBelong;
    }

    public void setInvoiceBelong(String invoiceBelong) {
        this.invoiceBelong = invoiceBelong;
    }

    public String getInvoiceRecipient() {
        return invoiceRecipient;
    }

    public void setInvoiceRecipient(String invoiceRecipient) {
        this.invoiceRecipient = invoiceRecipient;
    }

    public String getInvoiceAddres() {
        return invoiceAddres;
    }

    public void setInvoiceAddres(String invoiceAddres) {
        this.invoiceAddres = invoiceAddres;
    }

    public String getInvoiceFlag() {
        return invoiceFlag;
    }

    public void setInvoiceFlag(String invoiceFlag) {
        this.invoiceFlag = invoiceFlag;
    }

    public String getMerchants() {
        return merchants;
    }

    public void setMerchants(String merchants) {
        this.merchants = merchants;
    }

    public NatureInvoiceExcel() {
    }

    public NatureInvoiceExcel(NatureInvoice natureInvoice) {
        if (natureInvoice != null) {
            this.orderId = natureInvoice.getOrderId();
            this.invoiceType = InvoiceEnums.InvoiceType.getByCode(natureInvoice.getInvoiceType()).getMsg();
            this.invoiceBelong = InvoiceEnums.InvoiceBelong.getByCode(natureInvoice.getInvoiceBelong()).getMsg();
            this.invoiceContent = natureInvoice.getInvoiceContent();
            //this.invoiceTaxNo = natureInvoice.getInvoiceTaxNo();
            this.invoiceRecipient = natureInvoice.getInvoiceRecipient() + "" + natureInvoice.getInvoicePhoneNumber();
            //this.invoiceEmail = natureInvoice.getInvoiceEmail();
            this.invoiceAddres = natureInvoice.getInvoiceAddres() != null ? natureInvoice.getInvoiceAddres() : natureInvoice.getInvoiceEmail();
            this.invoiceFlag = InvoiceEnums.InvoiceFlag.getByCode(natureInvoice.getInvoiceFlag() == true ? 1 : 0).getMsg();
            this.merchants = "得便宜";
        }
    }
}

4、具体service导出操作的代码

 @Override
    public void exportexcelInvoice(NatureInvoiceParam natureInvoiceParam, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<NatureInvoice> invoiceList = natureInvoiceaAdminDao.exportexcelInvoice(natureInvoiceParam);
        List<NatureInvoiceExcel> excelList = invoiceList.stream().map(NatureInvoiceExcel::new)
                .collect(Collectors.toList());
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("发票列表",
                "发票列表"), NatureInvoiceExcel.class, excelList);
        FileDownload.fileDownload(response, FileDownload.getBytes(workbook), DateUtil.currentDate() + "发票列表.xls");
    }

5、最后导出的exce截图
这里写图片描述

要使用 EasyPoi 库实现 Excel 导出并嵌入图片,可以通过以下步骤进行操作: ### 实体类定义 在实体类中,需要定义一个 `byte[]` 类型的字段来存储图片数据,并使用 `@Excel` 注解来指定该字段在 Excel 中的表现形式。例如,可以设置图片的宽度、高度以及图片类型等属性。 ```java import cn.afterturn.easypoi.excel.annotation.Excel; public class Talen { @Excel(name = "签收单号", width = 30) private String signingRemark; @Excel(name = "签收单", width = 40, type = 2, height = 20, imageType = 2) private byte[] uploadSignPhotos; @Excel(name = "备注", width = 30) private String remark; // Getters and Setters } ``` ### 导出逻辑 在导出逻辑中,首先创建 `ExportParams` 对象并设置 sheet 名称。然后使用 `ExcelExportUtil.exportExcel` 方法将数据导出Excel 文件。为了确保图片能够正确显示,还需要手动调整行高。 ```java import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.util.ExcelExportUtil; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Sheet; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class ExcelExporter { public void exportExcelWithImages() { List<Talen> list = new ArrayList<>(); // 填充 list 数据 ExportParams params = new ExportParams(); params.setSheetName("sheet1"); int listCount = 0; if (!list.isEmpty()) { listCount = list.size(); } Workbook workbook = ExcelExportUtil.exportExcel(params, Talen.class, list); if (listCount > 0) { Sheet sheet0 = workbook.getSheet("sheet1"); for (int i = 1; i < listCount + 1; i++) { sheet0.getRow(i).setHeight((short) 2000); } } try { // 设置响应头和输出流 WebUtil.setResponseFile("测试.xlsx"); WebUtil.getResponse().setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); OutputStream outputStream = WebUtil.getResponse().getOutputStream(); workbook.write(outputStream); } catch (Exception e) { throw new BaseException("导出excel失败", e); } finally { try { workbook.close(); } catch (Exception e) { // 处理异常 } } } } ``` ### 注意事项 - **图片数据获取**:确保从数据库或网络(如阿里云 OSS)获取的图片 URL 能够被转换为 `byte[]` 格式。 - **图片大小**:根据需求合理设置单元格的宽度和高度,以保证图片Excel 中显示正常。 - **性能优化**:如果导出的数据量较大,建议对代码进行性能优化,避免内存溢出。 通过以上步骤,可以成功使用 EasyPoi 库实现 Excel 导出并嵌入图片的功能[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值