easyExce模板填充生成Excel的实际操作,多sheet页处理

       之前使用word作为文件模板,添加变量生成word文件,现在需要使用Excel作为文件模板填充变量生成Excel,首先考虑使用国产的esayExcel进行填充生成,easyExcel官网地址

https://easyexcel.opensource.alibaba.com/docs/current/

 下面看一下我这里需要制作的模板信息,这里包含普通变量,表格循环和图片展示,模板文件信   息如下

 生成后的文件截图

具体代码如下,这里需要注意表格循环后面还有变量的话,填充的配置一定要是这个

FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

 会自动换行

package com.example.demo.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qiankun.hu
 * @version 1.0.0
 * @createTime 2022年07月26日 13:47:00
 * @Description easyExcel模板填充
 */
public class EasyExcelUtil {

    public static void main(String[] args) throws MalformedURLException {

        List<Map<String, Object>> paramValueMapListNew = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Map<String, Object> cmap = new HashMap<>();
            cmap.put("id", i);
            cmap.put("name", "药品" + i);
            cmap.put("guige",  i +"ml" );
            paramValueMapListNew.add(cmap);
        }

        long begin = System.currentTimeMillis();
        //设置输出流和模板信息
        ExcelWriter excelWriter = EasyExcel.write("D:\\workSpace\\66.xlsx").withTemplate("D:\\workSpace\\easy模板1.xlsx").build();
        WriteSheet writeSheet0 = EasyExcel.writerSheet(0).build();
        //开启自动换行,自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(new FillWrapper("user", paramValueMapListNew), fillConfig, writeSheet0);
        excelWriter.fill(new FillWrapper("site", paramValueMapListNew), fillConfig, writeSheet0);

        FillConfig fillConfig2 = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
        excelWriter.fill( paramValueMapListNew, fillConfig2, writeSheet0);

        Map<String, Object> map = new HashMap<>();
        map.put("title", "药品回收记录单");
        map.put("total", 1000);
        map.put("time", "2022年07月22日13:28:28");
        map.put("image", new URL("https://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fimg.jj20.com%252Fup%252Fallimg%252F4k%252Fs%252F02%252F2109242306111155-0-lp.jpg%26refer%3Dhttp%253A%252F%252Fimg.jj20.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1661051088%26t%3D66856c9f40dffe887a63f02f856d8637&thumburl=https%3A%2F%2Fimg0.baidu.com%2Fit%2Fu%3D3798217922%2C3880088897%26fm%3D253%26fmt%3Dauto%26app%3D120%26f%3DJPEG%3Fw%3D889%26h%3D500"));
        excelWriter.fill(map, writeSheet0);
        excelWriter.finish();
        System.out.println(System.currentTimeMillis() - begin);

    }
}

 easyExcel maven版本

        <!--easyExcel-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.0</version>
        </dependency>

 如果是多个sheet页制作,需要多个  WriteSheet 信息

WriteSheet writeSheet0 = EasyExcel.writerSheet(0).build();   信息,改变其中的数字既可,多个sheet页参数信息不公用,

