admin 管理员组

文章数量: 887021

1.需求

导出用户信息,模板如下:

要求:导出多个用户信息时,另起一页,根据模板生成下一条用户信息。

2.模板变化

  • easypoi不能直接创建空白页(下一页),但可以使用apache的poi中的document.createParagraph().createRun().addBreak(BreakType.PAGE)来创建空白页(下一页)。
  • 根据需求需要将word总的表格动态生成多个表格,并且每个表格都需要新建空白页。例如:需要将4个user的信息导出,则模板需要变化成如下:

    然后通过easypoi使用变化后的模板导出word数据

3.具体代码如下

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.4.0</version>
        </dependency>

3.1 复制模板

目的是将初始模板改变成第二章节中的模板

package com.lylp.office.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.lylp.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * word/excel导出工具类<br>
 * <a url="http://doc.wupaas/docs/easypoi">官网文档</a>
 */
@Slf4j
public class OfficeExportUtils {

    /**
     * 复制word中的表格
     * @param templatePath 源文件
     * @param targetPath 目标文件
     * @param varPrefix 变量前缀
     * @param copyNum 拷贝数量
     * @param isNewPage 是否新增页
     */
    public static void copyWordTable(String templatePath, String targetPath, String varPrefix, int copyNum, boolean isNewPage) {
        File targetFile = new File(targetPath);
        XWPFDocument document = null;
        FileOutputStream out = null;
        try {
            document = new XWPFDocument(new FileInputStream(templatePath));
            List<XWPFTable> tables = document.getTables();
            if (CollectionUtils.isEmpty(tables)) {
                return;
            }
            List<XWPFTable> srcTables = new ArrayList<>(tables);
            for (int i = 1; i <= copyNum; i++) {
                XWPFParagraph paragraph = document.createParagraph();
                if (isNewPage) {
                    //新增空白页
                    paragraph.createRun().addBreak(BreakType.PAGE);
                }
                String newVarPreFix = "" + varPrefix + i;
                for (int j = 0; j < srcTables.size(); j++) {
                    XWPFTable srcTable = srcTables.get(j);
                    XWPFTable newTable = document.createTable();
                    for (int n = 0; n < srcTable.getRows().size(); n++) {
                        XWPFTableRow srcRow = srcTable.getRows().get(n);
                        XWPFTableRow newRow = newTable.insertNewTableRow(n);
                        copyTableRow(srcRow, newRow, varPrefix, newVarPreFix);
                    }
                    newTable.removeRow(newTable.getRows().size() - 1);
                }
            }
            out = new FileOutputStream(targetFile);
            document.write(out);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (document != null) {
                    document.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 复制word中的表格行
     * @param srcRow 源表格行
     * @param newRow 目标表格行
     * @param varPrefix 源变量前缀
     * @param newVarPreFix 新变量前缀
     */
    private static void copyTableRow(XWPFTableRow srcRow, XWPFTableRow newRow, String varPrefix, String newVarPreFix) {
        int size = srcRow.getTableCells().size();
        for (int i = 0; i < size; i++) {
            newRow.addNewTableCell();
        }
        newRow.getCtRow().setTrPr(srcRow.getCtRow().getTrPr());
        for (int i = 0; i < size; i++) {
            copyTableCell(srcRow.getCell(i), newRow.getCell(i), varPrefix, newVarPreFix);
        }
    }

    /**
     * 复制word中的表格cell
     * @param srcCell 源表格cell
     * @param newCell 目标表格cell
     * @param varPrefix 源变量前缀
     * @param newVarPreFix 新变量前缀
     */
    private static void copyTableCell(XWPFTableCell srcCell, XWPFTableCell newCell, String varPrefix, String newVarPreFix) {
        newCell.getCTTc().setTcPr(srcCell.getCTTc().getTcPr());
        for (int i = 0; i < newCell.getParagraphs().size(); i++) {
            newCell.removeParagraph(i);
        }
        for (XWPFParagraph srcParagraph : srcCell.getParagraphs()) {
            XWPFParagraph newParagraph = newCell.addParagraph();
            copyParagraph(srcParagraph, newParagraph, varPrefix, newVarPreFix);
        }
    }

    /**
     * 复制word中的表格Paragraph
     * @param srcParagraph 源表格Paragraph
     * @param newParagraph 目标表格Paragraph
     * @param varPrefix 源变量前缀
     * @param newVarPreFix 新变量前缀
     */
    private static void copyParagraph(XWPFParagraph srcParagraph, XWPFParagraph newParagraph, String varPrefix, String newVarPreFix) {
        newParagraph.getCTP().setPPr(srcParagraph.getCTP().getPPr());
        for (int i = 0; i < newParagraph.getRuns().size(); ++i) {
            newParagraph.removeRun(i);
        }
        for (XWPFRun srcRun : srcParagraph.getRuns()) {
            XWPFRun newRun = newParagraph.createRun();
            copyRun(srcRun, newRun, varPrefix, newVarPreFix);
        }
    }

    /**
     * 复制word中的表格Run
     * @param srcRun 源表格Run
     * @param newRun 目标表格Run
     * @param varPrefix 源变量前缀
     * @param newVarPreFix 新变量前缀
     */
    private static void copyRun(XWPFRun srcRun, XWPFRun newRun, String varPrefix, String newVarPreFix) {
        newRun.getCTR().setRPr(srcRun.getCTR().getRPr());
        newRun.setText(StringUtils.isNoneBlank(varPrefix) && StringUtils.isNotBlank(srcRun.text()) ? srcRun.text().replace(varPrefix, newVarPreFix) : srcRun.text());
    }

}

3.2 导出user数据

例如导出4个user数据

package com.lylp.test;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.lylp.office.utils.OfficeExportUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class UserExportTest {
    public static void main(String[] args) {
        File file = new File("E:\\workspace\\springboot-shiro-mybatis\\easypoi-office\\src\\main\\resources\\template\\userTemplate.docx");
        String temp = FileUtils.getFile(FileUtils.getTempDirectory(), UUID.randomUUID().toString() + ".docx").getAbsolutePath();
        System.out.println(temp);
        String varPrefix = "user";
        Map<String, Object> users = getUser(varPrefix);
        int copyNum = 3;
        //复制模板,由于基础模板“userTemplate.docx”中已经有一个表格,因此只需要在复制3个表格即可
        OfficeExportUtils.copyWordTable(file.getAbsolutePath(), temp, varPrefix, copyNum, true);
        //使用easypoi导出user数据
        File outFile = FileUtils.getFile(FileUtils.getTempDirectory(), UUID.randomUUID().toString() + ".docx");
        FileOutputStream out = null;
        XWPFDocument xwpfDocument = null;
        Workbook workbook = null;
        try {
            xwpfDocument = WordExportUtil.exportWord07(temp, users);
            out = new FileOutputStream(outFile);
            xwpfDocument.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (xwpfDocument != null) {
                try {
                    xwpfDocument.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 创建4个user信息
     * @param varPrefix user变量名前缀
     * @return user信息
     */
    private static Map<String, Object> getUser(String varPrefix) {
        Map<String, Object> users = new HashMap<>();
        for (int i = 0; i < 4; i++) {
            Map<String, Object> user = new HashMap<>();
            user.put("name", "张三" + i);
            user.put("sex", i % 2 == 0 ? "男" : "女");
            user.put("age", 25 + i);
            user.put("birthday", "2022-05-25");
            List<Map<String, Object>> homes = new ArrayList<>();
            for (int j = 0; j < 3; j++) {
                Map<String, Object> home = new HashMap<>();
                home.put("xh", j + 1);
                home.put("address", "四川省成都市高新区");
                home.put("no", (i + 1) + "-" + (j + 1) + "号");
                home.put("data", "2022-01-01");
                homes.add(home);
            }
            user.put("homes", homes);
            if (i == 0) {
                users.put(varPrefix, user);
            } else {
                users.put(varPrefix + i, user);
            }
        }

        return users;
    }
}

本文标签: 多组 类型 数据 空白页 java