大家好,又见面了,我是你们的朋友全栈君。
最近写一个系统,需要把复文本的数据生成一个word文档,网上查了一些资料都觉的有点老了,就自己想了一个(暂时可以使用纯文本和表格),借助office本身可以存html的机制!还借助jsoup!直接上代码!
引入包的:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.3</version>
</dependency>
代码:
/**
*
* @param content html body里面需要填充的内容
* @param fileName 文件名
* @param path 路径
* @return
*/
public static boolean htmlToWord(String content,String fileName,String path){
try {
//模板
InputStream html=new FileInputStream("E:\\HtmlToWord\\Mod.html");
String conte=getContent(html);
Document document=Jsoup.parse(conte);
Element body=document.body();
body.html(content);
File file=new File(path+fileName+".html");
FileWriter fileWriter=new FileWriter(file);
fileWriter.write(document.html());
fileWriter.close();
html.close();
File file1=new File(path+fileName+".doc");
if(file.renameTo(file1)){
return true;
}else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 把输入流里面的内容以UTF-8编码当文本取出。
* 不考虑异常,直接抛出
* @param ises
* @return
* @throws IOException
*/
private static 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;
}
思路就是先存成html,再改名为word文档! 写的简单哈!有不足之处还望指点!!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/182911.html原文链接:https://javaforall.cn