最近打算实现一个功能:在Android中加载显示Word文档,当然这里不是使用外部程序打开。查看一些资料后,打算采用poi实现,确定了以下实现思路:
这里略去下载word文档到本地不谈,仅仅后面两步,看起来还是比较简单的,网上也有相关代码。不过在使用过程中遇到了两个大的问题,着实让笔者费了一番脑筋。这里给大家列出来,希望能帮助大家节省些时间。
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文件。
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");
下面来详细说说存在的两个问题
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)
child2.getParentNode().removeChild( child2 );
i--;
更改为
if(child2.getParentNode()!=null){ child2.getParentNode().removeChild( child2 ); i--; }
然而这里需要重新编译AbstractWordUtils.java类,将源工程下载后,找到AbstractWordUtils.java后,试验了以下方法。
-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
转载来自:http://www.cnblogs.com/esrichina/p/3347454.html