java 实现导出word 自定义word 使用aspose教程包含图片 for 循环 自定义参数等功能

1,aspose导入 jar包 和 java编写基础代码

下载使用 aspose-words jar包

我使用的是 aspose-words-23.3 版本的
之前版本的导出大量word内容容易报错 使用新版解决此问题

导入 aspose jar 包 使用 maven导入

mvn install:install-file -DgroupId=aspose-words -DartifactId=aspose-words -Dversion=23.3 -Dpackaging=jar -Dfile=G:\你的windows电脑的jar包路径\aspose-word\aspose-words-23.3-jdk16.jar

java代码编写

首选新建一个工具类方法

public class QualityConstants {

    /**
     * 质量检测 的督导事项id
     */
    public static final int EVENTID = 12;

    /**
     * 数字0
     */
    public static final int NUM_ZERO = 0;
    /**
     * 数字1
     */
    public static final int NUM_ONE = 1;

    /**
     * 数字2
     */
    public static final int NUM_TWO = 2;
    /**
     * 数字-1
     */
    public static final int NUM_MINUS_1 = -1;
    /**
     * 字节大小512
     */
    public static final int BYTE_512 = 512;
    /**
     * 500错误编码
     */
    public static final int CODE_500 = 500;
    /**
     * 500错误提示信息 - 状态非法
     */
    public static final String CODE_500_MSG_1 = "状态非法!";
    /**
     * 500错误提示信息 - 非督导用户不允许查看质量检测记录
     */
    public static final String CODE_500_MSG_2 = "非督导用户不允许查看质量检测记录!";
    /**
     * 500错误提示信息 - 这条质量监测已经完成!无法修改
     */
    public static final String CODE_500_MSG_3 = "这条质量监测已经完成!无法修改!";
    /**
     * 500错误提示信息 - 提交失败,材料上传不能为空
     */
    public static final String CODE_500_MSG_4 = "提交失败,材料上传不能为空";
    /**
     * 500错误提示信息 - 提交失败,请稍后重试或联系管理员
     */
    public static final String CODE_500_MSG_5 = "提交失败,请稍后重试或联系管理员!";
    /**
     * 500错误提示信息 - 提交失败,意见反馈不能为空
     */
    public static final String CODE_500_MSG_6 = "提交失败,意见反馈不能为空!";
    /**
     * 405错误编码
     */
    public static final int CODE_405 = 405;
    /**
     * 405错误提示信息 - 该信息只允许督导查看
     */
    public static final String CODE_405_MSG_1 = "该信息只允许督导查看!";
    /**
     * 200成功编码
     */
    public static final int CODE_200 = 200;
    /**
     * 200成功提示信息 - 该信息只允许督导查看
     */
    public static final String CODE_200_MSG_1 = "提交成功!";

    /**
     * 错误提示信息 - 尚未选择记录
     */
    public static final String DELETE_FAIRURE_MSG = "删除失败,尚未选择记录!";
    /**
     * 错误提示信息 - 尚未选择记录
     */
    public static final String NO_RECORD_SELECTED = "尚未选择记录!";
    /**
     * 字符编码utf-8
     */
    public static final String UTF_8 = "utf-8";
    /**
     * 默认pid
     */
    public static final int PID = 0;
    /**
     * 默认层级
     */
    public static final int DEFUALT_LAYER = 1;

    /**
     * 不适当最低得分
     */
    public static final Integer MIN_SCORE = 1;
    /**
     * 优秀最高得分
     */
    public static final Integer MAX_SCORE = 7;

    /**
     * map的hash初始值
     */
    public static final int HASH_MAP_INIT_VALUE = 32;

    /**
     * 全园平均分
     */
    public final static String WHOLE_AVERAGE = "全园平均分";
    /**
     * 查询失败
     */
    public final static String QUERY_FAIRURE = "查询失败";
    /**
     * 操作成功
     */
    public final static String SUCCESS_MSG = "操作成功!";
    /**
     * 操作失败
     */
    public final static String FARIURE_MSG = "操作失败!";
    /**
     * 导出失败
     */
    public final static String FARIURE_EXPORT = "导出失败!";

    /**
     * 请求头 - 文档
     */
    public final static String CONTENT_TYPE_WORD = "application/msword";
    /**
     * 请求头 - 下载
     */
    public final static String CONTENT_TYPE_DOWNLOAD = "application/x-download";
    /**
     * 请求头 - 二进制文件
     */
    public final static String CONTENT_TYPE_STEAM = "application/octet-stream;charset=UTF-8";
    /**
     * 请求头
     */
    public final static String USER_AGENT = "User-Agent";
    /**
     * 请求头
     */
    public final static String CONTENT_TYPE = "Content-Type";
    /**
     * 连接
     */
    public final static String CONNECTION = "Connection";
    /**
     * 关闭连接
     */
    public final static String CLOSE = "close";
    /**
     * 连接
     */
    public final static String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
    /**
     * 连接
     */
    public final static String CONTENT_DISPOSITION = "Content-Disposition";

