接上一篇Android POI 生成word文档到本地,显示生成的word到页面,android不能直接显示word,先转成html,再用webview加载.转html需要用到 ‘fr.opensagres.xdocreport:xdocreport’.
1.gradle 依赖POI
dependencies {
...
implementation ('org.apache.poi:poi-ooxml:3.17'){
//poi-ooxml-schemas3.17版本有问题,下面重新依赖.
exclude group:'org.apache.poi',module:'poi-ooxml-schemas'
}
implementation 'org.apache.poi:ooxml-schemas:1.3'
implementation 'org.apache.xmlbeans:xmlbeans:3.1.0'
implementation 'javax.xml.stream:stax-api:1.0'
implementation 'com.fasterxml:aalto-xml:1.2.2'
implementation'org.apache.poi:poi-scratchpad:3.17'
//word ==> html
implementation 'fr.opensagres.xdocreport:xdocreport:2.0.1'
}
...
注意的坑:
1.xdocreport 注意版本号,最开始一直用1.0.6,转换一直报错NoSuchMethodError: No virtual method getPackageRelationship(),后面换成2.0.1版本正常.
2.ooxml-schemas 版本问题,类找不到,查资料poi3.17 ooxml-schemas的版本需要1.3,其他版本可能代码不是很全,但是依赖poi默认依赖了poi-ooxml-schemas3.17,这边只能用exclude :把默认的排除在外.重新依赖ooxml-schemas1.3
2.word转html
转换的html,webview可以正常显示,但是本地使用第三方打开时会访问不了图片,这应该是android App不能访问其他应用私有目录导致的.长远考虑可以继承ImageManager上传服务端,返回远程地址给html.
private void docxToHtml() {
String path = FileUtils.getAppRootPth(this) + File.separator + "word" + File.separator + "测试25.docx";
String img_path = FileUtils.getAppRootPth(this) + File.separator + "word_img"+ File.separator;
String fileOutName = img_path + "测试24.html";
try (FileInputStream fis = new FileInputStream(path)) {
XWPFDocument document = new XWPFDocument(fis);
XHTMLOptions options = XHTMLOptions.create();
//忽略未用到的样式 默认true
options.setIgnoreStylesIfUnused(false);
//将样式都写为内联样式,而不是写到style标签中 默认false
options.setFragment(true);
//设置html 图片储存位置.需要传服务器的,可以继承ImageManager,自己处理逻辑.
options.setImageManager(new ImageManager(new File(img_path),"img"));
File file = new File(fileOutName);
//创建所有的父路径,如果不存在父目录的话
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
XHTMLConverter.getInstance().convert(document, fos, options);
Log.i(TAG, "docxToHtml: 转换结束 - -");
String sd_path = "file://" + fileOutName;
Log.i(TAG, "docxToHtml: sd_path = " + sd_path);
//android 10以上官方默认false
mTestBinding.web.getSettings().setAllowFileAccess(true);
mTestBinding.web.loadUrl(sd_path);
} catch (IOException e) {
throw new RuntimeException(e);
}
}