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

來源:互聯網
上載者:User

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);//  } }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.