目录
docx格式文件操作问题
文章所属专区 项目问题解决
1.前言
通过poi包的一些方法操作doc docx的一些问题 这个问题之前有被问过,感觉解释的不是很好,特此说明一下。
2.问题起因
项目中需要预览一些文件中的内容,需要读取文件,转成字节流后转成字符串封装在json里
主要原因:xmlbeans包版本导致
3.解决方法
3.1xmlbeans包版本升级
在一个项目中指定了xmlbeans的版本导致了 XWPFDocument 这个类实例化时加载方法出错
此时需要升级所需的xmlbeans版本
升级xmlbeans版本为5.1.1后 XPDFDOCUMET类里加载的方法不会出错了
注意:poi相关的poi有三个:poi、poi-ooxml、poi-ooxml-schemas 这三个包的版本是有关联的 升级时需要注意其他包的版本
3.2通过其他方法来接收这些文本内容
这边引入iceblue的相关包(百度的操作word excel非常方便 也有免费的版本)
e-iceblue spire.office 5.3.1public static String WordToHtml(File wordFile) {
String content = null;
if (!wordFile.exists()) {
LogUtil.error("文件不存在!", null);
return null;
} else {
String parentPath = wordFile.getParent();
//String wordDir = wordFile.getPath();
String wordName = wordFile.getName();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
//String fileOnlyName = wordName.substring(0, wordName.lastIndexOf("."));
File imageFolderFile = new File(parentPath);
String courseFile = imageFolderFile.getCanonicalPath();
com.spire.doc.Document doc = new com.spire.doc.Document();
doc.loadFromFile(parentPath+File.separator+wordName);
// 设置css样式是否被嵌入
doc.getHtmlExportOptions().setCssStyleSheetType(CssStyleSheetType.Internal);
String fileName = wordName.substring(0,wordName.lastIndexOf("."));
File docToHtml = new File(courseFile+File.separator+fileName+".html");
doc.saveToFile(docToHtml.toString());
doc.dispose();
InputStream input = new FileInputStream(docToHtml);
int ch = -1;
while((ch = input.read()) != -1){
baos.write(ch);
}
content = docxParserHtml(new String(baos.toByteArray(), HttpConstant.REQUEST_ENCODING), courseFile);
input.close();
Path path = Paths.get(courseFile+File.separator+fileName+".html");
Files.delete(path);
// XWPFDocument document = new XWPFDocument(inputStream);
// File imageFolderFile = new File(parentPath);
// String courseFile = imageFolderFile.getCanonicalPath();
// XHTMLOptions options = XHTMLOptions.create().URIResolver(new BasicURIResolver(parentPath));
// options.setExtractor(new FileImageExtractor(imageFolderFile));
// options.setIgnoreStylesIfUnused(false);
// options.setFragment(true);
// XHTMLConverter.getInstance().convert(document, baos, options);
// content = parserHtml(new String(baos.toByteArray(), HttpConstant.REQUEST_ENCODING), courseFile);
} catch (Exception var29) {
LogUtil.error("Word转换为Html出错", var29);
}
return content;
}
}
总结
参考
Could not initialize class org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument
poi从3.6 升级为新版本5.2.2,导致 原先的代码 报错,替换方案
poi说明书
给个三连吧 谢谢谢谢谢谢了