利用模板导出文件(二)之jacob利用word模板导出word文件(Java2word)

先下载jacob.jar包。解压后将jacob.dll放到windows/system32下面或\jre\bin下面。将jacob.jar加入项目。

这样项目的环境基本上搭建完成,接下来就是书写相关的代码:

 

[java] view plain copy
 
  1. /** 
  2. * 传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。 
  3. * word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾, 
  4. * 如:$code$、$date$……,以免执行错误的替换。 
  5. * 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径 
  6. * (目前只判断文件后缀名为:.bmp、.jpg、.gif)。 
  7. * 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中: 
  8. * R代表从表格的第R行开始替换,N代表word模板中的第N张表格; 
  9. * Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代表一行数据, 
  10. * ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号, 
  11. * 如:要替换第一列、第二列、第三列的数据,则第一条记录为String[3] {"1","2","3"}。 
  12. */  
  13.   
  14. import java.util.ArrayList;  
  15. import java.util.HashMap;  
  16. import java.util.Iterator;  
  17.   
  18. import com.jacob.activeX.ActiveXComponent;  
  19. import com.jacob.com.Dispatch;  
  20. import com.jacob.com.Variant;  
  21.   
  22. /** 
  23.  * 利用word模板生成word文件 
  24.  * @typename:Java2word 
  25.  * @author: FishRoad 
  26.  * @since: 2015年8月24日 下午2:47:41 
  27.  * 
  28.  */  
  29. public class Java2word {  
  30.       
  31.      private boolean saveOnExit;  
  32.      /** 
  33.       * word文档 
  34.       */  
  35.      Dispatch doc = null;  
  36.       
  37.      /** 
  38.       * word运行程序对象s 
  39.       */  
  40.      private   ActiveXComponent word;  
  41.      /** 
  42.       * 所有word文档 
  43.       */  
  44.      private   Dispatch documents;  
  45.       
  46.       
  47.      /** 
  48.       * 构造函数 
  49.       */  
  50.      public Java2word() {  
  51.          if(word==null){  
  52.          word = new ActiveXComponent("Word.Application");  
  53.          word.setProperty("Visible",new Variant(false));  
  54.          }  
  55.          if(documents==null)  
  56.          documents = word.getProperty("Documents").toDispatch();  
  57.          saveOnExit = false;  
  58.      }  
  59.       
  60.      /** 
  61.       * 设置参数:退出时是否保存 
  62.       * @param saveOnExit boolean true-退出时保存文件,false-退出时不保存文件 
  63.       */  
  64.      public void setSaveOnExit(boolean saveOnExit) {  
  65.          this.saveOnExit = saveOnExit;  
  66.      }  
  67.      /** 
  68.       * 得到参数:退出时是否保存 
  69.       * @return boolean true-退出时保存文件,false-退出时不保存文件 
  70.       */  
  71.      public boolean getSaveOnExit() {  
  72.          return saveOnExit;  
  73.      }  
  74.       
  75.      /** 
  76.       * 打开文件 
  77.       * @param inputDoc String 要打开的文件,全路径 
  78.       * @return Dispatch 打开的文件 
  79.       */  
  80.      public Dispatch open(String inputDoc) {  
  81.          return Dispatch.call(documents,"Open",inputDoc).toDispatch();  
  82.      }  
  83.       
  84.      /** 
  85.       * 选定内容 
  86.       * @return Dispatch 选定的范围或插入点 
  87.       */  
  88.      public Dispatch select() {  
  89.          return word.getProperty("Selection").toDispatch();  
  90.      }  
  91.       
  92.      /** 
  93.       * 把选定内容或插入点向上移动 
  94.       * @param selection Dispatch 要移动的内容 
  95.       * @param count int 移动的距离 
  96.       */  
  97.      public void moveUp(Dispatch selection,int count) {  
  98.          for(int i = 0;i < count;i ++)  
  99.              Dispatch.call(selection,"MoveUp");  
  100.      }  
  101.       
  102.      /** 
  103.       * 把选定内容或插入点向下移动 
  104.       * @param selection Dispatch 要移动的内容 
  105.       * @param count int 移动的距离 
  106.       */  
  107.      public void moveDown(Dispatch selection,int count) {  
  108.          for(int i = 0;i < count;i ++)  
  109.              Dispatch.call(selection,"MoveDown");  
  110.      }  
  111.       
  112.      /** 
  113.       * 把选定内容或插入点向左移动 
  114.       * @param selection Dispatch 要移动的内容 
  115.       * @param count int 移动的距离 
  116.       */  
  117.      public void moveLeft(Dispatch selection,int count) {  
  118.          for(int i = 0;i < count;i ++) {  
  119.              Dispatch.call(selection,"MoveLeft");  
  120.          }  
  121.      }  
  122.       
  123.      /** 
  124.       * 把选定内容或插入点向右移动 
  125.       * @param selection Dispatch 要移动的内容 
  126.       * @param count int 移动的距离 
  127.       */  
  128.      public void moveRight(Dispatch selection,int count) {  
  129.          for(int i = 0;i < count;i ++)  
  130.              Dispatch.call(selection,"MoveRight");  
  131.      }  
  132.       
  133.      /** 
  134.       * 把插入点移动到文件首位置 
  135.       * @param selection Dispatch 插入点 
  136.       */  
  137.      public void moveStart(Dispatch selection) {  
  138.          Dispatch.call(selection,"HomeKey",new Variant(6));  
  139.      }  
  140.       
  141.      /** 
  142.       * 从选定内容或插入点开始查找文本 
  143.       * @param selection Dispatch 选定内容 
  144.       * @param toFindText String 要查找的文本 
  145.       * @return boolean true-查找到并选中该文本,false-未查找到文本 
  146.       */  
  147.      public boolean find(Dispatch selection,String toFindText) {  
  148.          //从selection所在位置开始查询  
  149.          Dispatch find = word.call(selection,"Find").toDispatch();  
  150.          //设置要查找的内容  
  151.          Dispatch.put(find,"Text",toFindText);  
  152.          //向前查找  
  153.          Dispatch.put(find,"Forward","True");  
  154.          //设置格式  
  155.          Dispatch.put(find,"Format","True");  
  156.          //大小写匹配  
  157.          Dispatch.put(find,"MatchCase","True");  
  158.          //全字匹配  
  159.          Dispatch.put(find,"MatchWholeWord","True");  
  160.          //查找并选中  
  161.          return Dispatch.call(find,"Execute").getBoolean();  
  162.      }  
  163.       
  164.      /** 
  165.       * 把选定内容替换为设定文本 
  166.       * @param selection Dispatch 选定内容 
  167.       * @param newText String 替换为文本 
  168.       */  
  169.      public void replace(Dispatch selection,String newText) {  
  170.          //设置替换文本  
  171.          Dispatch.put(selection,"Text",newText);  
  172.      }  
  173.       
  174.      /** 
  175.       * 全局替换 
  176.       * @param selection Dispatch 选定内容或起始插入点 
  177.       * @param oldText String 要替换的文本 
  178.       * @param newText String 替换为文本 
  179.       */  
  180.      public void replaceAll(Dispatch selection,String oldText,Object replaceObj) {  
  181.          //移动到文件开头  
  182.          moveStart(selection);  
  183.           
  184.          if(oldText.startsWith("table") || replaceObj instanceof ArrayList)  
  185.              replaceTable(selection,oldText,(ArrayList) replaceObj);  
  186.          else {  
  187.              String newText = (String) replaceObj;  
  188.              if(newText==null)  
  189.                  newText="";  
  190.              if(oldText.indexOf("image") != -1&!newText.trim().equals("") || newText.lastIndexOf(".bmp") != -1 || newText.lastIndexOf(".jpg") != -1 || newText.lastIndexOf(".gif") != -1){  
  191.                  while(find(selection,oldText)) {  
  192.                      replaceImage(selection,newText);  
  193.                      Dispatch.call(selection,"MoveRight");  
  194.                  }  
  195.              }else{  
  196.                  while(find(selection,oldText)) {  
  197.                      replace(selection,newText);  
  198.                      Dispatch.call(selection,"MoveRight");  
  199.                  }  
  200.              }  
  201.          }  
  202.      }  
  203.       
  204.      /** 
  205.       * 替换图片 
  206.       * @param selection Dispatch 图片的插入点 
  207.       * @param imagePath String 图片文件(全路径) 
  208.       */  
  209.      public void replaceImage(Dispatch selection,String imagePath) {  
  210.          Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture",imagePath);  
  211.      }  
  212.       
  213.      /** 
  214.       * 替换表格 
  215.       * @param selection Dispatch 插入点 
  216.       * @param tableName String 表格名称, 
  217.       * 形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,N代表word文件中的第N张表 
  218.       * @param fields HashMap 表格中要替换的字段与数据的对应表 
  219.       */  
  220.      public void replaceTable(Dispatch selection,String tableName,ArrayList dataList) {  
  221.          if(dataList.size() <= 1) {  
  222.              System.out.println("Empty table!");  
  223.              return;  
  224.          }  
  225.           
  226.          //要填充的列  
  227.          String[] cols = (String[]) dataList.get(0);  
  228.           
  229.          //表格序号  
  230.          String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);  
  231.          //从第几行开始填充  
  232.          int fromRow = Integer.parseInt(tableName.substring(tableName.lastIndexOf("$") + 1,tableName.lastIndexOf("@")));  
  233.          //所有表格  
  234.          Dispatch tables = Dispatch.get(doc,"Tables").toDispatch();  
  235.          //要填充的表格  
  236.          Dispatch table = Dispatch.call(tables,"Item",new Variant(tbIndex)).toDispatch();  
  237.          //表格的所有行  
  238.          Dispatch rows = Dispatch.get(table,"Rows").toDispatch();  
  239.          //填充表格  
  240.          for(int i = 1;i < dataList.size();i ++) {  
  241.              //某一行数据  
  242.              String[] datas = (String[]) dataList.get(i);  
  243.               
  244.              //在表格中添加一行  
  245.              if(Dispatch.get(rows,"Count").getInt() < fromRow + i - 1)  
  246.                  Dispatch.call(rows,"Add");  
  247.              //填充该行的相关列  
  248.              for(int j = 0;j < datas.length;j ++) {  
  249.                  //得到单元格  
  250.                  Dispatch cell = Dispatch.call(table,"Cell",Integer.toString(fromRow + i - 1),cols[j]).toDispatch();  
  251.                  //选中单元格  
  252.                  Dispatch.call(cell,"Select");  
  253.                  //设置格式  
  254.                  Dispatch font = Dispatch.get(selection,"Font").toDispatch();  
  255.                  Dispatch.put(font,"Bold","0");  
  256.                  Dispatch.put(font,"Italic","0");  
  257.                  //输入数据  
  258.                  Dispatch.put(selection,"Text",datas[j]);  
  259.              }  
  260.          }  
  261.      }  
  262.       
  263.      /** 
  264.       * 保存文件 
  265.       * @param outputPath String 输出文件(包含路径) 
  266.       */  
  267.      public void save(String outputPath) {  
  268.          Dispatch.call(Dispatch.call(word,"WordBasic").getDispatch(),"FileSaveAs",outputPath);  
  269.      }  
  270.       
  271.      /** 
  272.       * 关闭文件 
  273.       * @param document Dispatch 要关闭的文件 
  274.       */  
  275.      public void close(Dispatch doc) {  
  276.          Dispatch.call(doc,"Close",new Variant(saveOnExit));  
  277.          word.invoke("Quit",new Variant[]{});  
  278.          word = null;  
  279.      }  
  280.       
  281.      /** 
  282.       * 根据模板、数据生成word文件 
  283.       * @param inputPath String 模板文件(包含路径) 
  284.       * @param outPath String 输出文件(包含路径) 
  285.       * @param data HashMap 数据包(包含要填充的字段、对应的数据) 
  286.       */  
  287.      public void toWord(String inputPath,String outPath,HashMap data) {  
  288.          String oldText;  
  289.          Object newValue;  
  290.          try {  
  291.              if(doc==null)  
  292.              doc = open(inputPath);  
  293.               
  294.              Dispatch selection = select();  
  295.               
  296.              Iterator keys = data.keySet().iterator();  
  297.              while(keys.hasNext()) {  
  298.                  oldText = (String) keys.next();  
  299.                  newValue = data.get(oldText);  
  300.                   
  301.                  replaceAll(selection,oldText,newValue);  
  302.              }  
  303.               
  304.              save(outPath);  
  305.          } catch(Exception e) {  
  306.              System.out.println("操作word文件失败!");  
  307.              e.printStackTrace();  
  308.          } finally {  
  309.              if(doc != null)  
  310.                  close(doc);  
  311.          }  
  312.      }  
  313.       
  314.      public synchronized static void word(String inputPath,String outPath,HashMap data){  
  315.          Java2word j2w = new Java2word();  
  316.          j2w.toWord(inputPath,outPath,data);  
  317.      }  
  318.       
  319.      @SuppressWarnings({ "rawtypes", "unchecked" })  
  320.     public static void main(String[] args) {  
  321.          //替换word中相关的字段  
  322.          HashMap data = new HashMap();  
  323.          data.put("$reportDept$","2007-8-1");  
  324.          data.put("$findDate$","2007-8-2");  
  325.          data.put("$finder$","kdl");  
  326.          data.put("$lineName$","5号线");  
  327.          data.put("$voltageRate$","11月13日");  
  328.          data.put("$towerNumberBound$","2004年11月10日");  
  329.          data.put("$image1$","C:\\Users\\Administrator\\Pictures\\1.jpg");  
  330.          data.put("$name$", "FishRoad");  
  331.          data.put("$age$", "24");  
  332.          //替换word中表格的数据  
  333.          /** 
  334.           * 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中: 
  335.           * R代表从表格的第R行开始替换,N代表word模板中的第N张表格; 
  336.           * Value为ArrayList对象,ArrayList中包含的对象统一为String[], 
  337.           * 一条String[]代表一行数据,ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号, 
  338.           * 如:要替换第一列、第二列、第三列的数据,则第一条记录为String[3] {"1","2","3"} 
  339.           */  
  340.          ArrayList table1 = new ArrayList(3);  
  341.          String[] fieldName1 = {"1","2","3"};  
  342.          table1.add(fieldName1);  
  343.          String[] field11 = {"1","751002","华夏证券"};  
  344.          table1.add(field11);  
  345.          String[] field21 = {"2","751004","国泰君安"};  
  346.          table1.add(field21);  
  347.          String[] field31 = {"3","751005","海通证券"};  
  348.          table1.add(field31);  
  349.          data.put("table$2@2",table1);  
  350.            
  351.          Java2word j2w = new Java2word();  
  352.          long time1 = System.currentTimeMillis();  
  353.          j2w.toWord("E:/template.doc","E:/result.doc",data);  
  354.          System.out.println("time cost : " + (System.currentTimeMillis() - time1));  
  355.      }  
  356. }  

以上是相关的代码,接下来就要配置word模板,如下:

 

导出的结果如下图:

posted @ 2016-06-12 16:59  萧痕♂泪  阅读(1023)  评论(0)    收藏  举报