    /**
     * 浏览器 - ie
     */
    public final static String MSIE = "MSIE";
    /**
     * 浏览器 - Firefox
     */
    public final static String FIREFOX = "Firefox";

    /**
     * 填写报告的step
     */
    public final static String MODULE_STEP3_REPORT = "qualityreport";

    /**
     * 督导下园核实的材料
     */
    public final static String MODULE_STEP1_MATERIAL = "qualitymetrail";

    /**
     * 数字3
     */
    public final static int NUM_3 = 3;
    /**
     * 数字4
     */
    public final static int NUM_4 = 4;

    /**
     * 数字5
     */
    public final static int NUM_5 = 5;
    /**
     * 数字6
     */
    public final static int NUM_6 = 6;
    /**
     * 数字7
     */
    public final static int NUM_7 = 7;
    /**
     * 数字8
     */
    public final static int NUM_8 = 8;
    /**
     * 数字9
     */
    public final static int NUM_9 = 9;
    /**
     * 数字10
     */
    public final static int NUM_10 = 10;
    /**
     * 数字11
     */
    public final static int NUM_11 = 11;

    /**
     * 数字12
     */
    public final static int NUM_12 = 12;
    /**
     * 数字13
     */
    public final static int NUM_13 = 13;
    /**
     * 数字14
     */
    public final static int NUM_14 = 14;
    /**
     * 数字15
     */
    public final static int NUM_15 = 15;
    /**
     * 数字16
     */
    public final static int NUM_16 = 16;
    /**
     * 数字17
     */
    public final static int NUM_17 = 17;
    /**
     * 数字18
     */
    public final static int NUM_18 = 18;
    /**
     * 数字19
     */
    public final static int NUM_19 = 19;
    /**
     * 数字20
     */
    public final static int NUM_20 = 20;

    /**
     * 格式化数字
     */
    public final static String DECIMAL_Format = "######.00";


}


以下为实现post导出 并且删除新生成的文件代码 需要借助工具类
传入map json的方式获取参数


    @PostMapping("/Export")
    @ResponseBody
    public void ExportWord(@RequestBody Map<String, Object> json, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String filePath = "/xxx/xxx/xx/要生成的临时word地址和名称.docx";
        String tempName = "/xxx/xxx/xx/你的word模版地址和名称.docx";
        com.aspose.words.Document doc = new com.aspose.words.Document(tempName);
        Map<String, Object> map = new HashMap<>();
        XXX  XX= new XXX();  //XXX   为你的 word要的数据的实体类 自己建 这个XXX 包含word所有需要的字段 图片 和循环体

        XX.setTitle(json.get("title").toString());  //标题
//        图片 base64  传入
        BufferedImage image = decodeBase64Image(json.get("image").toString()); //json格式传入的base64图片

        /***
         * 这里获取图片可以用路径的方式 不使用base64传进来
         */
        //BufferedImage image =  ImageIO.read(new FileInputStream("/home/123.png"));
        //BufferedImage bufferedImage = Utils.resizeBufferedImage(image, 100, 100, false);
        scivalword.setImg(image );


        setParams(doc, scivalword);

        doc.save(filePath);
        File file = new File(filePath);
        //world输出流操作
        InputStream fin = null;
        OutputStream out = null;
        try {
            fin = new FileInputStream(file);
            response.setCharacterEncoding(QualityConstants.UTF_8);
            response.setContentType(QualityConstants.CONTENT_TYPE_WORD);
            
            String filename = "demo";
            String agent = request.getHeader(QualityConstants.USER_AGENT);
            String filenameEncoder = "";
            // 根据不同的浏览器进行不同的判断
            if (agent.contains(QualityConstants.MSIE)) {
                // IE浏览器
                filenameEncoder = URLEncoder.encode(filename, QualityConstants.UTF_8);
                filenameEncoder = filenameEncoder.replace("+", " ");
            } else if (agent.contains(QualityConstants.FIREFOX)) {
                // 火狐浏览器
                BASE64Encoder base64Encoder = new BASE64Encoder();
                filenameEncoder = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes(StandardCharsets.UTF_8)) + "?=";
            } else {
                // 其它浏览器
                filenameEncoder = URLEncoder.encode(filename, QualityConstants.UTF_8);
            }
            response.setHeader(QualityConstants.ACCESS_CONTROL_ALLOW_ORIGIN, "*");//所有域都可以跨
            response.setHeader(QualityConstants.CONTENT_TYPE, QualityConstants.CONTENT_TYPE_STEAM);//二进制  流文件
            response.setHeader(QualityConstants.CONTENT_DISPOSITION, "attachment;filename=" + filenameEncoder + ".doc");//下载及其文件名
            response.setHeader(QualityConstants.CONNECTION, QualityConstants.CLOSE);//关闭请求头连接
            //设置文件在浏览器打开还是下载
            response.setContentType(QualityConstants.CONTENT_TYPE_DOWNLOAD);
            out = response.getOutputStream();
            byte[] buffer = new byte[QualityConstants.BYTE_512];
            int bytesToRead = QualityConstants.NUM_MINUS_1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != QualityConstants.NUM_MINUS_1) {
                out.write(buffer, QualityConstants.NUM_ZERO, bytesToRead);
            }
        } catch (Exception e) {
            System.out.println("导出异常");
        } finally {
            try {
                 //这里最后删除文件
                if (fin != null) {
                    fin.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (file != null) {
                    file.delete();
                }
            } catch (IOException e) {
                System.out.println("导出异常");
            }
        }

    }
     private static void setParams(Document doc, XXX vo) throws Exception { //XXX   为你的 word要的数据的实体类 自己建 这个XXX 包含word所有需要的字段 图片 和循环体
        ReportingEngine engines = new ReportingEngine();
        engines.getKnownTypes().add(xxxxx.class);//加入实体类类型 - 在foreach中用到 
        engines.buildReport(doc, new Object[]{vo}, new String[]{"st"});
    }

