java POI HTML转Word

1、引用的jar包

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.0</version>
</dependency>

2、核心代码

String html = "<div>测试内容</div";

POIFSFileSystem poifs = null;
FileOutputStream ostream = null;
ByteArrayInputStream bais = null;
String uuid = "测试.doc";
File file = null;

try {
  //HTML内容必须被<html><body></body></html>包装
  fileParam.setcContent("<html><body>" + html + "</body></html>");
  byte[] b = fileParam.getcContent().getBytes();
  bais = new ByteArrayInputStream(b);
  poifs = new POIFSFileSystem();
  DirectoryEntry directory = poifs.getRoot();
  //WordDocument名称不允许修改
  directory.createDocument("WordDocument", bais);
  ostream = new FileOutputStream(uuid);
  poifs.writeFilesystem(ostream);//当前目录下就生成了一个测试.doc的文档
} catch (Exception e) {
  logger.error("exception is {}", e);
} finally {
  IOUtils.closeQuietly(poifs);
  IOUtils.closeQuietly(ostream);
  IOUtils.closeQuietly(bais);
  try {
    FileUtils.forceDelete(file);
  } catch (Exception e2) {
  }
}

猜你喜欢

转载自www.cnblogs.com/jiehanshi/p/11121782.html