JAVA使用POI将word(2007)转换成HTML

xu.wang

发布于 2020.01.10 23:32 阅读 2847 评论 0

 

在前面的文章中,记录了如何使用poi根据模板生成word文档,但是在生成word之后还不能在页面上进行预览,这个问题怎么解决呢?

目前搜索到三个方案:

方案一: 使用微软的在线文档预览功能,比较简单但是有限制

使用方法是在链接上直接拼接可外网访问的文档地址即可:http://view.officeapps.live.com/op/view.aspx?src="文档地址"

文档访问地址不能直接使用 ip,需要通过域名访问,并且端口必须是 80 端口
文档的格式(必须为以下格式之一): 
Word:docx、docm、dotm、dotx 
Excel:xlsx、xlsb、xls、xlsm 
PowerPoint:pptx、ppsx、ppt、pps、pptm、potm、ppam、potx、ppsm
文档的大小:Word 和 PowerPoint 文档必须小于 10 兆字节;Excel 必须小于五兆字节(通过office web app 部署的本地服务器可以设置文档大小)

方案二:使用Apache 的 openOffice

http://www.openoffice.org/download/index.html

使用方法如下:

首先需要先下载openoffice,并安装、启动。

启动openoffice方法如下:

windows:

cd C:\Program Files\OpenOffice.org 3\program 
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

mac:

#进入安装目录
cd /Applications/OpenOffice.app/Contents/program
#运行
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

 然后调用方法即可:

/**
     * 转换office文件为HTML
     * @param source
     * @param html
     * @throws IOException
     */
    public static void converter(File source, File html) throws IOException {
        OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
        try {
            con.connect();
        } catch (ConnectException e) {
            System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");
            e.printStackTrace();
        }
        DocumentConverter converter = new OpenOfficeDocumentConverter(con);
        converter.convert(source, html);
        con.disconnect();

        formatStyle(html);
    }
/**
     * 格式化HTML
     * @param html
     */
    public static void formatStyle(File html) {
        String file_path = null;
        StringBuffer s_html = new StringBuffer();

        try {
            //读取文件路径
            file_path = html.getPath();

            //读取文件
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(html), "GBK"));
            while (br.ready()) {
                s_html.append(br.readLine());
            }
            br.close();
            // 删除临时文件
            html.delete();

            //写文件
            BufferedWriter writer = null;
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(file_path)),"GBK"));
            writer.write(formatStyleUtils(s_html.toString()));
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    public static String formatStyleUtils(String html) {

        //去除左对齐样式
        //P { margin-bottom: 0.21cm; direction: ltr; color: #000000; /**text-align: justify;**/ widows: 0; orphans: 0 }
        html = html.replaceFirst("text-align: justify;", "");

        //图片居中样式
        html = html.replaceAll("<IMG", "<CENTER><IMG");

        return html;
    }

方案三:使用POI将word成HTML

首先引用jar

<!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/fr.opensagres.xdocreport.document -->
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>fr.opensagres.xdocreport.document</artifactId>
    <version>2.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.1</version>
</dependency>

然后调用方法即可:

/**
     * 将word(2007以上 xlxs)转换成HTML文件
     * @param dir 服务器项目目录
     * @param sourceFileName word地址
     * @param targetFileName  HTML路径
     * @throws Exception
     */
public void word2007ToHtml(String dir,String sourceFileName,String targetFileName) throws Exception {

        String imagePathStr = dir+"/upload/image/";
        OutputStreamWriter outputStreamWriter = null;
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(sourceFileName));
            XHTMLOptions options = XHTMLOptions.create();
            // 存放图片的文件夹
            options.setExtractor(new FileImageExtractor(new File(imagePathStr)));
            // html中图片的路径
            options.URIResolver(new BasicURIResolver("image"));
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFileName), "utf-8");
            XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
            xhtmlConverter.convert(document, outputStreamWriter, options);
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
        }finally {
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
        }
    }