最近項目中遇到一個新需求,需要將Word和Excel文檔解析成為html編碼並在前台顯示,word中包含圖片信息,保留原文檔基礎樣式,博主查找了相關資料后,利用OpenOffice第三方插件,以及自己封裝了一些解析方法,功能已經實現,在此分為上下兩部分做總結以便后期使用,希望可以幫助到大家,如有更好的建議望留言告知。
1.OpenOffice
1.軟件下載
首先,去到官網根據自己的需求下載所需要的版本(我的版本是4.1.4)。
2.軟件安裝
雙擊安裝包 打開運行程序 這里是安裝向導首界面 點擊下一步按鈕
點擊瀏覽按鈕 選擇安裝目錄路徑 如圖所示
會自動檢測系統中的插件 如果需要會自動安裝
輸入使用的用戶 以及選擇用戶權限 點擊下一步按鈕
這里勾選通常安裝 簡單而且點擊下一步
是否在桌面上創建一個快捷方式 建議勾選
這是安裝完成界面 點擊完成關閉安裝向導
PS:安裝度娘上都有,博主幫你們移植過來,按照步驟即可。
3.啟動OpenOffice服務
打開cmd命令窗口,進入OpenOffice安裝目錄下的program目錄,如下圖
因為我的OpenOffice安裝在D盤所以我先進的D盤,至於怎么在cmd里敲命令行我想大家都懂得,在這里我就不獻丑了。
進入program目錄后,繼續執行(按原句執行不要更改)
soffice -headless -accept=”socket,host=127.0.0.1,port=8100;urp;” -nofirststartwizard
如下圖:
執行完成后可打開:任務管理器 進行查看服務是否啟動 如下圖:
記住每次重啟電腦都得重新打開OpenOffice執行上述步驟,如果需要自啟動請自行寫自啟動腳本
4.工具類
OpenOfficeUtils.java
package com.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
/** * 任意文件轉化為html * * @author Mr.F * */
public class OpenOfficeUtils {
// 任意文件轉html
public static void FileToHtml(String sourceFile, String htmlFile) {
File SourceFile = new File(sourceFile);
File HtmlFile = new File(htmlFile);
/* * 轉換成pdf文件 * 項目執行需要啟動OpenOffice服務,在系統命令窗口執行命令。 * cd C:\Program Files (x86)\OpenOffice.org 4\program * soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard */
if(SourceFile.exists()) {
if(!HtmlFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(SourceFile, HtmlFile);
HtmlFile.createNewFile();
connection.disconnect();
System.out.println("第二步:轉換為HTML格式 路徑" + HtmlFile.getPath());
} catch (java.net.ConnectException e) {
//} catch (Exception e) {
e.printStackTrace();
System.out.println("OpenOffice服務未啟動");
try {
throw e;
} catch (ConnectException e1) {
e1.printStackTrace();
}
} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
e.printStackTrace();
System.out.println("讀取文件失敗");
throw e;
} catch (Exception e){
e.printStackTrace();
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("已轉換為HTML,無需再次轉換");
}
} else {
System.out.println("要轉換的文件不存在");
}
}
public static void main(String[] args) {
FileToHtml("F:\\ceshi.xlsx", "F:\\ceshi1.html");
}
}
PS:OpenOffice會自動識別Office版本,比如doc和docx以及xls和xlsx。
先告訴大家工具下載和使用情況,下篇會結合web工程給大家演示完整的功能,如有問題請留言告知,我們不止會New!