前段时间领导交代了一个需求:客户需要一个能够web在线编辑文字,如同编辑word文档一样,同时能够将编辑完成的内容导出为word文档并下载到本地。
实例化编辑器,并将后台传递的word内容数据(html形式)展现在编辑区域内。
var ue = UE.getEditor('editor',{
toolbars: [
['undo', 'redo', 'bold','italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|','rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'directionalityltr', 'directionalityrtl', 'indent', '|','justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|','simpleupload', 'insertimage','link', 'unlink', '|', 'customstyle', 'paragraph', 'fontfamily', 'fontsize','|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
,'horizontal', 'date', 'time', 'spechars', '|', 'preview', 'searchreplace','print']
],
});
ue.ready(function() {//content是html标签的内容,附带有css样式
ue.setContent(content,true)
});
以上是前台的简单实现,这个插件甚至能够直接粘贴图片!
后台的实现思路是:由于前台允许在线编辑,所有不能直接在后台生成一个报告文档,需要将前台显示的内容完全传至后台,有后台代码将前台的html界面转换成word文档。
我在项目中有两种后台实现方式,本篇先介绍前一种实现方式,另一种方式将于下一篇介绍。
这种方式生成的是doc后缀的文档,是Word以前规范的word文档。
@RequestMapping("/defectV2/defect/analysis/tranformHtmlToWord")
@ResponseBodypublicMessageBean tranformHtmlToWordDocx(@RequestParam Map params,HttpServletRequest request, HttpServletResponse response) {try{
//params包含前台传回的html内容//analysisService.tranformHtmlToWordDoc(params,response);
String content = "
" + (String) params.get("editorValue") + "";
InputStream is= new ByteArrayInputStream(content.getBytes());//utf-8//OutputStream os = new FileOutputStream("F:/analysis/test.doc");
OutputStream os =response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("问题统计分析.doc","utf-8"));
POIFSFileSystem fs= newPOIFSFileSystem();
fs.createDocument(is,"WordDocument");
fs.writeFilesystem(os);
os.close();
is.close();
fs.close();return new MessageBean("success", "生成报告成功!", null);
}catch(Exception e) {
e.printStackTrace();
utils.WriteSystemLog(sls,"ERROR", "生成报告", "生成报告失败!" +e.getCause());return new MessageBean("error", "生成报告失败!", null);
}
}
这种方式直接使用的POI附带的功能,在pom.xml需要引入POI的相关依赖。
org.apache.poi
poi
3.14
org.apache.poi
poi-ooxml
3.14