程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(5)

FreeMarker导出world表格插入图片

发布于2021-03-07 22:01     阅读(1315)     评论(0)     点赞(27)     收藏(1)


1、FreeMarker简介

FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
在线手册:

制作ftl模版

将文档另存为xml格式,再将xml格式手动更改为ftl格式放到项目中
将文档另存为xml格式,再将xml格式手动更改为ftl格式放到项目中
在上面中整理代码

这就是所设置的key这就是所设置的key
图片则是base64编码的字符串
图片则是base64编码的字符串
这里要将字符串删掉换成你所需要的key,如:
在这里插入图片描述
如过是多张图片则需要加一个list标签
注意事项

代码、工具类

/**
     * 通过 ftl 文件装填 result 数据生成静态文件
     * @param templatePath
     * 			模板路径
     * @param templateName
     * 			模板名称
     * @param result
     * 			模板参数
     * @throws IOException
     * @throws TemplateException
     */
    public  AjaxResult createFile(String templatePath, String templateName, Map result) throws IOException, TemplateException{
        String wordFilename = encodingFilename("工作记录.docx");
        // 路径加名称
        String fileName = getAbsoluteFile(wordFilename);
        templateName = "demo.ftl";
        Configuration config = new Configuration();
        config.setDirectoryForTemplateLoading(new File(templatePath));
        config.setObjectWrapper(new DefaultObjectWrapper());

        Template template = config.getTemplate(templateName, "UTF-8");

        FileOutputStream fileOut = new FileOutputStream(fileName);
        Writer out = new OutputStreamWriter(fileOut, "UTF-8");
        try {
            template.process(result, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();
        return AjaxResult.success(wordFilename);
    }

/**
     * 编码文件名
     */
    public String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename;
        return filename;
    }



    public String getAbsoluteFile(String filename) {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
/**
     * 任务world导出
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult taskWorldExport(String id) throws IOException, TemplateException {

        FileInputStream fis = null;
        OutputStream os = null;
        // 获取任务详情
        TbTask task = this.taskMapper.selectTaskInfoById(id);

        // 获取现场照片
        List<TbTaskFile> list = this.taskMapper.getLivePhotos(id, TaskFileType.LIVE_PHOTOS.getCode());
        list.stream().forEach(item -> item.setFilePath(this.baseApi + item.getFilePath()));

        // 获取其他照片
        List<TbTaskFile> listOther = this.taskMapper.getLivePhotos(id, TaskFileType.OTHER_PHOTOS.getCode());
        listOther.stream().forEach(item -> item.setFilePath(this.baseApi + item.getFilePath()));

        SimpleDateFormat date = new SimpleDateFormat("yyyy年MM月dd日");
        String dateFormat = date.format(task.getDate());
        SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
        String timeFormat = time.format(task.getTime());
        Map<String,Object> map = new HashMap<>();
        map.put("taskName",task.getTaskName());
        map.put("taskNature",task.getTaskValue());
        map.put("date",dateFormat);
        map.put("time",timeFormat);
        map.put("organizer",task.getOrganizer());
        map.put("participant",task.getParticipant());
        map.put("onSiteName",task.getOnSiteName());
        map.put("taskValue",task.getTaskValue());
        map.put("problemSolution",task.getProblemSolution());

        List<String> str = new ArrayList<>();
        List<String> str1 = new ArrayList<>();
        for (TbTaskFile entity: list) {
            str.add(image2byte(entity.getFilePath()));
        }

        for (TbTaskFile entity: listOther) {
            str1.add(image2byte(entity.getFilePath()));

        }


        map.put("image",str);
        map.put("list",str1);
        return new WordUtil().createFile(this.path,"",map);
    }
/**
     * @Description: 根据图片地址转换为base64编码字符串
     * @Author:
     * @CreateTime:
     * @return
     */
    public String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    public String image2byte(String path) throws IOException {
        byte[] data = null;
        URL url = null;
        InputStream input = null;
        try{
            url = new URL(path);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        data = output.toByteArray();
        output.close();
        input.close();
        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(data);
    }

在这里插入图片描述

希望对您有所帮助。。。

原文链接:https://blog.csdn.net/weixin_44677704/article/details/114411911




所属网站分类: 技术文章 > 博客

作者:前端霸主

链接:http://www.qianduanheidong.com/blog/article/33526/39a448c4707de5553812/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

27 0
收藏该文
已收藏

评论内容:(最多支持255个字符)