有个需求,需要从数据库提取某个字段(html富文本),要导出word模板然后上传到百度文库
由于百度文库的因素, 文库审核必须是word模板格式的,所以只能用poi或者第三包来处理,我们之前做过一次,用的spire.doc转的word,但是富文本不能直接转word,转到word里是直接带标签的
比如
所以我这里准备使用html转word,因为富文本的字符串写入html是有样式的,但是转换后又出现个问题,html首行有缩进的,用spire.doc转却没了缩进
比如这种,前面变成没有缩进齐刷刷的了,我找了一堆解决方案,有一个确实可行
https://blog.csdn.net/m0_46649280/article/details/111045442
但是他这个解决有问题,百度文库审核不会识别这种 ,果断只能放弃
最后找了半天,换了个包和写法就解决了
aspose-words
/*
* aspose-words工具将html转word
*/
public static void htmlToWord1(String content, String title) {
try {
// Load the HTML file
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// 插入富文本
builder.insertHtml(content);
// 存储文档
doc.save("D:\\JudriskWord\\" + title + ".docx", SaveFormat.DOCX);
// 删除水印
InputStream is = new FileInputStream("D:\\JudriskWord\\" + title + ".docx");
XWPFDocument document = new XWPFDocument(is);
//以上生成的文件会自带警告信息,这里来删除警告
document.removeBodyElement(0);
//输出word内容文件流,新输出路径位置
OutputStream os = new FileOutputStream("D:\\JudriskWord\\" + title + ".docx");
try {
document.write(os);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
content是我传过来的 富文本String, title是富文本文件的标题
效果
前面的段落也有了
至于那个第三方包怎么安,百度搜下maven安装就可以了,因为我是引的不是maven安的,这个包可以用maven去管理