Android 采用POI读取Office文件

前段时间项目内用到加载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类似,只不过使用的方法以及画的表不同,具体可参见:

 

代码在这

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
要实现 Android Apache POI 文件浏览功能,可以按照以下步骤进行: 1. 在项目的 build.gradle 文件中添加 Apache POI 的依赖项: ``` implementation 'org.apache.poi:poi:4.1.2' implementation 'org.apache.poi:poi-ooxml:4.1.2' ``` 2. 在布局文件中添加一个用于显示文件内容的 TextView: ``` <TextView android:id="@+id/tv_file_content" android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="16sp" android:padding="16dp" /> ``` 3. 在 Activity 中获取传递过来的文件路径,并使用 Apache POI 读取文件内容: ``` private void readExcelFile(String filePath) { try { InputStream inputStream = new FileInputStream(new File(filePath)); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); XSSFSheet sheet = workbook.getSheetAt(0); StringBuilder sb = new StringBuilder(); for (Row row : sheet) { for (Cell cell : row) { sb.append(cell.toString()).append("\t"); } sb.append("\n"); } tvFileContent.setText(sb.toString()); workbook.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 4. 在 Activity 的 onCreate 方法中获取传递过来的文件路径,并调用 readExcelFile 方法: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file_viewer); tvFileContent = findViewById(R.id.tv_file_content); String filePath = getIntent().getStringExtra("FILE_PATH"); readExcelFile(filePath); } ``` 这样就可以实现 Android Apache POI 文件浏览功能了。当用户点击一个文件时,可以将文件路径传递给该 Activity,然后在该 Activity 中读取文件内容并显示在 TextView 中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值