栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

添加依赖


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.5
         
    
    com.example
    word-export
    0.0.1-SNAPSHOT
    word-export
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.jfree
            jfreechart
            1.0.19
        
        
            cn.afterturn
            easypoi-base
            4.4.0
        
        
            cn.afterturn
            easypoi-web
            4.4.0
        
        
            cn.afterturn
            easypoi-annotation
            4.4.0
        
        
            junit
            junit
            4.13.2
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



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;


public class ExportUtil {
    public static void export(Map 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.*;


@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 map = new HashMap();

        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 map) {
        map.put("department", "Easypoi");
        map.put("person", "JueYue");
        map.put("time", "234234");
    }

    private void putImg(Map 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 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 dataMap) throws IOException {
        File file2 = File.createTempFile("temp", "jpg");
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();


        List 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 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 map) {
        List> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Map map1 = new HashMap<>();
            map1.put("name", "xiao");
            map1.put("age", "12");

            list.add(map1);
        }

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

}

模板

导出结果

源码地址

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/314874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号