通过easypoi导出word文档

x33g5p2x  于2021-12-16 转载在 其他  
字(6.8k)|赞(0)|评价(0)|浏览(665)

一 pom文件

<?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>demo2022</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- easypoi-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.1.0</version>
        </dependency>
        <!-- 防止控制台打印错误提示-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.6</version>
        </dependency>
    </dependencies>
</project>

二 实体类

package word;

import cn.afterturn.easypoi.excel.annotation.Excel;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

/**
* @className: Student
* @description: 学生信息
* @date: 2021/12/16
* @author: cakin
*/
public class Student implements Serializable {
    private static final long serialVersionUID = 2131321500629905052L;

    @Excel(name = "学生姓名")
    private String studentName;

    @Excel(name = "学生年龄")
    private Integer age;

    @Excel(name = "学生生日", importFormat = "yyyy/MM/dd", exportFormat = "yyyy/MM/dd")
    private Date birthday;

    @Excel(name = "语文成绩")
    private BigDecimal chineseScore;

    @Excel(name = "数学成绩")
    private BigDecimal mathScore;

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public BigDecimal getChineseScore() {
        return chineseScore;
    }

    public void setChineseScore(BigDecimal chineseScore) {
        this.chineseScore = chineseScore;
    }

    public BigDecimal getMathScore() {
        return mathScore;
    }

    public void setMathScore(BigDecimal mathScore) {
        this.mathScore = mathScore;
    }
}

三 测试类

package word;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.params.ExcelListEntity;
import cn.afterturn.easypoi.word.parse.excel.ExcelEntityParse;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
* @className: WordUtils
* @description: 参考文档
* https://blog.csdn.net/dingfengbo1203/article/details/106229844
* https://blog.csdn.net/YangangwuWuyangang/article/details/115206209
* @date: 2021/12/16
* @author: cakin
*/
public class WordTest {
    private static final String TEMPLATE_FILE_NAME = "D:/template.docx";
    private static final String TEMPLATE_FILE_NAME_JOB = "D:/template_job.docx";

    public static void main(String[] args) {
        // 简单文档导出
        SimpleWordExport();
        // 列表导出
        ExportList();
        // 导出工作经历
        exportJob();
    }

    /**
     * 功能描述:简单文档导出
     *
     * @author cakin
     * @date 2021/12/16
     */
    public static void SimpleWordExport() {
        Map<String, Object> map = new HashMap<>();
        map.put("0", "one");
        map.put("1", "two");
        map.put("2", "three");
        map.put("3", "four");
        map.put("4", "five");
        map.put("5", "six");
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(
                    TEMPLATE_FILE_NAME, map);
            FileOutputStream fos = new FileOutputStream("D:/simpleWord.docx");
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述:列表导出
     *
     * @author cakin
     * @date 2021/12/16
     */
    public static void ExportList() {
        Map<String, Object> map = new HashMap<>();
        map.put("0", "one");
        map.put("1", "two");
        map.put("2", "three");
        map.put("3", "four");
        map.put("4", "five");
        map.put("5", "six");
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(TEMPLATE_FILE_NAME, map);
            List<Student> list = new ArrayList<>(2);
            addStudents(list);
            // 导出批量数据
            new ExcelEntityParse().parseNextRowAndAddRow(doc.getTableArray(1), 1, new ExcelListEntity(list, Student.class, 1));

            FileOutputStream fos = new FileOutputStream("D:/simpleList.docx");
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述:增加学生到列表中
     *
     * @param list 列表
     * @author 贝医
     * @date 2021/12/16
     */
    private static void addStudents(List<Student> list) {
        Student stu = new Student();
        stu.setStudentName("wuyuan");
        stu.setAge(11);
        stu.setBirthday(new Date());
        stu.setChineseScore(new BigDecimal("88"));
        stu.setMathScore(new BigDecimal("85.5"));
        list.add(stu);
        stu = new Student();
        stu.setStudentName("lisi");
        stu.setAge(12);
        stu.setBirthday(new Date());
        stu.setChineseScore(new BigDecimal("87"));
        stu.setMathScore(new BigDecimal("89"));
        list.add(stu);
    }

    /**
     * 功能描述:导出工作经历
     *
     * @author cakin
     * @date 2021/12/16
     */
    public static void exportJob() {
        try {
            try (FileOutputStream fos = new FileOutputStream("d:/expJob.docx")) {
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("title", "个人信息");
                Map<String, String> user = new HashMap<>();
                user.put("name", "张三");
                user.put("age", "22");
                user.put("address", "重庆渝北区");
                user.put("other", "篮球");
                dataMap.put("user", user);

                List<Map<String, String>> jobs = new ArrayList<>();
                Map<String, String> job;
                for (int i = 0; i < 5; i++) {
                    job = new HashMap<>();
                    job.put("name", "公司名称-" + i);
                    job.put("address", "公司地址:" + i);
                    jobs.add(job);
                }

                dataMap.put("jobs", jobs);
                byte[] doc = exportWord(TEMPLATE_FILE_NAME_JOB, dataMap);
                fos.write(doc);
                fos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出word(2007版本docx)
     *
     * @param templateWordPath 模板路径
     * @param dataMap          导出数据
     * @return 导出数据
     * @throws Exception
     */
    public static byte[] exportWord(String templateWordPath, Map<String, Object> dataMap) throws Exception {
        File tf = new File(templateWordPath);
        if (!tf.exists() || !tf.isFile()) {
            throw new RuntimeException("File [" + templateWordPath + "] Not Found Or Not File.");
        }
        XWPFDocument document = WordExportUtil.exportWord07(templateWordPath, dataMap);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        document.write(bos);
        return bos.toByteArray();
    }
}

四 两个模板

模板位置如下:

1 template.docx 的内容

2 template_job.docx 的内容

五 运行后的结果

1 simpleWord.docx 的内容

2 simpleList.docx 的内容

3 expJob.docx 的内容

相关文章