Android中使用POI加載與顯示word文檔

最近打算實現一個功能:在Android中加載顯示Word文檔,固然這裏不是使用外部程序打開。查看一些資料後,打算採用poi實現,肯定了如下實現思路:html

  1. 將ftp中的word文檔下載到本地。
  2. 調用poi將word文檔轉成html格式並保存到本地
  3. 使用WebViewer加載顯示本地html

這裏略去下載word文檔到本地不談,僅僅後面兩步,看起來仍是比較簡單的,網上也有相關代碼。不過在使用過程當中遇到了兩個大的問題,着實讓筆者費了一番腦筋。這裏給你們列出來,但願能幫助你們節省些時間。java

 
首先,說一下POI使用方法
  1. 下載poi-bin-3.9-20121203.tar.gz並解壓,提取查看Office文檔所依賴的包。
  2. word相關操做依賴於poi-3.9-20121203.jar和poi-scratchpad-3.9-20121203.jar兩個包,將其加入到Android程序的libs文件夾中。
  3. 將word轉html並保存到本地,而後使用WebViewer加載顯示本地html。整個代碼以下
package com.example.office;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {
    
    private String docPath = "/mnt/sdcard/documents/";
    private String docName = "test.doc";
    private String savePath = "/mnt/sdcard/documents/";    
        
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String name = docName.substring(0, docName.indexOf("."));
        try {
            if(!(new File(savePath+name).exists()))
                new File(savePath+name).mkdirs();
            convert2Html(docPath+docName,savePath+name+".html");
        } catch (Exception e){
            e.printStackTrace();
        }
        //WebView加載顯示本地html文件
        WebView webView = (WebView)this.findViewById(R.id.office);       
        WebSettings webSettings = webView.getSettings();
        webSettings.setLoadWithOverviewMode(true);    
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webView.loadUrl("file:/"+savePath+name+".html");
    }
    
    /**
     * word文檔轉成html格式 
     * */
    public void convert2Html(String fileName, String outPutFile)  
            throws TransformerException, IOException,  
            ParserConfigurationException {  
        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());       
        
        //設置圖片路徑
        wordToHtmlConverter.setPicturesManager(new PicturesManager()  
         {  
             public String savePicture( byte[] content,  
                     PictureType pictureType, String suggestedName,  
                     float widthInches, float heightInches )  
             {  
                 String name = docName.substring(0,docName.indexOf("."));
                 return name+"/"+suggestedName;  
             }  
         } );
    
        //保存圖片
       List<Picture> pics=wordDocument.getPicturesTable().getAllPictures();  
        if(pics!=null){  
            for(int i=0;i<pics.size();i++){  
                Picture pic = (Picture)pics.get(i);  
                System.out.println( pic.suggestFullFileName()); 
                try {  
                    String name = docName.substring(0,docName.indexOf("."));
                    pic.writeImageContent(new FileOutputStream(savePath+ name + "/"
                            + pic.suggestFullFileName()));
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                }    
            }  
        }
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();  
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);
  
        TransformerFactory tf = TransformerFactory.newInstance();  
        Transformer serializer = tf.newTransformer();  
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");  
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");  
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);  
        out.close();  
        //保存html文件
        writeFile(new String(out.toByteArray()), outPutFile); 
    }
    
    /**
     * 將html文件保存到sd卡
     * */
    public void writeFile(String content, String path) {  
        FileOutputStream fos = null;  
        BufferedWriter bw = null;  
        try {  
            File file = new File(path);  
            if(!file.exists()){
                file.createNewFile();
            }                
            fos = new FileOutputStream(file);  
            bw = new BufferedWriter(new OutputStreamWriter(fos,"utf-8"));  
            bw.write(content);  
        } catch (FileNotFoundException fnfe) {  
            fnfe.printStackTrace();  
        } catch (IOException ioe) {  
            ioe.printStackTrace();  
        } finally {  
            try {  
                if (bw != null)  
                    bw.close();  
                if (fos != null)  
                    fos.close();  
            } catch (IOException ie) {  
            }  
        }  
    }
}
activity_main.xml以下
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:id = "@+id/office"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity"/>
</RelativeLayout>

