本文实现java将word转为html字符串
没有实现样式图片,只获取文字段落进行一些文字简单展示处理。
一般word文件后缀有doc、docx两种。docx是office word 2007以及以后版本文档的扩展名;doc是office word 2003文档保存的扩展名。对于这两种格式的word转换成html需要使用不同的方法。
不说了,直接看代码
工具类:
package com.ffcs.mss.cpmis.project.pub;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.hwpf.HWPFDocument;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
/**
* word文档转html工具类(未处理样式与图片)
*
*/
public class WordToHtmlUtil {
public static void main(String[] args) throws Exception {
String filePath = "C://Users//wbb//Desktop//测试说明文档.doc";
InputStream is = new FileInputStream(filePath);
String htmlstr=word2003ToHtml(is);
System.out.println(htmlstr);
String filePath2 = "C://Users//wbb//Desktop//测试说明文档.docx"; // Word文档路径
InputStream is2 = new FileInputStream(filePath2);
String htmlstr2=word2007ToHtml(is2);
System.out.println(htmlstr2);
}
public static String word2003ToHtml(InputStream is) throws IOException {
try {
StringBuilder htmlResponse = new StringBuilder();
htmlResponse.append("<html><body style='font-family: Arial;'>");
HWPFDocument doc = new HWPFDocument(is);
Range r = doc.getRange();// 文档范围
for (int i = 0; i < r.numParagraphs(); i++) {
Paragraph para = r.getParagraph(i);
String text = para.text();// 段落文本
htmlResponse.append(text);
}
htmlResponse.append("</body></html>");
is.close();
return htmlResponse.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}finally{
is.close();
}
}
public static String word2007ToHtml(InputStream is) throws IOException {
try {
XWPFDocument document = new XWPFDocument(is);
StringBuilder content = new StringBuilder();
// 读取文档中的段落
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph para : paragraphs) {
content.append(para.getText());
content.append("<br>"); // 添加HTML换行
}
is.close();
StringBuilder htmlResponse = new StringBuilder();
htmlResponse.append("<html><body style='font-family: Arial;'>");
htmlResponse.append(content.toString());
htmlResponse.append("</body></html>");
return htmlResponse.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}finally{
is.close();
}
}
}
效果:
Word文档:
转换后的html展示: