aspose.words通过书签导出word文件

一:导入aspose.words.jar

二:在word里要导出字段的位置,用书签标记,给一个key。将word放入需要获取模板的位置。

三:

  /**

  *功能:导出xxx

  *

  *@param targetFilePath 目标路径

  *@param templatePath 模板路径

  *@param map 数据

  *return File

  *throws IOException

  */

  public File exportWordText(String targetFilePath,String templatePath,Map map){

    String jvmPath= System.getProperty("jvmPath");//由于正式环境存放的盘不一定和开发环境的相同,通过jvm配置的路径。

    File temlateFile = jvmPath+templatePath;

    if(!temlateFile.exists()){

      throw new IllegalArgumentException("参数有误:指定模板不存在");

    }

    File targetFile = null;

    if(StringUtils.isEmpty(targetFilePath)){

      targetFilePath= "这里是要导出的位置"; 

    }

    targetFile = new File("targetFilePath");

    if(!targetFile.exists() || !targetFile.isFile()){

      targetFil.createNewFile();

    }

 

    if(!targetFile.exists() || !targetFile.isFile()){

      throw new IOException("目标文件无法创建");

    }

    FileUtils.copyFile(temlateFile,targetFile)

    doDaraToFile(targetFilePath,map);//注入数据到文件

  }

 

  

 /**

  *功能:导出xxx

  *

  *@param targetFilePath 目标路径

 

  *@param map 数据

 

 

  */

  private static void doDataToFile(String targetFilePath,Map map){

    try{

      Document doc = new Document(targetFilePath);

      if(doc !=null && doc.HaoMacros()){//涉及到Document的save操作前都将含有的宏清除。

        doc.remove();

      }

      DocumentBuilder builder = new DocumentBuilder(doc);//生成解析器

      BookMarkCollection bColl = doc.getRange().getBookmarks();

      for(int bkIndex = (bColl.getCount()-1);bkIndex>=0;bkIndex--){

        Bookmark bk = bColl.get(bkIndex);

        String mkname = bk.getName();

        Set keySet = map.keySet();

        Iterator<String> ketIt = keySet.Iterator();

        Object v = null;

        while(keyIt.hasNexk()){

          String key = keyIt.next();

          if(StringUtils.equalsIgnoreCase(mkName,key)){

            v=map.get(key);

          }

          if(v!=null){

            builder,moveToBookmark(bk.getName());//移动到书签

            bk.setText(v.toString);

          }

        }

        if(v == null){

          bk.setText("");

        }

        //导入图片

        String touxiangurl = (String) map.get("touxiangurl");

        File file = new File(touxiangurl);

        if(file.exists()){

          builder.moveToBookmark("touxiangurl");

          int margin = RelativeHorizontalPosition,MARGIN;

          int square = WrapType.SQUARE;

          builder.insertImage(touxiangurl,margin,1,margin,1,100,150,square);

        }

      }

      for(int i=0;i<bColl.getCount();i++){

        bColl.removeAt(i);//移除书签,如果不移除,导出的字段会有个标签图样;

        i--;

      }

      String docExt = FilenameUtils.getExtension(targetFilePath);

      int saveFormat = StringUtils.equalsIgnoreCase(docExt,"doc")?SaveFormat.DOC:SaveFormat.DOCX;

      doc.save(targetFilePath,saveFormat);

    }chtch(Exception e){

      e.printStackTrace();

    } 

  }

 

posted @ 2020-07-13 16:13  790021521  阅读(536)  评论(0编辑  收藏  举报