使用easyexcel实现复杂excel表格导出

1、问题描述

        最近在做一个自动化开发票的需求,就是把网页预览的发票导出成一个excel文件。其实这个很好实现,就是使用blob就可以实现把网页的html内容导出成一个.xls的文件就行了。

Blob把html导出为excel文件_blob导入导出excel_金斗潼关的博客-CSDN博客

这种方式其实就是利用了.xls文件可以解析html文本的功能。本质上还是一个html文件只不过是将.html另存为.xls而已。因为我的logo图片是放在服务器上的,所以导出.xls的时候需访问一次服务器上logo图片的路径,才能把logo图片加载到.xls文件里面。但是海外分公司他们导出的.xls文件里面就是加载不出logo图片,起初怀疑是因为国内与海外的网络问题,再他们尝试了vpn连接后导出的.xls也是无法加载logo图片的。我排查下来,可能是与这个证书有关系。因为要访问服务器路径肯定要过一个认证的,他们的office365打开.xls文件时没有过这个证书认证,所以他们的.xls文件自然就访问不了logo图片了。

 

         因为解决不了这个证书问题,所以只能使用easyexcel写一个后端的服务,连带图片内容合成.xlsx文件。

2、解决方法

        使用Springboot整合easyExcel写一个后端接口服务

官方文档:https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write

GitHub:alibaba/easyexcel: 快速、简洁、解决大文件内存溢出的java处理Excel工具 (github.com) 

         不过,我看文档以及github上给的例子,貌似都是简单表格导出的,类似于这种:

         但我想导出的是这种样子的:其中表头是可以动态改变的

         经过我的研究,貌似easyExcel不支持这种复杂的表格样式导出。

        不过我受到了这篇文章的启发:EasyExcel实现追加写入文件_easyexcel追加写入_Lincain的博客-CSDN博客

        我们可以通过模板的形式不断的追加,即一个复杂的excel表格样式可以由若干个简单样式的模板拼接起来。         

3、我的代码

        logo.png

        pom.xml 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>easyexcelTest</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.8.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        引入easyexcel依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.7.11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>

        bo类

            把复杂的表格样式拆为若干个模板,分别用不同的实体类对应。

package com.easyexcel.bo;

import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.InputStream;

/**
 * @author Wulc
 * @date 2023/7/25 16:47
 * @description logo
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ContentRowHeight(80)
@ColumnWidth(40)
public class LogoBO {
    //logo图片
    private InputStream logoImage;
}






package com.easyexcel.bo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author Wulc
 * @date 2023/7/25 16:53
 * @description
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CompanyInfoBO {
    private String param;
}




package com.easyexcel.bo;

import com.alibaba.excel.annotation.write.style.ContentLoopMerge;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import static com.alibaba.excel.enums.poi.HorizontalAlignmentEnum.CENTER;

/**
 * @author Wulc
 * @date 2023/7/25 16:54
 * @description
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ContentStyle(horizontalAlignment = CENTER)//内容样式
public class InvoiceTitleBO {
    @ContentLoopMerge(columnExtend = 6)
    private String invoiceTitle;
}



package com.easyexcel.bo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author Wulc
 * @date 2023/7/27 17:29
 * @description
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class InvoiceInfoBO {
    private String param1;
    private String param2;
    private String param3;
    private String param4;
}




package com.easyexcel.bo;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.enums.BooleanEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import static com.alibaba.excel.enums.poi.HorizontalAlignmentEnum.CENTER;

/**
 * @author Wulc
 * @date 2023/7/28 10:02
 * @description
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ContentStyle(horizontalAlignment = CENTER, wrapped = BooleanEnum.FALSE)//内容样式
@ColumnWidth(30)
public class ProductListBO {
    @ExcelProperty("编号")
    private String item;
    @ExcelProperty("表头1")
    private String product;
    @ExcelProperty("表头2")
    private String description;
    @ExcelProperty("表头3")
    private String quantity;
    @ExcelProperty("表头4")    //表头4会动态改变
    private String unitPrice;
    @ExcelProperty("表头5")    //表头5会动态改变
    private String amount;
}

        MyExcelUtils.java
package com.easyexcel.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.easyexcel.bo.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Wulc
 * @date 2023/7/25 17:07
 * @description
 */
