您的位置:首页 > 其它

POI创建生成Word文件

2014-11-12 09:47 113 查看
直接把Html文本写入到Word文件

获取查看页面的body内容和引用的css文件路径传入到后台。
把对应css文件的内容读取出来。
利用body内容和css文件的内容组成一个标准格式的Html文本。
根据组合后的Html文本生成对应的ByteArrayInputStream。
构建一个默认的POIFSFileSystem,并利用它和生成的ByteArrayInputStream创建一个WordDocument。
把构建的POIFSFileSystem写入到对应的输出流。

经过上面这几步之后我们就可以把Html格式的文本写入到Word文件中,同时使生成的Word文件呈现出对应的Web样式。需要注意的是原本Html文件中引用到的css文件的内容需要放到生成的Word文件中,生成后的Word文件才会呈现出对应的Web样式。下面是一个针对于该方式的一个简单例子:

public void htmlToWord2() throws Exception {          InputStream bodyIs = new FileInputStream("f:\\1.html");          InputStream cssIs = new FileInputStream("f:\\1.css");          String body = this.getContent(bodyIs);          String css = this.getContent(cssIs);          //拼一个标准的HTML格式文档          String content = "<html><head><style>" + css + "</style></head><body>" + body + "</body></html>";          InputStream is = new ByteArrayInputStream(content.getBytes("GBK"));          OutputStream os = new FileOutputStream("f:\\1.doc");          this.inputStreamToWord(is, os);       }             /**        * 把is写入到对应的word输出流os中        * 不考虑异常的捕获,直接抛出        * @param is        * @param os        * @throws IOException        */       private void inputStreamToWord(InputStream is, OutputStream os) throws IOException {          POIFSFileSystem fs = new POIFSFileSystem();          //对应于org.apache.poi.hdf.extractor.WordDocument          fs.createDocument(is, "WordDocument");          fs.writeFilesystem(os);          os.close();          is.close();       }             /**        * 把输入流里面的内容以UTF-8编码当文本取出。        * 不考虑异常,直接抛出        * @param ises        * @return        * @throws IOException        */       private String getContent(InputStream... ises) throws IOException {          if (ises != null) {             StringBuilder result = new StringBuilder();             BufferedReader br;             String line;             for (InputStream is : ises) {                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));                while ((line=br.readLine()) != null) {                    result.append(line);                }             }             return result.toString();          }          return null;       }


1.css代码如下

table {       border: 1px solid blue;       width: 800px;       height: 500px;       text-align: center;}td {       width: 200px;       border: 1px solid blue;}


1.html对应的内容如下:

<table cellpadding="5" style="border-collapse: collapse;">       <tr>              <td>中文</td>              <td>中文</td>              <td>中文</td>              <td>中文</td>       </tr>       <tr>              <td>中文</td>              <td>中文</td>              <td>中文</td>              <td>中文</td>       </tr></table>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: