话不多说,直接上代码
依赖如下:
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.12</version>
</dependency>
我是转成html格式后,直接获取字符串发送到前端,也可以直接将html文件直接保存到项目中
@RequestMapping("previewFile")
public void previewFile(Model model,String names)throws Exception
{
final String imagepath = ResourceUtils.getURL("classpath:").getPath()+"static/image/";//解析时候如果doc文件中有图片 图片会保存在此路径
String filepath = ResourceUtils.getURL("classpath:").getPath()+"static/sumary/";
String fileName = names;
String htmlName = "456.html";
final String file = filepath + fileName;
InputStream input = new FileInputStream(new File(file));
HWPFDocument wordDocument = new HWPFDocument(input);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//设置图片存放的位置
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
File file = new File(imagepath + suggestedName);
try {
OutputStream os = new FileOutputStream(file);
os.write(content);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return "/image/" + suggestedName;
}
});
//解析word文档
wordToHtmlConverter.processDocument(wordDocument);
Document htmlDocument = wordToHtmlConverter.getDocument();
// File htmlFile = new File(filepath + htmlName);
// OutputStream outStream = new FileOutputStream(htmlFile);
//也可以使用字符数组流获取解析的内容
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream outStream = new BufferedOutputStream(baos);
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer serializer = factory.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
//也可以使用字符数组流获取解析的内容
String content = baos.toString();
baos.close();
outStream.close();
model.addAttribute("word", content);
}
这个地方一定要注意,返回图片路径的时候,一定是项目图片的路径,不然显示的时候会找不到图片。
下面是前端的代码,直接显示就可以了
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.w3.org/1999/xhtml">
<script th:inline="javascript">
</script>
<div th:utext="${word}"></div>
</html>