= array(); } $post['classname'] = 'post'; } function comment_format(&$post) { global $conf, $uid, $gid, $forumlist; if (empty($post)) return; $forum = $post['fid'] ? forum_read($post['fid']) : ''; $thread = well_thread_read_cache($post['tid']); if ($thread) { //$post['fid'] = $thread['fid']; $post['closed'] = $thread['closed']; $post['subject'] = $thread['subject']; $post['url'] = $thread['url']; } else { $post['closed'] = 0; $post['subject'] = lang('thread_not_exists'); $post['url'] = ''; } $post['create_date_fmt'] = humandate($post['create_date']); //$post['message'] = stripslashes(htmlspecialchars_decode($post['message'])); $user = user_read_cache($post['uid']); $post['username'] = array_value($user, 'username'); $post['user_avatar_url'] = array_value($user, 'avatar_url'); $post['user'] = $user ? user_safe_info($user) : user_guest(); isset($post['floor']) || $post['floor'] = 0; // 权限判断 $post['allowupdate'] = 2 == array_value($forum, 'comment', 0) && ($uid == $post['uid'] || forum_access_mod($post['fid'], $gid, 'allowupdate')); $post['allowdelete'] = group_access($gid, 'allowuserdelete') && $uid == $post['uid'] || forum_access_mod($post['fid'], $gid, 'allowdelete'); $post['user_url'] = url('user-' . $post['uid'] . ($post['uid'] ? '' : '-' . $post['pid'])); if ($post['files'] > 0) { list($attachlist, $imagelist, $filelist) = well_attach_find_by_pid($post['pid']); // 使用图床 评论使用图床,mysql会过多,写死链接到内容是减轻mysql的过多的方法 if (2 == $conf['attach_on']) { foreach ($imagelist as $key => $attach) { $url = $conf['upload_url'] . 'website_attach/' . $attach['filename']; // 替换成图床 $post['message'] = FALSE !== strpos($post['message'], $url) && $attach['image_url'] ? str_replace($url, $attach['image_url'], $post['message']) : $post['message']; } } $post['filelist'] = $filelist; } else { $post['filelist'] = array(); } $post['classname'] = 'post'; } function comment_format_message(&$val) { global $conf; if (empty($val)) return; // 使用云储存 if (1 == $conf['attach_on'] && 1 == $val['attach_on']) { $val['message'] = str_replace('="upload/', '="' . file_path($val['attach_on']), $val['message']); } elseif (2 == $conf['attach_on'] && 2 == $val['attach_on']) { // 使用图床 list($attachlist, $imagelist, $filelist) = well_attach_find_by_tid($val['tid']); foreach ($imagelist as $key => $attach) { $url = $conf['upload_url'] . 'website_attach/' . $attach['filename']; // 替换成图床 $val['message'] = FALSE !== strpos($val['message'], $url) && $attach['image_url'] ? str_replace($url, $attach['image_url'], $val['message']) : $val['message']; } } else { $val['message'] = str_replace('="upload/', '="' . file_path($val['attach_on']), $val['message']); } //$val['message'] = stripslashes(htmlspecialchars_decode($val['message'])); } // 把内容中使用了云储存的附件链接替换掉 function comment_message_replace_url($pid, $message) { global $conf; if (0 == $conf['attach_on']) { $message = FALSE !== strpos($message, '="../upload/') ? str_replace('="../upload/', '="upload/', $message) : $message; $message = FALSE !== strpos($message, '="/upload/') ? str_replace('="/upload/', '="upload/', $message) : $message; } elseif (1 == $conf['attach_on']) { // 使用云储存 $message = str_replace('="' . $conf['cloud_url'] . 'upload/', '="upload/', $message); } elseif (2 == $conf['attach_on']) { // 使用图床 评论使用图床,mysql会过多,写死链接到内容是减轻mysql的过多的方法 list($attachlist, $imagelist, $filelist) = well_attach_find_by_pid($pid); foreach ($imagelist as $key => $attach) { $url = $conf['upload_url'] . 'website_attach/' . $attach['filename']; // 替换回相对链接 $message = $attach['image_url'] && FALSE !== strpos($message, $attach['image_url']) ? str_replace($attach['image_url'], $url, $message) : $message; } } return $message; } function comment_filter($val) { unset($val['userip']); return $val; } function comment_highlight_keyword($str, $k) { $r = str_ireplace($k, '' . $k . '', $str); return $r; } // //
function comment_message_format(&$s) { if (xn_strlen($s) < 100) return; $s = preg_replace('#.*?
#is', '', $s); $s = str_ireplace(array('
', '
', '
', '

', '', '', '', '' . ''), "\r\n", $s); $s = str_ireplace(array(' '), " ", $s); $s = strip_tags($s); $s = preg_replace('#[\r\n]+#', "\n", $s); $s = xn_substr(trim($s), 0, 100); $s = str_replace("\n", '
', $s); } // 对内容进行引用 function comment_quote($quotepid) { $quotepost = comment_read($quotepid); if (empty($quotepost)) return ''; $uid = $quotepost['uid']; $s = $quotepost['message']; $s = comment_brief($s, 100); $userhref = url('user-' . $uid); $user = user_read_cache($uid); $r = '
' . $user['username'] . ' ' . $s . '
'; return $r; } // 获取内容的简介 0: html, 1: txt; 2: markdown; 3: ubb function comment_brief($s, $len = 100) { $s = strip_tags($s); $s = htmlspecialchars($s); $more = xn_strlen($s) > $len ? ' ... ' : ''; $s = xn_substr($s, 0, $len) . $more; return $s; } ?>利用poi-tl生成word模板并实现行复制
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

利用poi-tl生成word模板并实现行复制

网站源码admin58浏览0评论

第一步,引入相关依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

        <!-- poi-tl依赖 -->
      <dependency>
        <groupId>com.deepoove</groupId>
           <artifactId>poi-tl</artifactId>
           <version>1.10.0</version>
       </dependency>
        <!-- Maven 依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

第二步 制作word模板

图片的循环这里使用[@xxxx]占位,普通文本字段使用{{xxxx}}占位,因为存在行复制,所以使用{{xxx}}占位后,使用[xxxx]进行占位

第三步 直接上代码

a.因为涉及到对于图片的处理,图片也要进行行循环,所以要继承AbstractRenderPolicy,话不多数,直接上代码

  public class PictureRenderPolicy extends AbstractRenderPolicy<List<PictureRenderData>>  {

        @Override
        public void doRender(RenderContext<List<PictureRenderData>> renderContext) throws Exception {
            WhereDelegate where = renderContext.getWhereDelegate();
            List<PictureRenderData> data = renderContext.getData();
            for (int i = 0; i < data.size(); i++) {
                // 目标宽度,等比例缩放图片,指定宽度
                int targetWidth = 200;
                ByteArrayInputStream in = new ByteArrayInputStream(data.get(i).getPictureSupplier().get());
                BufferedImage image = ImageIO.read(in);
                int originalWidth = image.getWidth();
                int originalHeight = image.getHeight();
                int targetHeight = (int) Math.round((double) targetWidth / originalWidth * originalHeight);
                //缩放图片
                BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics2D = scaledImage.createGraphics();
                graphics2D.drawImage(image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null);
                graphics2D.dispose();
                byte[] scaledImageData = getImageBytes(scaledImage);
                where.addPicture(new ByteArrayInputStream(scaledImageData),6,targetWidth,targetHeight);
            }
        }
        @Override
        protected void afterRender(RenderContext<List<PictureRenderData>> context) {
            // 清空标签
            clearPlaceholder(context, true);
        }

    }
    
     private static byte[] getImageBytes(BufferedImage image) throws Exception {
        File tempFile = File.createTempFile("tempImage", "");
        ImageIO.write(image, "png", tempFile);
        FileInputStream inputStream = new FileInputStream(tempFile);
        byte[] imageData = IOUtils.toByteArray(inputStream);
        inputStream.close();
        tempFile.delete();
        return imageData;
    }

最后进行测试

 @Test
    public void test5(){
       //创建行循环策略
        LoopRowTableRenderPolicy rowTableRenderPolicy = new LoopRowTableRenderPolicy();
       //告诉模板引擎,要在p做行循环,绑定行循环策略
        Configure configure = Configure.builder().bind("p", rowTableRenderPolicy).bind("c",rowTableRenderPolicy).bind("img", new PictureRenderPolicy()).bind("img1", new PictureRenderPolicy()).build();
        //创建目标文件
        File sourceFile = new File("D:\\company\\develop\\pdfdemo\\src\\main\\resources\\templates\\temp.docx");
        //构建数据
        Map<String, Object> data = new HashMap();
        data.put("projectName", "jiefei");
        data.put("date", "18");
        data.put("person1", "福建福清");
        data.put("person2", "福建福清");

        List<PictureRenderData> list = new ArrayList<>();
        PictureRenderData pictureRenderData = Pictures.ofUrl("https://gimg2.baidu/image_search/src=http%3A%2F%2Fsafe-img.xhscdn%2Fbw1%2F7f0ae7b4-0a4c-418b-b0c9-1d666caa6b47%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1690452830&t=265cd68782f20caa66f175404c784ca5")
                .size(100, 100).create();
        list.add( Pictures.ofUrl("https://gimg2.baidu/image_search/src=http%3A%2F%2Fsafe-img.xhscdn%2Fbw1%2F7f0ae7b4-0a4c-418b-b0c9-1d666caa6b47%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1690452830&t=265cd68782f20caa66f175404c784ca5")
                .size(200, 200).create());
        list.add( Pictures.ofUrl("https://gimg2.baidu/image_search/src=http%3A%2F%2Fss2.meipian.me%2Fusers%2F72978711%2Forigin6b96eb6e50aa18ec21756318da432bea.jpg%3Fmeipian-raw%2Fbucket%2Fivwen%2Fkey%2FdXNlcnMvNzI5Nzg3MTEvb3JpZ2luNmI5NmViNmU1MGFhMThlYzIxNzU2MzE4ZGE0MzJiZWEuanBn%2Fsign%2Fbeea6e21a810f6f90e231fe5f1aeb0df.jpg&refer=http%3A%2F%2Fss2.meipian.me&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1690453179&t=7849883700d28ef9905cd68b1703a846")
                .size(200, 200).create());

        List<String> c = new ArrayList<>();
        c.add("11111111111111111");
        c.add("2222222222222222222");

        Demo demo = new Demo("1",list,c ,list,c);


        Demo demo1 = new Demo("2",list,c,list,c);

        List<TestDemo> list3 = new ArrayList<>();
        TestDemo test =new TestDemo("ceshi","手动滑稽开始的");
        TestDemo test1 =new TestDemo("ceshi","手动滑稽开始的");
        list3.add(test);
        list3.add(test1);
        List<Demo> list2 = new ArrayList<>();
        list2.add(demo);
        list2.add(demo1);
        data.put("p",list2);
        data.put("c",list3);
        data.put("process","aaaa \n bbbbb");



       //创建输出流
        OutputStream os = null;
        try {
            os = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\temps.docx");
            //最终编译渲染并输出
            XWPFTemplatepile(sourceFile,configure).render(data).writeAndClose(os);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }



    }

最终结果

发布评论

评论列表(0)

  1. 暂无评论