轉自:http://blog.csdn.net/chinapi_hzh/article/details/5798689
因為微軟沒有公開word源代碼,是以直接用java流來讀取word的後果是讀出來的全是亂碼。是以必須通過jacob這個中間橋 。當然也可用poi來讀取。
先說用poi讀取的方法吧。用poi讀取的話,先要下載下傳tm-extractors-0.4.jar百度一下可以找到。代碼如下:
1 import java.io.FileInputStream;
2
3 try {
4 FileInputStream fileinputstream = new FileInputStream(filepath);
5 WordExtractor extractor = new WordExtractor();
6 temp = extractor.extractText(fileinputstream);
7 System.out.println(temp + "==temp");
8 fileinputstream.close();
9 } catch (Exception ex) {
10 System.out.println("FileNotFoundException error" + ex.getMessage());
11 }
filepath為word文檔路徑,傳回一個temp字元串。這樣讀出來的不是亂碼了,但是效果并不如意。因為把word格式給丢掉了。
再說用jacob. 先到官方網站上去下載下傳:http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368 jacob.zip. 下載下傳之後解壓,把jacob.jar放到項目/web-inf/lib下面。把jacob .dll放到c:/windos/system32/以及java/jdk*.*/jre/bin下面。這樣就算是配置完成了。說代碼:
1 import com.jacob.activeX.ActiveXComponent;
2 import com.jacob.com.Dispatch;
3 import com.jacob.com.Variant;
4 public boolean ChageFormat (String FolderPath,String FileName){
5 String FileFormat = "";
6 System.out.println(FolderPath);
7 FileFormat = FileName.substring(FileName.length()-4,FileName.length());
8 System.out.println(FileFormat);
9 if(FileFormat.equalsIgnoreCase(".doc"))
10 {
11 String DocFile = FolderPath +"//"+ FileName;
12 System.out.println("word檔案路徑:"+DocFile);
13 //word檔案的完整路徑
14 String HtmlFile = DocFile.substring(0, (DocFile.length() - 4)) + ".htm";
15 System.out.println("htm檔案路徑:"+HtmlFile);
16 //html檔案的完整路徑
17 ActiveXComponent app = new ActiveXComponent("Word.Application");
18 //啟動word
19 try
20 {
21 app.setProperty("Visible", new Variant(false));
22 //設定word程式非可視化運作
23 Dispatch docs = app.getProperty("Documents").toDispatch();
24 Dispatch doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{DocFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch();
25 //打開word檔案
26 Dispatch.invoke(doc,"SaveAs",Dispatch.Method, new Object[]{HtmlFile,new Variant(8)}, new int[1]);
27 //作為htm格式儲存檔案
28 Dispatch.call(doc, "Close",new Variant(false));
29 //關閉檔案
30 }
31 catch (Exception e)
32 {
33 e.printStackTrace();
34 }
35 finally
36 {
37 app.invoke("Quit", new Variant[] {});
38 //退出word程式
39 }
40 //轉化完畢
41 return true;
42 }
43 return false;
44 }
FolderPath為word存放路徑。FileName為word名稱。通過這個方法就把word檔案轉成的htm檔案。這時候就可以用流來讀取htm檔案了,讀出來的既不是亂碼。并且帶有格式。
另外要強調的是jacob這個元件和jdk,以及windows版本都有關系。是以版本一定要比對。否則會報錯。版本的問題就要挨個去試了。沒有捷徑可走。