word文档转html格式在线预览,使用了phpoffice,pydocx,java POI各方案,最终用unoconv解决

本文介绍了在PHP项目中实现word和excel文件在线预览的全过程。尝试了phpoffice的phpword、python的pydocx和java的Apache POI,但都存在不足。最终通过unoconv成功处理doc和docx格式,结合libreoffice实现了转换,并解决了样式和内容丢失的问题。
摘要由CSDN通过智能技术生成

最近客户要做一个word,excel 文件在线预览功能,以下是实现此功能的全过程。
由于我们用的是PHP开发项目,最开始想到的是用PHPoffice里的phpword来进行转换,以下是关键代码。

<?php
$phpWord = \PhpOffice\PhpWord\IOFactory::load('test.doc');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
$xmlWriter->save('test.html); 

用这种方法转是可以转,但是转出来的html文件相对原文件,丢失了很多字,如果说样式和原文不一样还可以忍受,但是内容丢失,就不太好了,而且对DOC格式又无法处理,所以这种方法,我最终选择了放弃。
然后,我就想用python来解决这个问题,查到了python有个pydocx库可以处理word文档,于是我就安装了一下。

pip install pydocx

这个库用起来也很简单,主要代码如下:

from pydocx import PyDocX
html = PyDocX.to_html("test2.doc")
f = open("test.html", 'w', encoding="utf-8")
f.write(html)
f.close()

转换效果也还可以,除了表格样式和原文有点不一样以外,内容倒是没丢失,但是有一个问题,这个库是转换docx的,对doc转换不了,我们客户还上传挺多doc格式的文件的,于是我只好另外想办法。
查资料发现java有个poi库可以用来对word文件进行转换, Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。我想试一下,查资料半天,就开始写了,先Maven引入依赖:

    <dependencies>
        <dependency>
                   <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                    <version>4.1.2</version>
                </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- 针对2003版本的库 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.4.3</version></dependency>
    </dependencies>

以下是引用别人的可用代码:

import cn.hutool.core.img.ImgUtil;
import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值