word模版导出

由于需要导出图片,所以需要用到poi4.1以上

pom.xml

 <!--   导出到word(循环图片)     -->
        <!-- word导出  方式:easypoi-->
        <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>
        <!--注意:word中要使用循环等标签必须单独导入以下依赖-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>

导入jar

 

 我原来是3.9换成4.1.2有不少代码是不一样的

jdk6换成了jdk8

换成:

style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

 添加

 

 

 少架包

package com.hits.util;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

public class WordUtil {


    /**
     * word模版下载
     * @param templatePath 模版路径
     * @param temDir 生成文件路径
     * @param fileName 文件名称
     * @param params 数据
     * @param request
     * @param response
     */
    public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        /*Assert.notNull(templatePath,"模板路径不能为空");
        Assert.notNull(temDir,"临时文件路径不能为空");
        Assert.notNull(fileName,"导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");*/
        if (!temDir.endsWith("/")){
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {

            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            delFileWord(temDir,fileName);//这一步看具体需求,要不要删
        }
    }

    /**
     * 删除零时生成的文件
     */
    public static void delFileWord(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        File file1 = new File(filePath);
        file.delete();
        file1.delete();
    }

    /**
     * word模版下载
     * @param templatePath 模版路径
     * @param temDir 生成文件路径
     * @param fileName 文件名称
     * @param params 数据
     */
    public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) {
        /*Assert.notNull(templatePath,"模板路径不能为空");
        Assert.notNull(temDir,"临时文件路径不能为空");
        Assert.notNull(fileName,"导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");*/
        if (!temDir.endsWith("/")){
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {

            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            delFileWord(temDir,fileName);//这一步看具体需求,要不要删
        }
    }

}
  public String data(HttpSession session, HttpServletRequest req) {
        System.out.println("====================================");
        String msg = "";
        try {
            //导出表头信息
            //定义一个Map集合params
            Map<String, Object> params = new HashMap<>();
            //模板文件的路径templatePath
            String templatePath = "E:/template/patrolWord.docx"; //模板路径

            //简单渲染文本
            params.put("gsmc", "公司");
            params.put("gsdz", "大厦");

            ImageEntity image = new ImageEntity();
            image.setHeight(30);
            image.setWidth(30);
            image.setUrl("E:/template/profile.jpg"); //url路径
            //image.setData(out.toByteArray()); //字节流读取
            //设置读取图片方式(必须)
            image.setType(ImageEntity.URL);
            //表格外添加简单图片
            params.put("logo", image);

            //声明了一个名为alarms的变量,它是一个List类型,其中每个元素都是一个Map<String, Object>类型的键值对集合。
            List<Map<String, Object>> alarms = new ArrayList<>();

            //序号从1开始
            int order = 1;
            for (int i = 0; i < 3; i++) {

                //创建了一个名为alarm的新的HashMap对象
                Map<String, Object> alarm = new HashMap<>();
                //将循环中获取到的信息添加到集合里面
                //变电站
//                    alarm.put("name", taskResultEquipment.getTaskName());
                //设备名称
                alarm.put("order", order);
                alarm.put("xm", "张三" + i);
                alarm.put("xb", "男");
                alarm.put("sjh", "1865603568" + i);
                //表格内循环添加图片(easypoi 4.3以后才支持,不然只能打印出ImageEntity的内存地址)

                //创建了一个名为simage的新的ImageEntity对象,并将其赋值给simage变量。
                // 具体来说,ImageEntity是一个Java类,用于表示一个图像实体,其中包含了图像的各种属性和数据。
                ImageEntity simage = new ImageEntity();
                simage.setHeight(50);
                simage.setWidth(50);
                //将图片的本地路径导入进去
                simage.setUrl("E:/template/profile.jpg");
                //将simage对象的类型设置为URL类型。
                //该图像实体表示的是一个通过URL链接获取的远程图像,而不是一个本地存储的图像。
                simage.setType(ImageEntity.URL);
//                    ByteArrayOutputStream out = new ByteArrayOutputStream();
//                    simage.setData(out.toByteArray()); //字节流读取
                //将图片添加进去
                alarm.put("tx", simage);
                //alarms是一个里面元素都是map的list集合
                alarms.add(alarm);
                order = order + 1;
            }

            //Map集合params,将jobs(元素为map的list集合添加进去)
            params.put("ry", alarms);
            //定义了一个表示模板文件夹路径的字符串变量temDir,用于存储模板文件所在的文件夹的路径。
            // 在这个例子中,temDir指向E:/template/file/word/路径。表示文件路径分隔符,可以是\或者/,具体取决于操作系统
            String temDir = "E:" + File.separator + "template" + File.separator + "word" + File.separator ;
            ;//生成临时文件存放地址
            //生成文件名
            Long time = new Date().getTime();
            // 生成的word格式
            String formatSuffix = ".docx";
            // 拼接后的文件名
            String fileName = time + formatSuffix;//文件名  带后缀
            //导出word
            WordUtil.exportWord(templatePath, temDir, fileName, params);
            msg = temDir + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            msg = "操作失败";
        }
        return msg;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值