上面代碼中convert2Html用於將word文檔轉換html。下面的代碼則是使用WebViewer加載顯示本地html文件。 android

        WebView webView = (WebView)this.findViewById(R.id.office);       
        WebSettings webSettings = webView.getSettings();
        webSettings.setLoadWithOverviewMode(true);    
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webView.loadUrl("file:/"+savePath+name+".html");

下面來詳細說說存在的兩個問題 web

問題一:使用時有以下報錯:

09-23 17:40:12.350: W/System.err(29954): java.lang.NullPointerException
09-23 17:40:12.350: W/System.err(29954):      at org.apache.poi.hwpf.converter.AbstractWordUtils.compactChildNodesR(AbstractWordUtils.java:146)
apache

 
這個是 POI自身的bug具體緣由在於 AbstractWordUtils.java中 沒有 對child2.getParent是否爲空進行判斷。將以下代碼
child2.getParentNode().removeChild( child2 );
i--;

更改成app

if(child2.getParentNode()!=null){
  child2.getParentNode().removeChild( child2 );
  i--;
}

然而這裏須要從新編譯AbstractWordUtils.java類,將源工程下載後,找到AbstractWordUtils.java後,試驗瞭如下方法。dom

  1. 直接使用javac編譯,會提示不少類庫找不到
  2. 使用反編譯工具,反編譯後更改個文字還能夠,更改代碼就有點勉強了。
  3. 將整個poi導入eclipse後從新編譯,工做量太大,沒有進行嘗試。
最後絞盡腦汁仍是想到了一個至關簡單的方法(高手請飄過~),爲此還得瑟了幾分鐘。具體以下:
  1. 將AbstractWordUtils.java,poi-3.9-20121203.jar,poi-scratchpad-3.9-20121203.jar放到同一目錄下,非必需
  2. 經過引用已有的兩個包進行編譯,編譯命令以下:javac -cp d:\poi-3.9-20121203.jar;d:\poi-scratchpad-3.9-20121203.jar; d:\AbstractWordUtils.java ;編譯後生成AbstractWordUtils.class文件。
  3. 將poi-3.9-20121203.jar的後綴改爲zip,將AbstractWordUtils.class拖到zip中覆蓋掉原有文件,而後將後綴zip改爲jar便可。點擊此處下載更改好的poi-3.9-20121203.jar。
問題二:找不到HWPFDocument錯誤:java.lang.NoClassDefFoundError: org.apache.poi.hwpf.HWPFDocument或者內存不足問題:Unable to execute dex: Java heap space
 
上述問題取決於使用poi-3.9-20121203.jar,poi-scratchpad-3.9-20121203.jar包的不一樣方式。
 
若是將兩個jar包放在libs目錄下,就不會出現類找不到的錯誤;但極可能會出現內存不足的問題。筆者開始經過更改eclipse安裝文件夾下的eclipse.ini文件增大內存到512M,解決了內存不足的問題;後來加入到另一個更大的程序後,又出現內存不足的問題,調整到800M解決。值得注意的是,若是把最大值調整到1024M,eclipse就沒法啓動了(和你的機器相關), 這實在不能算是個好的解決方案。如下爲筆者機器上修改後eclipse.ini文件,注意標紅的部分。
 -startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m --launcher.defaultAction
openFile
-vmargs
-Xms256m
-Xmx800m
 
若是經過使用 Add Library的方法加載jar包,就不會出現內存的問題,可是會出現類找不到的的問題:java.lang.NoClassDefFoundError: org.apache.poi.hwpf.HWPFDocument。雖然 csdn上有人經過將新增的user lib放置到最上面的方法解決了,但我試了下沒有生效,不得已仍是採用了第一種方法。 這裏也但願解決了該問題的人可以留下評論或聯繫方式,方便請教。
 
最後,補充幾點
  1. 目前poi只針對2003的doc格式,不支持2007及其以上的docx格式。
  2. 經測試發現,偶爾會出現的問題,不知如何解決。這裏建議內部程序簡單預覽,外部程序打開word文檔詳細瀏覽的方式。
  3. poi和android API的版本或ADT版本有關;有的在java環境下良好,在android環境下就有問題,還請多多注意。
  4. 整個工程實例代碼請點擊此處
相關文章
相關標籤/搜索