您的位置:首页 > 编程语言 > Java开发

java基于freemarker导出指定word格式带多图片源码。

2016-10-18 15:12 513 查看
1.把word转换成xml

2.把要替换的地方用${name}替代,name就是显示的数据。例:

3.然后另存为ftl格式保存。

4,附上代码

/**

     * 导出驾驶培训电子教学日志 word格式

     *

     * @return

     */

    public boolean on_export_classhours_log() {

        this.createWord();

        if (true) {

            msg = "<script type=\"text/javascript\">alert('导出成功到D盘!');</script>";

        } else {

            msg = "<script type=\"text/javascript\">alert('导出失败!');</script>";

        }

        return true;

    }

    private Configuration configuration = null;

    public void createWord() {

        Map<String, Object> dataMap = new HashMap<String, Object>();

        getData(dataMap);

        configuration.setClassForTemplateLoading(this.getClass(), "");// 模板文件所在路径

        Template t = null;

        try {

            t = configuration.getTemplate("bxjxrz.ftl"); // 获取模板文件

        } catch (IOException e) {

            e.printStackTrace();

        }

        File outFile = new File("D:/outFile/" + Math.random() * 10000 + ".doc"); // 导出文件

        Writer out = null;

        try {

            out = new BufferedWriter(new OutputStreamWriter(

                    new FileOutputStream(outFile)));

        } catch (FileNotFoundException e1) {

            e1.printStackTrace();

        }

        try {

            t.process(dataMap, out); // 将填充数据填入模板文件并输出到目标文件

        } catch (TemplateException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    /**

     * 导出的学时数据

     *

     * @param dataMap

     */

    private void getData(Map<String, Object> dataMap) {

        String nowid = queryDetail.getValue();

        VPClasshoursstatic vpchs = cdao.findById(nowid);

        this.getContext().getSession().removeAttribute("vpchs");

        this.getContext().getSession().setAttribute("vpchs", vpchs);

        Date btime = vpchs.getBegintime();

        String year = DateUtil.getYearPart(btime);

        String month = DateUtil.getMonthPart(btime);

        String day = DateUtil.getDayPart(btime);

        SimpleDateFormat simDateFormat = new SimpleDateFormat("HH:mm");

        String kssjString = simDateFormat.format(vpchs.getBegintime());

        String jssjString = simDateFormat.format(vpchs.getEndtime());

        PersonAllHoursViwe pAllHoursViwe = new PersonAllHoursViwe();

        List<PersonAllHoursViwe> pAllHours = pDao.findByProperty("iccardid",

                vpchs.getIccardid());

        dataMap.put("jpjgmc", vpchs.getEnterprisename());

        dataMap.put("xyxm", vpchs.getName());

        dataMap.put("xybh", vpchs.getTableno());

        dataMap.put("yyyy", year);

        dataMap.put("mm", month);

        dataMap.put("dd", day);

        dataMap.put("image1", getImageOne());

        dataMap.put("image2", getImageTwo());

        dataMap.put("kssj", kssjString);

        dataMap.put("jssj", jssjString);

        dataMap.put("jly", vpchs.getTrainman());

        dataMap.put("jlcph", vpchs.getCartno());

        dataMap.put("cx", vpchs.getVehicletypename());

        dataMap.put("zxs", pAllHours.get(0).getTotalhours());

        dataMap.put("bcxs", vpchs.getEBtime());

        dataMap.put("bclc", "");

        dataMap.put("bcsd", "");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        for (int i = 0; i < 10; i++) {

            Map<String, Object> map = new HashMap<String, Object>();

            map.put("jpjgmc", i);

            map.put("xyxm", i);

            map.put("xybh", i);

            map.put("yyyy", i);

            map.put("mm", i);

            map.put("dd", i);

            map.put("image1", i);

            map.put("image2", i);

            map.put("kssj", i);

            map.put("jssj", i);

            map.put("jly", i);

            map.put("jlcph", i);

            map.put("cx", i);

            map.put("zxs", i);

            map.put("bcxs", i);

            map.put("bclc", i);

            map.put("bcsd", i);

            list.add(map);

        }

        dataMap.put("list", list);

    }

    /**

     * 获取第一个照片

     *

     * @return

     */

    private String getImageOne() {

        List listImage = getImageList();

        if (listImage.size()>0) {

            return setImage((String) listImage.get(0));

        }

        return setImage(basePath+"/jxtrain/img/photo2.png");

    }

    /**

     * 获取第二个照片

     *

     * @return

     */

    private String getImageTwo() {

        List listImage = getImageList();

        if (listImage.size()>=2) {

            return setImage((String) listImage.get(1));

        }

        return setImage(basePath+"/jxtrain/img/photo2.png");

    }

    /**

     * 接收照片地址转换成输出编码

     *

     * @return

     */

    private Strin
a1ba
g setImage(String listImage) {

        String imgFile = "";

        InputStream is = null;

        byte[] data = null;

        if (!"".equals(listImage) && listImage != null) {

            imgFile = listImage;

        } else {

            imgFile = basePath+"/jxtrain/img/photo2.png";

        }

        try {

            BufferedImage bufferImg = ImageIO.read(new URL(imgFile));

            ByteArrayOutputStream bs = new ByteArrayOutputStream();

            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);

            ImageIO.write(bufferImg, "jpg", imOut); // scaledImage1为BufferedImage,jpg为图像的类型

            is = new ByteArrayInputStream(bs.toByteArray());

            data = new byte[is.available()];

            is.read(data);

            is.close();

        } catch (MalformedURLException e1) {

            e1.printStackTrace();

        } catch (IOException e1) {

            e1.printStackTrace();

        }

        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(data);

    }

    /**

     * 从数据库获取照片列表

     */

    private List getImageList() {

        listTime = new ArrayList();

        listImg = new ArrayList();

        String nowid = queryDetail.getValue();

        if (nowid == null || nowid.equals("")) {

            // condition.append("无相片!");

        } else {

            this.getContext().getSession().removeAttribute("persionid");

            this.getContext().getSession().setAttribute("persionid", nowid);

            Object object2 = this.getContext().getSession().getAttribute(

                    "persionid");

            VPClasshoursstatic vpch = (VPClasshoursstatic) this.getContext()

                    .getSession().getAttribute("vpchs");

            List personlist = cdao.querycondition("idcard ='"

                    + vpch.getIdcard() + "'");

            this.getContext().getSession().removeAttribute("personlist");

            this.getContext().getSession().setAttribute("personlist",

                    personlist);

            Object object1 = this.getContext().getSession().getAttribute(

                    "personlist");

            String cartid = null;

            String endtime = null;

            String begintime = null;

            String image = "image";// 默认查本月

            // condition.append("<table cellspacing=\"0\" cellpadding=\"0\"

            // border=\"0\"> <tr>");

            SimpleDateFormat gobalFormat = new SimpleDateFormat(

                    "yyyy-MM-dd HH:mm:ss");

            SimpleDateFormat NowFormat = new SimpleDateFormat("yyyyMM");

            Connection conn = null;

            PreparedStatement psmt = null;

            ResultSet rs = null;

            if (object1 != null && object2 != null) {

                try {

                    List lsit = (ArrayList) object1;

                    String persionid = (String) object2;

                    for (int s = 0; s < lsit.size(); s++) {

                        VPClasshoursstatic vPClasshoursstatic = (VPClasshoursstatic) lsit

                                .get(s);

                        // System.out.printhln(vPClasshoursstatic.getId().toString());

                        if (vPClasshoursstatic.getId().toString().equals(

                                persionid)) {

                            cartid = vPClasshoursstatic.getCartid();

                            endtime = gobalFormat.format(vPClasshoursstatic

                                    .getEndtime());

                            // System.out.println(endtime);

                            begintime = gobalFormat.format(vPClasshoursstatic

                                    .getBegintime());

                            // System.out.println(endtime);

                        }

                    }

                    String TimeWhere = NowFormat.format(DateUtil

                            .getDateFromStr(begintime));// 条件时间

                    String NowTime = NowFormat.format(DateUtil.getNowDate());// 当前时间

                    if (!TimeWhere.equals(NowTime)) {

                        image += TimeWhere;

                    }

                    String sql = "select imageaddress,gpstime from "

                            + image

                            + " t where t.caroid='"

                            + cartid

                            + "' and t.gpstime between to_date('"

                            + begintime

                            + "','yyyy-mm-dd hh24:mi:ss') and to_date('"

                            + endtime

                            + "','yyyy-mm-dd hh24:mi:ss') order by t.gpstime asc";

                    // System.out.print(sql);

                    conn = DataUtil.getConnection();

                    psmt = conn.prepareStatement(sql);

                    rs = psmt.executeQuery();

                    while (rs.next()) {

                        // condition.append("<td>");

                        String imageaddress = rs.getString("imageaddress");

                        String gpstime = gobalFormat.format(rs

                                .getTimestamp("gpstime"));

                        listTime.add(gpstime);

                        listImg.add(basePath218 + imageaddress);

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                } finally {

                    DataUtil.close(conn, psmt, rs);

                }

            }

        }

        return listImg;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: