java使用easypoi导出word文档,包含图片,表格,文字;

添加依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>word-export</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>word-export</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.19</version>
        </dependency>
        <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>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

ExportUtil类

package com.example.wordexport.utils;

import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

/**
 * @author chenbin
 * @date 2021/10/11
 */
public class ExportUtil {
    public static void export(Map<String, Object> map, String url, File tempFile) {

        try {
            XWPFDocument doc = WordExportUtil.exportWord07(url, map);
            FileOutputStream fos = new FileOutputStream(tempFile);
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

JFreeChartToFileUtil类

package com.example.wordexport.utils;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import java.awt.*;
import java.io.File;

public class JFreeChartToFileUtil {

    public static void createPieChart(DefaultPieDataset pds, File file,String title) {
        try {
            // 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
            JFreeChart chart = ChartFactory.createPieChart(title, pds, false, false, true);
            // 如果不使用Font,中文将显示不出来
            Font font = new Font("宋体", Font.BOLD, 12);
            // 设置图片标题的字体
            chart.getTitle().setFont(font);
            // 得到图块,准备设置标签的字体
            PiePlot plot = (PiePlot) chart.getPlot();
            // 设置标签字体
            plot.setLabelFont(font);
            plot.setStartAngle(3.14f / 2f);
            // 设置plot的前景色透明度
            plot.setForegroundAlpha(0.7f);
            // 设置plot的背景色透明度
            plot.setBackgroundAlpha(0.0f);
            // 设置标签生成器(默认{0})
            // {0}:key {1}:value {2}:百分比 {3}:sum
            plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}占{2}"));
            // 将内存中的图片写到本地硬盘
            ChartUtilities.saveChartAsJPEG(file, chart, 600, 300);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createBarChart(CategoryDataset pds, File file,String title) {
        try {
            // 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
            JFreeChart chart = ChartFactory.createBarChart3D(title, null,
                    null, pds, PlotOrientation.VERTICAL,
                    true, true, true);
            // 如果不使用Font,中文将显示不出来
            Font font = new Font("宋体", Font.BOLD, 12);
            // 设置图片标题的字体
            chart.getTitle().setFont(font);
            chart.getLegend().setItemFont(font);
            // 得到图块,准备设置标签的字体
            CategoryPlot plot = (CategoryPlot) chart.getPlot();
            // 设置plot的前景色透明度
            plot.setForegroundAlpha(0.7f);
            // 设置plot的背景色透明度
            plot.setBackgroundAlpha(0.0f);
            // 设置标签生成器(默认{0})

            ValueAxis rangeAxis = plot.getRangeAxis();
            CategoryAxis domainAxis = plot.getDomainAxis();

            rangeAxis.setLabelFont(font);
            rangeAxis.setTickLabelFont(font);
            domainAxis.setLabelFont(font);
            domainAxis.setTickLabelFont(font);
            domainAxis.setMaximumCategoryLabelLines(10);
            domainAxis.setMaximumCategoryLabelWidthRatio(0.5f);

            // 将内存中的图片写到本地硬盘
            ChartUtilities.saveChartAsJPEG(file, chart, 600, 300);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ExportController类

package com.example.wordexport.controller;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.example.wordexport.utils.ExportUtil;
import com.example.wordexport.utils.JFreeChartToFileUtil;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
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.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author chenbin
 * @date 2021/10/11
 */
@RestController
public class ExportController {

    @RequestMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/msword");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("测试.docx", StandardCharsets.UTF_8.name()));
        OutputStream outputStream = response.getOutputStream();


        Map<String, Object> map = new HashMap<String, Object>();

        putBaseInfo(map);
        //putImg(map);
        putList(map);

        zhuzhuangtu(map);
        //putBar(map);


        String url =  Objects.requireNonNull(getClass().getClassLoader().getResource("export.docx")).getPath();

        File tempFile = File.createTempFile("tempDoc", ".docx");

        ExportUtil.export(map, url, tempFile);


        InputStream in = new FileInputStream(tempFile);

        //创建存放文件内容的数组
        byte[] buff = new byte[1024];
        //所读取的内容使用n来接收
        int n;
        //当没有读取完时,继续读取,循环
        while ((n = in.read(buff)) != -1) {
            //将字节数组的数据全部写入到输出流中
            outputStream.write(buff, 0, n);
        }
        //强制将缓存区的数据进行输出
        outputStream.flush();
        //关流
        outputStream.close();
        in.close();
        tempFile.deleteOnExit();

    }


    private void putBaseInfo(Map<String, Object> map) {
        map.put("department", "Easypoi");
        map.put("person", "JueYue");
        map.put("time", "234234");
    }

    private void putImg(Map<String, Object> map) {
        ImageEntity image = new ImageEntity();
        image.setHeight(200);
        image.setWidth(500);
        image.setUrl("C:\\Users\\chenbin\\Pictures\\1.jpg");
        image.setType(ImageEntity.URL);
        map.put("img", image);
    }

    private void putBar(Map<String, Object> map) throws IOException {

        File file2 = File.createTempFile("temp", "jpg");


        DefaultPieDataset pds = new DefaultPieDataset();

        pds.setValue("上市公司股票", 100);
        pds.setValue("非上市公司股权", 200);
        pds.setValue("传统不良债权", 300);
        pds.setValue("抵债资产", 400);
        pds.setValue("投资性房地产", 500);
        pds.setValue("长期股权投资", 600);

        JFreeChartToFileUtil.createPieChart(pds, file2, "账面价值比例");

        ImageEntity image = new ImageEntity();
        image.setHeight(200);
        image.setWidth(500);
        System.out.println(file2.getAbsolutePath());
        image.setUrl(file2.getAbsolutePath());
        image.setType(ImageEntity.URL);
        map.put("img", image);
    }

    public void zhuzhuangtu(Map<String, Object> dataMap) throws IOException {
        File file2 = File.createTempFile("temp", "jpg");
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();


        List<String> nameList = new ArrayList<>();
        nameList.add("广东省");
        nameList.add("河南省");
        nameList.add("内蒙古自治区");
        nameList.add("黑龙江省");
        nameList.add("新疆");
        nameList.add("湖北省");
        nameList.add("辽宁省");
        nameList.add("山东省");
        nameList.add("陕西省");
        nameList.add("上海市");
        nameList.add("贵州省");
        nameList.add("重庆市");
        nameList.add("西藏自治区");
        nameList.add("安徽省");
        nameList.add("福建省");
        nameList.add("湖南省");
        nameList.add("海南省");
        nameList.add("江苏省");
        nameList.add("广西");
        nameList.add("宁夏");
        nameList.add("青海省");
        nameList.add("江西省");
        nameList.add("浙江省");
        nameList.add("山西省");
        nameList.add("四川省");
        nameList.add("香港特别行政区");
        nameList.add("澳门特别行政区");
        nameList.add("云南省");
        nameList.add("北京市");
        nameList.add("天津市");
        nameList.add("吉林省");


        List<String> areaList = new ArrayList<>();

        nameList.forEach(i -> {
            if (i.contains("省")) {
                areaList.add(i.replace("省", ""));
            } else if (i.contains("特别行政区")) {
                areaList.add(i.replace("特别行政区", ""));
            } else if (i.contains("市")) {
                areaList.add(i.replace("市", ""));
            } else if (i.contains("自治区")) {
                areaList.add(i.replace("自治区", ""));
            } else {
                areaList.add(i);
            }
        });


        areaList.forEach(i -> {
            dataset.setValue(23434, "账面价值", i);
        });

        areaList.forEach(i -> {
            dataset.setValue(34234234, "估值结果", i);
        });

        JFreeChartToFileUtil.createBarChart(dataset, file2, "资产结果");
        ImageEntity image = new ImageEntity();
        image.setHeight(200);
        image.setWidth(500);
        System.out.println(file2.getAbsolutePath());
        image.setUrl(file2.getAbsolutePath());
        image.setType(ImageEntity.URL);
        dataMap.put("img", image);
    }

    private void putList(Map<String, Object> map) {
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Map<String, String> map1 = new HashMap<>();
            map1.put("name", "xiao");
            map1.put("age", "12");

            list.add(map1);
        }

        map.put("list", list);
    }

}

模板

在这里插入图片描述

导出结果

在这里插入图片描述

源码地址

https://gitee.com/xiaodonglegal/word-export

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一点博客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值