springmvc 后台
public void exportWord(HttpServletResponse response, String body)
throws Exception {
String fileName = "a.doc";
String content = "<html><head></head><body>"+StringEscapeUtils.unescapeHtml4(body)+"</body><html/>";
System.out.println(content);
byte b[] = content.getBytes();
response.reset();
response.setHeader("Content-Disposition",
"attachment;filename=" +
new String( (fileName + ".doc").getBytes(),
"iso-8859-1"));
response.setContentType("application/msword");
ByteArrayInputStream bais = new ByteArrayInputStream(b);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("word", bais);
//输出文件
response.reset();
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(documentEntry.getName() + ".doc"));
OutputStream ostream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
ostream.write(b);
ostream.flush();
ostream.close();
}
富文本使用kindeditor编辑器
<textarea id="editor_id" name="content" style="width:700px;height:300px;">
</textarea>
<a>导出</a>
获取文本的html,提交到后台。此处获取到html需要做处理,否则会导致编译
var editor;
KindEditor.ready(function(K) {
editor = K.create('#editor_id');
});
$('a').click(function () {
var form = $('<form style="display:none" method="POST"
action="/test/download"><input type="hidden" name="body" value="' +
html_encode(editor.html()) + '"/></form>');
$('body').append(form);
form.submit();
form.remove();
});
function html_encode(strHTML){
var s = "";
if (strHTML.length == 0) return "";
s = strHTML.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/\'/g, "'");
s = s.replace(/\"/g, """);
s = s.replace(/\n/g, "");
return s;
}