Android 采用POI读取Office文件

本文介绍如何在Android应用中使用Apache POI库将Office文档(包括Word、Excel和PPT)转换为HTML,并通过WebView展示。文章详细解释了针对03和07版本Office文档的适配过程,以及如何处理文档内的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前段时间项目内用到加载Office文件的功能,还不能直接调用手机本地的APP(WPS)进行加载,在网上找到相关的jar包都是含有水印的,无法再项目内进行使用。

反复查找无果只能自己去实现了,Java上是可以通过POI包进行本地转化office文本为HTML,然后在进行展示HTML来实现加载office的目的。

当然在Android方面也是存在POI的转换jar包的,不过只是Java版本的阉割版,当然对于简单的文档展示还是够用的。

在展示office文档是会出现03和07版本的不同,这里就需要进行两个版本的适配。

(一)新建工程,导入用到的jar包

这些jar包可以在我源码内进行拷贝,也可以自己去Apache POI 去自己下载对应版本的jar包

(二)定义webView用来加载转换后的HTML

                mOfficeWebview = (WebView) findViewById(R.id.webview);
		// 支持JavaScript
		mOfficeWebview.getSettings().setJavaScriptEnabled(true);
		// 设置可以支持缩放(双击以及拖动)
		mOfficeWebview.getSettings().setSupportZoom(true);
		mOfficeWebview.getSettings().setBuiltInZoomControls(true);
		// 不显示WebView缩放按钮(3.0以上版本)
		mOfficeWebview.getSettings().setDisplayZoomControls(false);
		// 扩大比例的缩放
		mOfficeWebview.getSettings().setUseWideViewPort(true);
		// 自适应屏幕
		mOfficeWebview.getSettings().setLayoutAlgorithm(
				LayoutAlgorithm.SINGLE_COLUMN);
		mOfficeWebview.getSettings().setLoadWithOverviewMode(true);

(三)以03版的Word 后缀为.doc为例来进行文档转化加载展示说明

关键类:HWPFDocument

public static 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());

        final String savePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/" + "gdemm";
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {


			@Override
			public String savePicture(byte[] arg0, PictureType arg1,
					String arg2, float arg3, float arg4) {
				// TODO Auto-generated method stub
				return savePath + "/" + arg2;
			}


        });
        wordToHtmlConverter.processDocument(wordDocument);
        // 保存图片
        List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
        if (pics != null) {
            for (int i = 0; i < pics.size(); i++) {
                Picture pic = (Picture) pics.get(i);
                try {
                    pic.writeImageContent(new FileOutputStream(savePath + "/" + pic.suggestFullFileName()));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        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, encoding);
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();
        writeFile(new String(out.toByteArray()), outPutFile);
    }

 

写入类:writeFile

private static void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos, encoding));
            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) {
            }
        }
    }

 

主类内进行数据加载,webView数据展示如下:

                if (filePath.endsWith(".doc")) {
			Toast.makeText(ShowWordActivity.this, "doc", Toast.LENGTH_SHORT)
					.show();
			if (!isExistsDoc(filePath)) {
				try {
					Log.e("文件不存在", "HTML路径 :" + mOfficeHtmlPath + "| "
							+ filePath);
					// String officeName = mOfficeHtmlPath.substring(
					// mOfficeHtmlPath.indexOf("0") + 1,
					// mOfficeHtmlPath.length());
					String[] mStrPath = mOfficeHtmlPath.split("/");
					String officeName = mStrPath[mStrPath.length - 1];
					htmlPath = mSdcardPath + File.separator + "gdemm"
							+ File.separator + officeName;
					WordToHtml.convert2Html(filePath, htmlPath);
				} catch (TransformerException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					e.printStackTrace();
				}
			}
			mOfficeWebview.loadUrl("file://" + htmlPath);
			// FR fr = new FR(filePath);
			// mOfficeWebview.loadUrl(fr.returnPath);
		}

 

其他Excel以及PPT都和加载Word类似,只不过使用的方法以及画的表不同,具体可参见:

 

代码在这

android 使用poi读取高版本excel, 解决以下这两个错误 java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/xml/stream/XMLEventFactory; at org.apache.poi.openxml4j.opc.internal.marshallers.PackagePropertiesMarshaller.(PackagePropertiesMarshaller.java:41) at org.apache.poi.openxml4j.opc.OPCPackage.init(OPCPackage.java:161) at org.apache.poi.openxml4j.opc.OPCPackage.(OPCPackage.java:141) at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:97) at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:324) at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:184) at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:149) javax.xml.stream.FactoryConfigurationError: Provider com.sun.xml.internal.stream.events.XMLEventFactoryImpl not found at javax.xml.stream.FactoryFinder.newInstance(Unknown Source) at javax.xml.stream.FactoryFinder.newInstance(Unknown Source) at javax.xml.stream.FactoryFinder.find(Unknown Source) at javax.xml.stream.FactoryFinder.find(Unknown Source) at javax.xml.stream.XMLEventFactory.newInstance(Unknown Source) at org.apache.poi.openxml4j.opc.internal.marshallers.PackagePropertiesMarshaller.(PackagePropertiesMarshaller.java:41) at org.apache.poi.openxml4j.opc.OPCPackage.init(OPCPackage.java:161) at org.apache.poi.openxml4j.opc.OPCPackage.(OPCPackage.java:141) at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:97) at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:324) at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:184) at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:149)
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值