java POI HTML轉Word 兩種方式


說明,不論使用哪種方式,都不能引用CSS來渲染樣式,而是使用style,或者將樣式放在當前頁面的<style></style>中

方法一、

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) {
  }
}

 

方法二

 /**
     * word格式html的標簽頭
     */
    public static final String HTML_TAG_BGN = "<html xmlns=\"http://www.w3.org/TR/REC-html40\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"><head><meta name=\"ProgId\" content=\"Word.Document\" /><meta name=\"Generator\" content=\"Microsoft Word 12\" /><meta name=\"Originator\" content=\"Microsoft Word 12\" /> <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View></w:WordDocument></xml><[endif]-->";
    

public filePath downloadWordReport(String htmlForPrint) {
        try {
            String wordString = htmlForPrint.replaceAll("<head>", "").replaceAll("<html>", HTML_TAG_BGN );
            String fileName = new String("測試文件.doc".getBytes(), "UTF-8");
            //上傳文件方法
            return this.upload(new ByteArrayInputStream(wordString.getBytes()), fileName);

        } catch (Exception e) {
            return null;
        }
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM