Springboot生成word解析HTML标签
最近由于项目问题需要在生成的word中保留html的标签,花了一下午的时间总结出来了两种方法,因为我们使用POI 生成的word 我们控制的实在太少,以至于传进去的html页面他直接就自动识别成了字符串,String,但是在外面写一个html的网页,在外面可以直接改后缀名就可以使html转成word于是我就想到了流的方法,用java 生成一个html文件,然后在去改本地文件的后缀名。以下是代码
@Test
void FileTestDemo(){
String whitName = "test";
File file = new File("D:\\springbootword\\"+whitName+".html");
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write("<p>从之前的一些信息来看,安倍很有可能已经患肠癌。因为之<font face=\"楷体\">前安倍更换了主治医师,新的主治医师以治疗消化道肿瘤著称</font>。安倍<i>之前长期患有肠炎,很有可能恶化成了肠癌。虽然<span style=\"background-color: rgb(194, 79, 74);\">没有明确公布,但</span></i><span style=\"background-color: rgb(194, 79, 74);\">很明显,安倍在至少数</span></p><p style=\"text-align: right;\">年之前就已经确诊了癌症,只是一直没有公布。从一般癌症的进<font size=\"5\" color=\"#f9963b\">展规律来看,安倍现在的情况应该是已经进入了癌症的末期阶段</font>。到了这个阶段,病人的剩余寿命一般在3~6个月。</p>\n".getBytes());
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
然后在处理类的上面我担心会出错所以我使用批量的修改
@Test
void fileName() {
File file=new File("D:\\springbootword\\test\\");
File []fileList=file.listFiles();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].exists()) {
String filename=fileList[i].getName();
String filenamesub=filename.substring(0,filename.lastIndexOf("."));
fileList[i].renameTo(new File("D:/springbootword/test/"+filenamesub + ".docx"));
}
}
}
最后是发现成功了的
最后在使用的时候我发现居然可以简便成最简单的
File file = new File("D:\\springbootword\\" + wordName + ".docx");
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(text.getBytes());
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
可以直接使用 这样可以直接通过生成docx的文件