`

使用Java将HTML转成Word格式文件

    博客分类:
  • J2SE
阅读更多

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

 

public class HtmlToWord {

 public static boolean writeWordFile() {

  boolean w = false;
  String path = "c:/";
  
  try {
   if (!"".equals(path)) {
    
    // 检查目录是否存在
    File fileDir = new File(path);
    if (fileDir.exists()) {
     
     // 生成临时文件名称
     String fileName = "a.doc";
     String content = "<html>" +
           "<head>你好</head>" +
          "<body>" +
            "<table>" +
             "<tr>" +
              "<td>信息1</td>" +              
              "<td>信息2</td>" +              
              "<td>t3</td>" +              
             "<tr>" +
            "</table>" +
            "</body>" +
            "</html>";
     
     byte b[] = content.getBytes();
     ByteArrayInputStream bais = new ByteArrayInputStream(b);
     POIFSFileSystem poifs = new POIFSFileSystem();
     DirectoryEntry directory = poifs.getRoot();
     DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
     FileOutputStream ostream = new FileOutputStream(path+ fileName);
     poifs.writeFilesystem(ostream);
     bais.close();
     ostream.close();
     
    }
   }

  } catch (IOException e) {
   e.printStackTrace();
  }

  return w;
 }
 
 public static void main(String[] args){
  writeWordFile();
 }
 
}

分享到:
评论
3 楼 asd51731 2013-06-01  
谷超 写道
如果html中有图片,如何把图片转换到word中呢?

这个真没实现
2 楼 谷超 2013-05-15  
如果html中有图片,如何把图片转换到word中呢?
1 楼 asd51731 2012-07-06  
请问一下,您生成的word有中文乱码问题吗??

相关推荐

Global site tag (gtag.js) - Google Analytics