package com.solid.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
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 (ists()) {
String content = readFile(filepath);
byte b[] = Bytes();
bais = new ByteArrayInputStream(b);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = Root();
DocumentEntry documentEntry = ateDocument("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 InputStreamReader(new FileInputStream(new File(filename)),Charset.forName("UTF8")));
buffer = new StringBuffer();
while (br.ready())
buffer.append((char) br.read());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br!=null) br.close();
}
String();
}
public static void main(String[] args) throws Exception {
java修改html文件 new HtmlToDoc().writeWordFile("C:/single.html");//根据实际情况写文件路径
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论