package format.conversion;
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 javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class HtmlToDoc {
public static void main(String[] args) throws Exception {
HtmlToDoc test=new HtmlToDoc();
test.go();
}
public void go(){
try{
String FilePath="C:/Tomcat/apache-tomcat-7.0.42/webapps/Export-Report/Report.html";
String url = new File(FilePath).toURI().toURL().toString();
System.out.println(url);
JFileChooser fileSave=new JFileChooser(".");
FileNameExtensionFilter extension=new FileNameExtensionFilter("doc files(.doc)","doc");
fileSave.setFileFilter(extension);
fileSave.showSaveDialog(null);
File file=fileSave.getSelectedFile();
if(!file.getPath().endsWith(".doc")){
file=new File(file.getPath()+".doc");
}
String outputFile =file.toString();
writeWordFile(FilePath,outputFile);
System.out.println("word文件保存成功!");
System.out.println("文件保存路径为:"+new File(outputFile).toURI().toURL());
}catch(Exception ex){
System.out.println("word文件保存失败!");
}
}
public boolean writeWordFile(String filepath,String outputFile) throws Exception {
boolean flag = false;
ByteArrayInputStream bais = null;
FileOutputStream fos = null;
try {
if (!"".equals(outputFile)) {
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(outputFile);
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;
}
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();
}
}
1 个解决方案
#1
自己顶一下。。。。
#1
自己顶一下。。。。