Java编程琐事8java将html导出到word
Java编程琐事(8)——java将html导出到word
一、第三方
jar
包下载:
在
java
中将
html
文件导出到
word
需要应用到第三方的
jar
包:采用
poi-bin-3.0-FINAL-20070503.zip
。可以到
官方网站下载最新版本。
二、开发思路:
采用
Java IO
将
html
文件读入到一个临时的
String
对象中,然后采用
poi
提供的
API
生成
word
文档。
三、开发源代码:
package com.solid.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
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;
/**
将
html
文档转为
doc
@author soildwang
*/
public class HtmlToDoc {
/**
读取
html
文件到
word
- @param filepath html
文件的路径
@return
@throws Exception
*/
public boolean writeWordFile(String filepath) throws Exception {
boolean flag = false;
ByteArrayInputStream bais = null;
FileOutputStream fos = null;
String path = “C:/”;
//
根据实际情况写路径
try {
if (!"".equals(path)) {
File fileDir = new File(path);
if (fileDir.exists()) {
String content = readFile(filepath);
byte b[] = content.getBytes();
bais = new ByteArrayInputStream(b);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument(“WordDocument”, bais);
fos = new FileOutputStream(path + “temp.doc”);
poifs.writeFilesystem(fos);
bais.close();
fos.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null) fos.close();
if(bais != null) bais.close();
}
return flag;
}
/**
读取
html
文件到字符串
@param filename
@return
@throws Exception
*/
public String readFile(String filename) throws Exception {
StringBuffer buffer = new StringBuffer("");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
buffer = new StringBuffer();
while (br.ready())
buffer.append((char) br.read());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br!=null) br.close();
}
return buffer.toString();
}
public static void main(String[] args) throws Exception {
new HtmlToDoc().writeWordFile(“C:/preview4510.html”);
}
}