1. 程式人生 > >使用Jacob批量轉換word為txt、pdf、xps、html、xml等文件

使用Jacob批量轉換word為txt、pdf、xps、html、xml等文件

Jacob全稱位java com bridge,通過該外掛,可以使用Java語言編寫程式,呼叫COM、ActiveX元件來操作Windows本地程式。

參考一位網友的例子,我寫了一個程式,用來將word批量轉換為txt等格式的文件。

該程式核心部分,僅僅是呼叫了Jacob的幾個類,實現了呼叫Word開啟指定的word文件,並在指定的目的路徑中將其另存為指定的文件格式,簡而言之,就是“Open”,“save As”。

Jacob能夠實現的遠不止這點,操作word的Java外掛有不少,功能強大的Jacob可以為首。

因為程式是呼叫本地Office進行的開啟、另存為操作,所以需要本地安裝有word,並且,不同的office版本操作的結果自然是不同的。

我使用的是word2010,在word2010下可以開啟97-2003doc文件和2007-2010docx文件,儲存的格式也有docx、pdf,而在word2003版本下,該功能實習不了。如果有興趣測試的話,在word2003的環境下,可以把相關的程式碼註釋掉。

下邊附上原始碼:

    /** 
     *@author eyuan 
     */  
    package per.eyuan.word2txt.core;  
      
    import com.jacob.*;  
    import com.jacob.com.*;  
    import com.jacob.activeX.*;  
    import java.io.*;  
    import java.util.Scanner;  
      
    public class Core {  
     /** 
      * 實現轉換的函式 
      * @param sourceFilesPath 
      * @param destinationFilesPath 
      * @param destinationFilesType 
      * @return void 
      * @see import com.jacob.activeX.*; 
      */  
     public boolean change(String sourceFilesPath,String destinationFilesPath,int destinationFilesType){  
      //使用word檔案所在的目錄(源路徑)建立目錄檔案  
      File sourcePathFile=new File(sourceFilesPath);  
      //取得word檔案(原始檔列表)  
      File sourceFilesList[]=sourcePathFile.listFiles();  
      System.out.println("共有"+sourceFilesList.length+"個檔案(資料夾)");  
      //指定要轉換的檔案所在的目錄下,如果有子目錄,  
      //則進入子目錄,繼續查詢word文件並將其轉換,  
      //直到將指定目錄下的所有word文件轉換完。  
      //子目錄名  
      String sourceChildPath=new String("");  
      //保持原來的層次關係,將子目錄下的檔案存放在新建的子目錄中  
      String destiNationChildPath=new String("");  
      //檢索檔案,過濾掉非word檔案,通過副檔名過濾  
      for(int i=0;i<sourceFilesList.length;i++){  
       //排除掉子資料夾  
       if(sourceFilesList[i].isFile()){  
        System.out.println("第"+(i+1)+"個檔案:");  
        //取得檔案全名(包含副檔名)  
        String fileName=sourceFilesList[i].getName();  
        String fileType=new String("");      
        //取得副檔名  
        fileType=fileName.substring((fileName.length()-4), fileName.length());  
        //word2007-2010副檔名為docx  
        //判斷是否為word2007-2010文件,及是否以docx為字尾名  
        if(fileType.equals("docx")){  
         System.out.println("正在轉換。。。");  
         //輸出word文件所在路勁  
         System.out.println("目錄:"+sourceFilesPath);  
         //輸出word文件名  
         System.out.println("檔名:"+fileName);  
         //System.out.println(fileName.substring(0, (fileName.length()-5)));  
         //核心函式  
         //啟動word  
         ActiveXComponent app=new ActiveXComponent("Word.Application");  
         //要轉換的文件的全路徑(所在資料夾+檔案全名)  
         String docPath=sourceFilesPath+"\\"+fileName;  
         //轉換後的文件的全路徑(所在資料夾+檔名)  
         String othersPath=destinationFilesPath+"\\"+fileName.substring(0,(fileName.length()-5));  
         //  
         String inFile=docPath;  
         String outFile=othersPath;  
         //  
         boolean flag=false;  
         //核心程式碼  
         try{  
          //設定word可見性  
          app.setProperty("Visible", new Variant(false));  
          //  
          Dispatch docs=app.getProperty("Documents").toDispatch();  
          //開啟word文件     
          Dispatch doc=Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[]{inFile,new Variant(false),new Variant(true)}, new int[1]).toDispatch();  
          //0:Microsoft Word 97 - 2003 文件 (.doc)  
          //1:Microsoft Word 97 - 2003 模板 (.dot)  
          //2:文字文件 (.txt)  
          //3:文字文件 (.txt)  
          //4:文字文件 (.txt)  
          //5:文字文件 (.txt)  
          //6:RTF 格式 (.rtf)  
          //7:文字文件 (.txt)  
          //8:HTML 文件 (.htm)(帶資料夾)  
          //9:MHTML 文件 (.mht)(單檔案)  
          //10:MHTML 文件 (.mht)(單檔案)  
          //11:XML 文件 (.xml)  
          //12:Microsoft Word 文件 (.docx)  
          //13:Microsoft Word 啟用巨集的文件 (.docm)  
          //14:Microsoft Word 模板 (.dotx)  
          //15:Microsoft Word 啟用巨集的模板 (.dotm)  
          //16:Microsoft Word 文件 (.docx)  
          //17:PDF 檔案 (.pdf)  
          //18:XPS 文件 (.xps)  
          //19:XML 文件 (.xml)  
          //20:XML 文件 (.xml)  
          //21:XML 文件 (.xml)  
          //22:XML 文件 (.xml)  
          //23:OpenDocument 文字 (.odt)  
          //24:WTF 檔案 (.wtf)  
          //另存為指定格式的文件  
          Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{outFile,new Variant(destinationFilesType)}, new int[1]);  
          //  
          Variant file=new Variant(false);  
          //關閉文件  
          Dispatch.call(doc, "Close",file);  
          //  
          flag=true;  
         }catch(Exception e){  
          e.printStackTrace();  
          System.out.println("文件轉換失敗");  
         }finally{  
          app.invoke("Quit",new Variant[]{});  
         }  
         System.out.println("轉換完畢");         
        }  
        //word97-2003副檔名為doc  
        //判斷是否為word2003-2007文件,及是否以doc為字尾名  
        else if(fileType.equals(".doc")){  
         System.out.println("正在轉換。。。");  
         //輸出word文件所在路勁  
         System.out.println("目錄:"+sourceFilesPath);  
         //輸出word文件名  
         System.out.println("檔名:"+fileName);  
         //System.out.println(fileName.substring(0, (fileName.length()-4)));  
         //核心函式  
         //啟動word  
         ActiveXComponent app=new ActiveXComponent("Word.Application");  
         //要轉換的文件的全路徑(所在資料夾+檔案全名)  
         String docPath=sourceFilesPath+"\\"+fileName;  
         //轉換後的文件的全路徑(所在資料夾+檔名)  
         String othersPath=destinationFilesPath+"\\"+fileName.substring(0,(fileName.length()-4));  
         //  
         String inFile=docPath;  
         String outFile=othersPath;  
         //  
         boolean flag=false;  
         //核心程式碼  
         try{  
          //設定word可見性  
          app.setProperty("Visible", new Variant(false));  
          //  
          Dispatch docs=app.getProperty("Documents").toDispatch();  
          //開啟word文件     
          Dispatch doc=Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[]{inFile,new Variant(false),new Variant(true)}, new int[1]).toDispatch();  
          //另存為指定格式的文件  
          Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{outFile,new Variant(destinationFilesType)}, new int[1]);  
          //  
          Variant file=new Variant(false);  
          //關閉文件  
          Dispatch.call(doc, "Close",file);  
          //  
          flag=true;  
         }catch(Exception e){  
          e.printStackTrace();  
          System.out.println("文件轉換失敗");  
         }finally{  
          app.invoke("Quit",new Variant[]{});  
         }  
         System.out.println("轉換完畢");         
        }  
        //文件的副檔名不是doc或docx  
        else{  
         System.out.println("非word文件");  
        }  
       }  
       //如果是子資料夾,則遞迴遍歷,將所有的word文件轉換  
       else{  
        //  
        sourceChildPath=sourceFilesPath;  
        //該檔案是目錄  
        sourceChildPath=sourceChildPath+"\\"+sourceFilesList[i].getName()+"\\";  
        System.out.println("原始檔所在路徑:"+sourceChildPath);  
        //修改目標資料夾,保持原來的層級關係  
        destiNationChildPath=destinationFilesPath;  
        destiNationChildPath=destinationFilesPath+"\\"+sourceFilesList[i].getName()+"\\";  
        System.out.println("轉換後文件所在路徑"+destiNationChildPath);  
        //  
        mkdir(destiNationChildPath);  
        //遞迴遍歷所有目錄,查詢word文件,並將其轉換  
        change(sourceChildPath, destiNationChildPath,destinationFilesType);  
       }  
      }  
      System.out.println("所有文件轉換完畢");  
      return true;  
     }  
     /**  
      * 用於建立資料夾的方法  
      * @param mkdirName  
      */  
     public void mkdir(String mkdirName){  
      try{  
       //使用指定的路徑建立檔案物件  
       File dirFile = new File(mkdirName);   
       //  
       boolean bFile = dirFile.exists();  
       //已經存在資料夾,操作???提醒是否要替換  
       if( bFile == true ) {   
        System.out.println("已經存在資料夾"+mkdirName);   
       }  
       //不存在該資料夾,則新建該目錄  
       else{  
        System.out.println("新建資料夾"+mkdirName);   
        bFile = dirFile.mkdir();   
        if( bFile == true ){  
         System.out.println("資料夾建立成功");   
        }else{  
         System.out.println(" 資料夾建立失敗,清確認磁碟沒有防寫並且空件足夠");   
         System.exit(1);   
        }  
       }  
      }catch(Exception err){  
       System.err.println("ELS - Chart : 資料夾建立發生異常");   
       err.printStackTrace();   
      }finally{  
         
      }  
     }  
     /** 
      * 判斷某個資料夾是否存在 
      * @param path 
      */  
     /** 
      * 將形如D:\word的路徑轉換為D:\\word 
      */  
     public String changePath(String path){  
      String newPath="";  
      StringBuffer sb=new StringBuffer();  
      for(int i=0;i<path.length();i++){  
       sb.append(path.charAt(i));  
       if(path.charAt(i)=='\\')  
        sb.append('\\');  
      }  
      newPath=sb.toString();  
      System.out.println(newPath);  
      return newPath;  
     }  
     public boolean isPathExist(String path){  
      boolean isPathExist=false;  
      try{  
       File pathFile = new File(path);  
       if(pathFile.exists())  
        isPathExist= true;  
       else  
        isPathExist= false;  
      }catch(Exception err){  
       err.printStackTrace();   
      }  
      return isPathExist;  
     }  
     /** 
      * 主函式 
      */  
     public static void main(String[] args){  
      Core c=new Core();  
    //  c.changePath("D:\\word");  
      Scanner sc=new Scanner(System.in);  
      //源文件所在路徑  
      String sourceFilesPath="";   
    //  String inputSourcePath="";  
    //  boolean sourcePathFlag=true;  
    //  System.out.println("請輸入要轉換文件所在的資料夾");  
    //  while(sourcePathFlag){  
    //   inputSourcePath=sc.next();  
    //   if(!isPathExist(inputSourcePath))  
    //    System.out.println("源路徑不存在,請輸入正確的路徑");  
    //   else  
    //    sourcePathFlag=false;  
    //  }  
    //  sourceFilesPath=inputSourcePath;  
      sourceFilesPath="D:\\word";  
      //目標文件要存放的目錄  
      String destinationFilesPath="";  
    //  String inputdestinationPath="";  
    //  boolean destinationPathFlag=true;  
    //  System.out.println("請輸入轉換後文檔要存放的資料夾");  
    //  while(destinationPathFlag){  
    //   inputdestinationPath=sc.next();  
    //   //目標檔案不存在時,是否要提示使用者建立檔案  
    //   if(!isPathExist(inputdestinationPath))  
    //    System.out.println("目標路徑不存在,請輸入正確的路徑");  
    //   else  
    //    destinationPathFlag=false;  
    //  }  
    //  destinationFilesPath=inputdestinationPath;    
      destinationFilesPath="D:\\txt";  
      //選擇要轉換的型別  
      int destinationFilesType=0;  
      int inputNumber=0;  
      boolean numFlag=true;  
      System.out.println("您要將word文件轉換為哪種文件格式?");  
      System.out.println("0:doc \t 2:txt \t 6:rtf \t 8:html \t 9:mht \t 11:xml \t 12:docx \t 17:pdf \t 18:xps");  
      while(numFlag){  
       inputNumber=sc.nextInt();  
       if(inputNumber!=2&&inputNumber!=6&&inputNumber!=8&&inputNumber!=9&&inputNumber!=11&&inputNumber!=12&&inputNumber!=17){  
        System.out.println("您的輸入有誤,請輸入要轉換的文件型別前的數字");  
       }else  
        numFlag=false;  
      }    
      destinationFilesType=inputNumber;  
      //實行轉換  
      c.change(sourceFilesPath, destinationFilesPath,destinationFilesType);  
      //測試各種型別轉換  
    //  for(int i=0;i<25;i++){  
    //   destinationFilesType=i;  
    //   System.out.println("檔案型別"+destinationFilesType);    
    //   System.out.println("存放目錄:"+destinationFilesPath+"\\"+i);  
    //   mkdir(destinationFilesPath+"\\"+i);  
    //   change(sourceFilesPath, destinationFilesPath+"\\"+i,destinationFilesType);  
    //  }  
     }  
    }