Word导出01

word导入的时候,如果有图片,poi图片可以抓出,但是不能定位位置,目前没有想到好的解决方案。

word导出,纯文本用的是poi,图文的文档用docx4j。

还有FreeMarker,用xml/ftl里面封装要导出格式的文档,设置key,最后通过map封装,导出word,我是用mac开发的,有一些问题没有成功,下面我把代码贴出来,有兴趣的研究。

 private Configuration configuration = null;


    public exportQuestionWord() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
    }


    public void createDoc(Map<String,Object> dataMap, String fileName) throws UnsupportedEncodingException {
        //dataMap 要填入模本的数据文件
        //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
        //这里我们的模板是放在包下面
        configuration.setClassForTemplateLoading(this.getClass(), "/");
        Template t=null;
        try {
            configuration.setObjectWrapper(new DefaultObjectWrapper());
            //设置异常处理器
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
            //test.ftl为要装载的模板 /Users/limeng/Public/工具/workspace/lmlog/src/test/java/com/icu/util/fb.ftl
            t = configuration.getTemplate("fb.xml","utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //输出文档路径及名称
        File outFile = new File(fileName);
        Writer out = null;
        FileOutputStream fos=null;
        try {
            fos = new FileOutputStream(outFile);
            OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
            //这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
            //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
            out = new BufferedWriter(oWriter,10240);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }


        try {
            t.process(dataMap, out);
            out.flush();
            out.close();
            fos.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


  List<String> list1 = new ArrayList<>();//题目

   List<Question> list=parseWord("/Users/limeng/word/bbb2.docx");//数据集合,可以换数据源替换
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("xytitle",list.get(0));

            for (int i = 1; i < list.size(); i++) {
                list1.add(list.get(i));
            }

            dataMap.put("xycontent",list1.toString());

            edoc.createDoc(dataMap, "/Users/limeng/word/aaa3.doc");

猜你喜欢

转载自blog.csdn.net/qq_19968255/article/details/78455441