@Component
public class MyExcelUtils {
    /**
     * @author Wulc
     * @date 2023/7/25 17:11
     * @description 根据excel模板追加内容
     */
    public void appendExcelContent() throws IOException, NoSuchFieldException, IllegalAccessException {
        Resource resource = new ClassPathResource("/");
        String path = resource.getFile().getPath();

        //插入Logo
        String templatePath1 = path + "\\template1.xlsx";
        LogoBO logoBO = new LogoBO(this.getClass().getClassLoader().getResource("logo.png").openStream());
        List<LogoBO> logoBOList = new ArrayList<>();
        logoBOList.add(logoBO);
        EasyExcel.write(templatePath1, LogoBO.class).sheet().useDefaultStyle(false).needHead(false).doWrite(logoBOList);

        //插入公司信息
        String templatePath2 = path + "\\template2.xlsx";
        List<CompanyInfoBO> companyInfoBOList = new ArrayList<>();
        companyInfoBOList.add(new CompanyInfoBO("HelloWorld"));
        companyInfoBOList.add(new CompanyInfoBO("HelloSea"));
        companyInfoBOList.add(new CompanyInfoBO("HelloLand"));


        EasyExcel.write(templatePath2, CompanyInfoBO.class).withTemplate(new File(templatePath1)).sheet().useDefaultStyle(false).needHead(false).doWrite(companyInfoBOList);

        //插入标题
        String templatePath3 = path + "\\template3.xlsx";
        List<InvoiceTitleBO> invoiceTitleBOList = new ArrayList<>();
        invoiceTitleBOList.add(new InvoiceTitleBO("标题"));

        EasyExcel.write(templatePath3, InvoiceTitleBO.class).withTemplate(new File(templatePath2)).sheet().useDefaultStyle(false).needHead(false).doWrite(invoiceTitleBOList);

        //插入Invoice内容
        String templatePath4 = path + "\\template4.xlsx";
        List<InvoiceInfoBO> invoiceInfoBOList = new ArrayList<>();
        invoiceInfoBOList.add(new InvoiceInfoBO("param1", "信息1", "param6", "信息6"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param2", "信息2", "param7", "信息7"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param3", "信息3", "param8", "信息8"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param4", "信息4", "param9", "信息9"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param5", "信息5", "", ""));
        EasyExcel.write(templatePath4, InvoiceInfoBO.class).withTemplate(new File(templatePath3)).sheet().useDefaultStyle(false).needHead(false).doWrite(invoiceInfoBOList);

        //插入产品清单
        String templatePath5 = path + "\\template5.xlsx";
        //动态改变表头,我是用了反射,通过改变@ExcelProperty注解的value的值实现改变表头
        ProductListBO productListBO = new ProductListBO();
        Field field1 = productListBO.getClass().getDeclaredField("unitPrice");
        Field field2 = productListBO.getClass().getDeclaredField("amount");
        ExcelProperty excelProperty1 = field1.getAnnotation(ExcelProperty.class);
        ExcelProperty excelProperty2 = field2.getAnnotation(ExcelProperty.class);
        InvocationHandler invocationHandler1 = Proxy.getInvocationHandler(excelProperty1);
        InvocationHandler invocationHandler2 = Proxy.getInvocationHandler(excelProperty2);
        Field declaredField1 = invocationHandler1.getClass().getDeclaredField("memberValues");
        Field declaredField2 = invocationHandler2.getClass().getDeclaredField("memberValues");
        declaredField1.setAccessible(true);
        declaredField2.setAccessible(true);
        Map memberValues1 = (Map) declaredField1.get(invocationHandler1);
        Map memberValues2 = (Map) declaredField1.get(invocationHandler2);
        String[] a1 = new String[1];
        String[] a2 = new String[1];
        a1[0] = "表头44";    //设置表头的值
        a2[0] = "表头55";    //设置表头的值
        memberValues1.put("value", a1);
        memberValues2.put("value", a2);
        List<ProductListBO> productListBOList = new ArrayList<>();
        productListBOList.add(new ProductListBO("1", "产品1", "描述1", "10", "10", "200"));
        productListBOList.add(new ProductListBO("2", "产品2", "描述2", "20", "10", "300"));
        productListBOList.add(new ProductListBO("3", "产品3", "描述3", "20", "10", "300"));
        EasyExcel.write(templatePath5, productListBO.getClass()).withTemplate(new File(templatePath4)).sheet().useDefaultStyle(true).needHead(true).doWrite(productListBOList);
        
    }

}

         

        ExcelTest .java

package com.easyexcel;

import com.easyexcel.util.MyExcelUtils;
import com.easyexcel.util.MyExcelUtils2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

/**
 * @author Wulc
 * @date 2023/7/28 20:08
 * @description
 */
@SpringBootTest(classes = SpringbootApplication.class)
@RunWith(SpringRunner.class)
public class ExcelTest {
    @Autowired
    private MyExcelUtils myExcelUtils;

    @Test
    public void test1() throws IOException, NoSuchFieldException, IllegalAccessException {
        myExcelUtils.appendExcelContent();
    }
}

测试一下。

 你会发现在target目录下的test-classes(因为是@test单元测试启动的,所以构建编译文件都放在target/test-classes下面)有5个.xlsx文件,分别对应MyExcelUtils.java中的template1~5。其中template1~4为过程文件,就是你每个模板依次拼接得到的中间文件。template5为你最终想要的。在实际开发中,可以在生成了template5后就把template1~4文件给删掉,只保留一个template5.xlsx供下载,下载好template5后再把template5.xlsx也给删掉就行了。

修改一下appendExcelContent()方法,返回值改为File类型,并且合成了template5后再把template1~4删掉

MyExcelUtils.java

package com.easyexcel.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.easyexcel.bo.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Wulc
 * @date 2023/7/25 17:07
 * @description
 */
@Component
public class MyExcelUtils {
    /**
     * @author Wulc
     * @date 2023/7/25 17:11
     * @description 根据excel模板追加内容
     */
    public File appendExcelContent() throws IOException, NoSuchFieldException, IllegalAccessException {
        Resource resource = new ClassPathResource("/");
        String path = resource.getFile().getPath();

        //插入Logo
        String templatePath1 = path + "\\template1.xlsx";
        LogoBO logoBO = new LogoBO(this.getClass().getClassLoader().getResource("logo.png").openStream());
        List<LogoBO> logoBOList = new ArrayList<>();
        logoBOList.add(logoBO);
        EasyExcel.write(templatePath1, LogoBO.class).sheet().useDefaultStyle(false).needHead(false).doWrite(logoBOList);

        //插入公司信息
        String templatePath2 = path + "\\template2.xlsx";
        List<CompanyInfoBO> companyInfoBOList = new ArrayList<>();
        companyInfoBOList.add(new CompanyInfoBO("HelloWorld"));
        companyInfoBOList.add(new CompanyInfoBO("HelloSea"));
        companyInfoBOList.add(new CompanyInfoBO("HelloLand"));


        EasyExcel.write(templatePath2, CompanyInfoBO.class).withTemplate(new File(templatePath1)).sheet().useDefaultStyle(false).needHead(false).doWrite(companyInfoBOList);

        //插入标题
        String templatePath3 = path + "\\template3.xlsx";
        List<InvoiceTitleBO> invoiceTitleBOList = new ArrayList<>();
        invoiceTitleBOList.add(new InvoiceTitleBO("标题"));

        EasyExcel.write(templatePath3, InvoiceTitleBO.class).withTemplate(new File(templatePath2)).sheet().useDefaultStyle(false).needHead(false).doWrite(invoiceTitleBOList);

        //插入Invoice内容
        String templatePath4 = path + "\\template4.xlsx";
        List<InvoiceInfoBO> invoiceInfoBOList = new ArrayList<>();
        invoiceInfoBOList.add(new InvoiceInfoBO("param1", "信息1", "param6", "信息6"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param2", "信息2", "param7", "信息7"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param3", "信息3", "param8", "信息8"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param4", "信息4", "param9", "信息9"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param5", "信息5", "", ""));
        EasyExcel.write(templatePath4, InvoiceInfoBO.class).withTemplate(new File(templatePath3)).sheet().useDefaultStyle(false).needHead(false).doWrite(invoiceInfoBOList);

        //插入产品清单
        String templatePath5 = path + "\\template5.xlsx";
        //动态改变表头,我是用了反射,通过改变@ExcelProperty注解的value的值实现改变表头
        ProductListBO productListBO = new ProductListBO();
        Field field1 = productListBO.getClass().getDeclaredField("unitPrice");
        Field field2 = productListBO.getClass().getDeclaredField("amount");
        ExcelProperty excelProperty1 = field1.getAnnotation(ExcelProperty.class);
        ExcelProperty excelProperty2 = field2.getAnnotation(ExcelProperty.class);
        InvocationHandler invocationHandler1 = Proxy.getInvocationHandler(excelProperty1);
        InvocationHandler invocationHandler2 = Proxy.getInvocationHandler(excelProperty2);
        Field declaredField1 = invocationHandler1.getClass().getDeclaredField("memberValues");
        Field declaredField2 = invocationHandler2.getClass().getDeclaredField("memberValues");
        declaredField1.setAccessible(true);
        declaredField2.setAccessible(true);
        Map memberValues1 = (Map) declaredField1.get(invocationHandler1);
        Map memberValues2 = (Map) declaredField1.get(invocationHandler2);
        String[] a1 = new String[1];
        String[] a2 = new String[1];
        a1[0] = "表头44";    //设置表头的值
        a2[0] = "表头55";    //设置表头的值
        memberValues1.put("value", a1);
        memberValues2.put("value", a2);
        List<ProductListBO> productListBOList = new ArrayList<>();
        productListBOList.add(new ProductListBO("1", "产品1", "描述1", "10", "10", "200"));
        productListBOList.add(new ProductListBO("2", "产品2", "描述2", "20", "10", "300"));
        productListBOList.add(new ProductListBO("3", "产品3", "描述3", "20", "10", "300"));
        EasyExcel.write(templatePath5, productListBO.getClass()).withTemplate(new File(templatePath4)).sheet().useDefaultStyle(true).needHead(true).doWrite(productListBOList);
        new File(templatePath1).delete();
        new File(templatePath2).delete();
        new File(templatePath3).delete();
        new File(templatePath4).delete();
        return new File(templatePath5);
    }

}
ExcelController.java
package com.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.easyexcel.entity.DemoData;
import com.easyexcel.util.MyExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author Wulc
 * @date 2023/7/20 16:02
 * @description
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {
    @Autowired
    private MyExcelUtils myExcelUtils;

    @GetMapping("/exceldownload")
    public void exceldownload(HttpServletResponse response) throws IOException, NoSuchFieldException, IllegalAccessException {
        File file = myExcelUtils.appendExcelContent();
        try {
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        file.delete();  //下载完后,把文件删除
    }

}

 4、总结

        在使用过程中发现easyExcel不支持Object类型,每一行数据对应一个实体类,每个单元格对应该实体类的一个属性,但这个属性必须是确切的类型,不支持Object属性。

解决EasyExcel不支持解析List以及实体类对象问题_easyexcel list_小熊学Java的博客-CSDN博客

这就造成了,如果是复杂的表格样式,比如第一行是图片,第二行是文字,你就必须定义两个实体类分别对应第一行与第二行的内容。不能一个实体类定义Object属性搞定,这个就不是很方便,希望easyExcel开发者下一版中可以支持Object类型。 

5、参考资料

EasyExcel自定义各种合并策略 - 掘金

IDEA打包时clean报错Failed to delete_柠檬气泡水~的博客-CSDN博客

EasyExcel实现追加写入文件_easyexcel追加写入_Lincain的博客-CSDN博客

easyexcel 自适应(行宽, 行高)_easyexcel自适应行高__Mr丶s的博客-CSDN博客

记录java使用EasyExcel进行单元格内换行操作_easyexcel 换行_阿任_的博客-CSDN博客

Java反射动态修改注解的值_修改注解的value值_ChihoiTse的博客-CSDN博客

SpringBoot实现文件下载的几种方式_spring boot 文件下载_user2025的博客-CSDN博客

注意事项:

        我这些只是本地测试,所以文件都是直接获取操作的resources目录。如果是发布打jar包的话,其实要改一下文件路径的。

        可以参考这篇:

运行jar包出现class path resource[] cannot be resolved to absolute file path because it does not XXX_金斗潼关的博客-CSDN博客

2023/10/18补充

       

        之前我是通过反射修改@ExcelProperty注解value的方式设置导出的excel的表头。不过在实际生产中发现。使用反射修改注解值,有可能出现修改无效导致表头的值没有被动态的改变。我又看了下easyexcel的官方文档,发现其实不用专门通过反射去修改@ExcelProperty注解的值实现对表头行的动态修改,其实easyexcel本身就提供了head()的方法,支持在写入excel的时候再设置表头。写Excel | Easy Excel (alibaba.com)

MyExcelUtils.java
 /**
     * @author Wulc
     * @date 2023/10/18 15:50
     * @description 根据excel模板追加内容
     */
    public File appendExcelContent() throws IOException, NoSuchFieldException, IllegalAccessException {
        Resource resource = new ClassPathResource("/");
        String path = resource.getFile().getPath();

        //插入华讯Logo
        String templatePath1 = path + "\\template1.xlsx";
        LogoBO logoBO = new LogoBO(this.getClass().getClassLoader().getResource("logo.png").openStream());
        List<LogoBO> logoBOList = new ArrayList<>();
        logoBOList.add(logoBO);
        EasyExcel.write(templatePath1, LogoBO.class).sheet().useDefaultStyle(false).needHead(false).doWrite(logoBOList);

        //插入公司信息
        String templatePath2 = path + "\\template2.xlsx";
        List<CompanyInfoBO> companyInfoBOList = new ArrayList<>();
        companyInfoBOList.add(new CompanyInfoBO("HelloWorld"));
        companyInfoBOList.add(new CompanyInfoBO("HelloSea"));
        companyInfoBOList.add(new CompanyInfoBO("HelloLand"));


        EasyExcel.write(templatePath2, CompanyInfoBO.class).withTemplate(new File(templatePath1)).sheet().useDefaultStyle(false).needHead(false).doWrite(companyInfoBOList);

        //插入标题
        String templatePath3 = path + "\\template3.xlsx";
        List<InvoiceTitleBO> invoiceTitleBOList = new ArrayList<>();
        invoiceTitleBOList.add(new InvoiceTitleBO("标题"));

        EasyExcel.write(templatePath3, InvoiceTitleBO.class).withTemplate(new File(templatePath2)).sheet().useDefaultStyle(false).needHead(false).doWrite(invoiceTitleBOList);

        //插入Invoice内容
        String templatePath4 = path + "\\template4.xlsx";
        List<InvoiceInfoBO> invoiceInfoBOList = new ArrayList<>();
        invoiceInfoBOList.add(new InvoiceInfoBO("param1", "信息1", "param6", "信息6"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param2", "信息2", "param7", "信息7"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param3", "信息3", "param8", "信息8"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param4", "信息4", "param9", "信息9"));
        invoiceInfoBOList.add(new InvoiceInfoBO("param5", "信息5", "", ""));
        EasyExcel.write(templatePath4, InvoiceInfoBO.class).withTemplate(new File(templatePath3)).sheet().useDefaultStyle(false).needHead(false).doWrite(invoiceInfoBOList);

        //插入产品清单
        String templatePath5 = path + "\\template5.xlsx";
        //动态改变表头,我是用了反射,通过改变@ExcelProperty注解的value的值实现改变表头
        ProductListBO productListBO = new ProductListBO();
//        Field field1 = productListBO.getClass().getDeclaredField("unitPrice");
//        Field field2 = productListBO.getClass().getDeclaredField("amount");
//        ExcelProperty excelProperty1 = field1.getAnnotation(ExcelProperty.class);
//        ExcelProperty excelProperty2 = field2.getAnnotation(ExcelProperty.class);
//        InvocationHandler invocationHandler1 = Proxy.getInvocationHandler(excelProperty1);
//        InvocationHandler invocationHandler2 = Proxy.getInvocationHandler(excelProperty2);
//        Field declaredField1 = invocationHandler1.getClass().getDeclaredField("memberValues");
//        Field declaredField2 = invocationHandler2.getClass().getDeclaredField("memberValues");
//        declaredField1.setAccessible(true);
//        declaredField2.setAccessible(true);
//        Map memberValues1 = (Map) declaredField1.get(invocationHandler1);
//        Map memberValues2 = (Map) declaredField1.get(invocationHandler2);
//        String[] a1 = new String[1];
//        String[] a2 = new String[1];
//        a1[0] = "表头44";
//        a2[0] = "表头55";
//        memberValues1.put("value", a1);
//        memberValues2.put("value", a2);
        
        
        List<List<String>> heads = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<>();
        List<String> head1 = new ArrayList<>();
        List<String> head2 = new ArrayList<>();
        List<String> head3 = new ArrayList<>();
        List<String> head4 = new ArrayList<>();
        List<String> head5 = new ArrayList<>();
        head0.add("编号");
        head1.add("表头1");
        head2.add("表头2");
        head3.add("表头3");
        head4.add("表头44");
        head5.add("表头55");

        heads.add(head0);
        heads.add(head1);
        heads.add(head2);
        heads.add(head3);
        heads.add(head4);
        heads.add(head5);

        List<ProductListBO> productListBOList = new ArrayList<>();
        productListBOList.add(new ProductListBO("1", "产品1", "描述1", "10", "10", "200"));
        productListBOList.add(new ProductListBO("2", "产品2", "描述2", "20", "10", "300"));
        productListBOList.add(new ProductListBO("3", "产品3", "描述3", "20", "10", "300"));
        EasyExcel.write(templatePath5, productListBO.getClass()).head(heads).withTemplate(new File(templatePath4)).sheet().useDefaultStyle(true).needHead(true).doWrite(productListBOList);
        new File(templatePath1).delete();
        new File(templatePath2).delete();
        new File(templatePath3).delete();
        new File(templatePath4).delete();
        return new File(templatePath5);
    }

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金斗潼关

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值