代码如下

        WriteSheet writeSheet0 = EasyExcel.writerSheet(0).build();
        //开启自动换行,自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        FillConfig fillConfig2 = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
        //excelWriter.fill(paramValueMapListNew, fillConfig, writeSheet);
        excelWriter.fill(new FillWrapper("user", paramValueMapListNew), fillConfig, writeSheet0);
        excelWriter.fill(new FillWrapper("site", paramValueMapListNew), fillConfig, writeSheet0);
        excelWriter.fill( paramValueMapListNew, fillConfig2, writeSheet0);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("title", "药品回收记录单");
        map1.put("total", 1000);
        map1.put("time", "2022年07月22日13:28:28");
        map1.put("image", new URL("https://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fimg.jj20.com%252Fup%252Fallimg%252F4k%252Fs%252F02%252F2109242306111155-0-lp.jpg%26refer%3Dhttp%253A%252F%252Fimg.jj20.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1661051088%26t%3D66856c9f40dffe887a63f02f856d8637&thumburl=https%3A%2F%2Fimg0.baidu.com%2Fit%2Fu%3D3798217922%2C3880088897%26fm%3D253%26fmt%3Dauto%26app%3D120%26f%3DJPEG%3Fw%3D889%26h%3D500"));
        excelWriter.fill(map1, writeSheet0);


        WriteSheet writeSheet1 = EasyExcel.writerSheet(1).build();
        excelWriter.fill(new FillWrapper("user", paramValueMapListNew), fillConfig, writeSheet1);
        excelWriter.fill(new FillWrapper("site", paramValueMapListNew), fillConfig, writeSheet1);
        excelWriter.fill( paramValueMapListNew, fillConfig2, writeSheet1);
        map1.put("image", new URL("https://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fimg.jj20.com%252Fup%252Fallimg%252F4k%252Fs%252F02%252F2109242306111155-0-lp.jpg%26refer%3Dhttp%253A%252F%252Fimg.jj20.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1661051088%26t%3D66856c9f40dffe887a63f02f856d8637&thumburl=https%3A%2F%2Fimg0.baidu.com%2Fit%2Fu%3D3798217922%2C3880088897%26fm%3D253%26fmt%3Dauto%26app%3D120%26f%3DJPEG%3Fw%3D889%26h%3D500"));
        excelWriter.fill(map1, writeSheet1);

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Java中根据模板导出Excel报表并复制模板生成多个Sheet,可以使用Apache POI库。下面是一个简单的示例代码,可以将一个模板文件复制多次,并分别填充不同的数据,生成多个Sheet: ```java import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ExcelExporter { public static void main(String[] args) throws IOException { // 加载模板文件 FileInputStream templateFile = new FileInputStream("template.xls"); Workbook templateWorkbook = new HSSFWorkbook(templateFile); // 获取模板中的样式和格式 Sheet templateSheet = templateWorkbook.getSheetAt(0); Row templateRow = templateSheet.getRow(0); Cell templateCell = templateRow.getCell(0); CellStyle templateStyle = templateCell.getCellStyle(); DataFormat templateFormat = templateWorkbook.createDataFormat(); // 模拟数据 List<Map<String, Object>> data = new ArrayList<>(); for (int i = 1; i <= 3; i++) { Map<String, Object> map = new HashMap<>(); map.put("name", "Tom" + i); map.put("age", 20 + i); data.add(map); } // 遍历数据,复制模板填充数据 for (int i = 0; i < data.size(); i++) { Map<String, Object> map = data.get(i); // 复制模板 Sheet sheet = templateWorkbook.cloneSheet(0); templateWorkbook.setSheetName(templateWorkbook.getSheetIndex(sheet), "Sheet" + (i + 1)); // 填充数据 for (int j = 0; j < sheet.getLastRowNum() + 1; j++) { Row row = sheet.getRow(j); if (row == null) { row = sheet.createRow(j); } for (int k = 0; k < row.getLastCellNum(); k++) { Cell cell = row.getCell(k); if (cell == null) { cell = row.createCell(k); } String value = getValueForCell(cell, map); cell.setCellValue(value); cell.setCellStyle(templateStyle); if (value.matches("\\d+")) { // 如果是数字,设置单元格格式 cell.setCellStyle(getNumericCellStyle(templateWorkbook, templateStyle, templateFormat)); } } } } // 删除模板Sheet templateWorkbook.removeSheetAt(0); // 将工作簿保存到文件 FileOutputStream fileOut = new FileOutputStream("workbook.xls"); templateWorkbook.write(fileOut); fileOut.close(); System.out.println("Excel文件导出成功!"); } // 获取单元格的值 private static String getValueForCell(Cell cell, Map<String, Object> map) { String value = ""; if (cell.getCellType() == CellType.STRING) { value = cell.getStringCellValue(); if (value.startsWith("$")) { // 如果是占位符,替换为数据 value = map.get(value.substring(1)).toString(); } } return value; } // 获取数字类型单元格的样式 private static CellStyle getNumericCellStyle(Workbook workbook, CellStyle style, DataFormat format) { CellStyle newStyle = workbook.createCellStyle(); newStyle.cloneStyleFrom(style); newStyle.setDataFormat(format.getFormat("#,##0.00")); return newStyle; } } ``` 以上代码中,我们首先加载一个模板文件,并获取其中的样式和格式。接下来,我们模拟了一个数据集,然后遍历数据集,复制模板填充数据,生成多个Sheet。在填充数据时,我们首先遍历每个单元格,判断其是否为占位符,如果是,则替换为对应的数据。接着,我们将单元格的值设置为填充后的数据,并设置单元格的样式和格式。最后,我们删除了模板Sheet,并将工作簿保存到文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值