//获取当前日期的年月日
    public static String getCurrentDate() {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年 MM月dd日");
        return dateFormat.format(currentDate);
    }
//把字符串类型的base64图片转换成IO流给buffere 
    public static BufferedImage decodeBase64Image(String base64Image) {
        try {
            byte[] imageData = Base64.getDecoder().decode(base64Image);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageData);
            return ImageIO.read(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    

上面的代码中包含 图片 和实体类 for循环就是要在你的实体类里面插入一个 list 然后往这个list里面插入值以后
在这里插入图片描述
这里需要加入你要插入循环的实体类 给word里面获取实体类使用

在这里插入图片描述
比如我的实体类里面就有这些list 那么这些list里面的 bo就需要插入到上面的图片里面

上的代码中
XXX 为你的实体类自己创建 可以创建一个 默认的 比如

public class XXX{
	//注意 get set 方法一定要有
	private String title;
	private BufferedImage img;
	private List<entityBo> entitbo;
}

2,if判断 是否显示

这里用到word里面的if判断了
如图
在这里插入图片描述

<<if [st.getTitle() != null ]>> <<[st.getTitle()]>> <>
这里就判断了如果 传入的title不为空的情况下再进行显示

2,显示指定值

在这里插入图片描述
直接使用 就可以显示值

3,循环显示List 集合列表 使用 foreach

在这里插入图片描述

这里用到了 entitylist 进行了for循环 xxxx为
在这里插入图片描述
这里显示的实体类 必须在这里加入 否则会报错和无法使用
注意 开始 foreach就要有结束的 foreach 相对应的都是 类似于 xml格式的 word导出

注意 “String[]{“st”}” st表示在word里面的初始名称 调用关键字 比如你的实体类里面有title的字段 就用 st.getTitle() 就可以调用 如果是list就是 st.getList() 就可以调用

4,显示图片 ,

显示图片就是你的baset64复值给实体类传入以后 打开你的 word
在这里插入图片描述
点击文本框
插入到里面 在里面写入bo的img名称即可
如图
在这里插入图片描述
如果不想要外边框可以使用
在这里插入图片描述
属性里面的内容设置成无即可

附赠一个 word
在这里插入图片描述


  • 9
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现java导出动态word带有图片的步骤如下: 1. 首先,需要在Java项目中引入aspose.word的依赖。 2. 接着,需要准备好自定义word模板,可以使用Microsoft Word进行制作。在制作模板时,将需要动态填充的位置标记出来,同时为需要插入图片的位置添加一个图片控件。在这个控件的属性中,设置好图片的默认值,以及允许用户插入新的图片。 3. 在Java代码中,使用aspose.word提供的API读取自定义word模板,并且使用aspose.word提供的API将需要填充的数据填入模板中。对于需要插入图片的位置,可以使用aspose.word提供的API获取到图片控件,并且替换其中的图片。 4. 最后,将填充好数据的word文件输出即可。 以下是示例代码: ```java // 加载自定义word模板 Document doc = new Document("自定义word模板.docx"); // 获取需要填充的位置 NodeCollection<Node> nodes = doc.getChildNodes(NodeType.RUN, true); // 填充数据,这里使用了HashMap作为数据源,实际开发中可以根据实际情况使用其他数据源 HashMap<String, String> data = new HashMap<String, String>(); data.put("name", "张三"); data.put("age", "25"); data.put("address", "北京市朝阳区"); // 插入图片,这里使用了FileInputStream作为图片源,实际开发中可以根据实际情况使用其他图片源 for (Shape shape : (Iterable<Shape>) doc.getChildNodes(NodeType.SHAPE, true)) { if (shape.hasImage()) { FileInputStream imageStream = new FileInputStream("图片源.png"); shape.getImageData().setImage(imageStream); } } // 输出填充好数据的word文件 doc.save("填充好数据的word文件.docx"); ``` 以上代码演示了如何使用aspose.word自定义word模板实现java导出动态word带有图片

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值