java导出生成word文档并进行下载的方法
·
前端html内容展示
<div class="col-md-1 col_top_daochu">
导出内容并进行下载
</div>
前端js内容展示
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/frame/layui/layui.all.js"></script>
//导出合同
$(document).on("click",".col_top_daochu",function(){
//获取当前词目列的ID
var headwordId = $(".col_color_zhong").attr("buttonchi");
//导出合同数据
$.ajax({
type:"post",
url:'${pageContext.request.contextPath }/headword/newfiles.json',
data:{headwordId:headwordId},
dataType:"json",
success:function(res){
if(res.code==6)
{
/* layer.msg('默认导出到桌面成功',{icon:6,time:1000},function(){
//刷新本页面
location.reload();
}); */
//导出文档流程思路:应该是先导出到服务器内部,然后再通过访问链接的形式下载导出的文档
layer.confirm('导出成功,是否下载?', {
btn: ['下载', '取消'] //可以无限个按钮
}, function(index, layero){
//res.fileUrl路径
window.location.href="http://localhost:8080"+res.fileUrl;
//点击按钮下载服务器内的文本
// window.location.href="域名"+res.fileUrl;
//关闭弹出框
layer.close(index);
}, function(index){
//取消按钮
});
}
else if(res.code==5){
layer.msg('导出失败',{icon:5,time:1000},function(){
//刷新本页面
location.reload();
});
}
},
error:function(){
layer.msg('导出合同出现异常,请查看桌面是否已存在该文档');
//刷新本页面
location.reload();
}
});
})
后端接口内容展示
//导出词目信息文件
@ResponseBody
@RequestMapping("newfiles.json")
public String savenewFile(@RequestParam("headwordId")Integer headwordId,HttpServletRequest request)
{
// String fileoriname="D:/res.docx";//模板所在位置
//模板存在的位置
String fileoriname = request.getSession().getServletContext().getRealPath("") + "/statics/uploadfiles/explay.docx";
String fileconame=request.getSession().getServletContext().getRealPath("") + "/statics/uploadfiledocxs/res1.docx";
//获取软件部署在本地的桌面路径path
// FileSystemView systemView = FileSystemView.getFileSystemView();
// File homeDirectory = systemView.getHomeDirectory();
// String path = homeDirectory.getPath();
// System.out.println("path=========="+path);
String filenowname=request.getSession().getServletContext().getRealPath("")+"/statics/uploadfiles/newWenben.docx";
//String filenowname=path+"\\"+"newWenben.docx";//模板说明下载到指定的位置
// String filenowname="newWenben.docx";//导出文档到指定的位置
Headword headword=headwordService.selectByPrimaryKey(headwordId);
Map<String, Object> mapParem=new HashMap<String, Object>();
//词目ID
mapParem.put("headwordId",headword.getHeadwordId().toString() );
// 词目标题
mapParem.put("headwordTitle", headword.getHeadwordTitle());
//词目文本内容
String headwordHtml = headword.getHeadwordContent();
String headwordcontent = headwordHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
headwordcontent = headwordcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
mapParem.put("headwordContent", headwordcontent);
//词目经文内容
String scriptureHtml = headword.getScriptureContent();
String scripturecontent = scriptureHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
scripturecontent = scripturecontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
mapParem.put("scriptureContent", scripturecontent);
//词目注释文本内容
HashMap<Object, Object> map=new HashMap<Object, Object>();
map.put("headwordId", headwordId);
List<Notes> listnotes=notesService.getSelective(map);
String noteContentHtmls="";
//bcmStr += key + ":" + value + "\n";//这里标识以\r\n为标识,表名明需要换行
for (int i = 0; i < listnotes.size(); i++) {
noteContentHtmls=noteContentHtmls+listnotes.get(i).getNotesContent()+"\n";
}
String noteContents = noteContentHtmls.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
// noteContents = noteContents.replaceAll("<a>\\s*|\t|\r\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
mapParem.put("noteContents", noteContents);
//卷名
mapParem.put("rollTitle", headword.getRoll().getRollTitle());
//经目名
mapParem.put("prayerTitle", headword.getRoll().getPrayer().getPrayerTitle());
//序目名
mapParem.put("preambleTitle",headword.getRoll().getPrayer().getPreamble().getPreambleTitle() );
//版本名
mapParem.put("editionTitle", headword.getRoll().getPrayer().getPreamble().getEdition().getEditionTitle());
//书名
mapParem.put("bookTitle", headword.getRoll().getPrayer().getPreamble().getEdition().getBook().getBookTitle());
//导出时间
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapParem.put("newDate", dateFormat.format(new Date()));
// SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
//mapParem.put("summaryTime", simpleDateFormat.format(summary.getSummaryTime()));
JSONObject jsonObject=new JSONObject();
boolean bloo= WordUtil.generateWord(null, fileoriname, fileconame);
if(bloo)
{
boolean blu= WordUtil.generateWord(mapParem, fileconame, filenowname);
if(blu)
{
jsonObject.put("msg", "导出成功");
jsonObject.put("code", 6);
jsonObject.put("fileUrl", "/record/statics/uploadfiles/newWenben.docx");
}
else
{
jsonObject.put("msg", "没有导出成功");
jsonObject.put("code", 5);
}
}
// System.out.println("jsonObject==="+jsonObject);
// System.out.println("jsonObject.toString()==="+jsonObject.toString());
return jsonObject.toString();
}
插件静态类 接口内容展示
/**
*
*/
package com.tools;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
/**
* @Title: WordUtil.java
* @Package logist
* @Description: TODO
* @author 爱奋斗的人
* @date 2018年12月19日 上午9:09:12
* @version V1.0
*/
public class WordUtil {
public static boolean generateWord(Map<String, Object> param, String fileSrc, String fileDest) {
XWPFDocument doc = null;
OPCPackage pack = null;
try {
pack = POIXMLDocument.openPackage(fileSrc);
doc = new XWPFDocument(pack);
if (param != null && param.size() > 0) {
// 处理段落
List<XWPFParagraph> paragraphList = doc.getParagraphs();
processParagraphs(paragraphList, param, doc);
}
} catch (Exception e) {
e.printStackTrace();
}
FileOutputStream fopts = null;
try {
fopts = new FileOutputStream(fileDest);
doc.write(fopts);
pack.close();
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
closeStream(fopts);
}
return true;
}
public static void closeStream(FileOutputStream fopts) {
try {
fopts.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理段落,替换关键字
*
* @param paragraphList
* @throws FileNotFoundException
* @throws InvalidFormatException
*/
public static void processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param, XWPFDocument doc)
throws InvalidFormatException, FileNotFoundException {
if (paragraphList != null && paragraphList.size() > 0) {
// 遍历所有段落
for (XWPFParagraph paragraph : paragraphList) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
System.out.println("text=========" + text);
if (text != null) {
boolean isSetText = false;
for (Entry<String, Object> entry : param.entrySet()) {
String key = entry.getKey(); //传参类实体的key值
if (text.indexOf(key) != -1) {// 在配置文件中有这个关键字对应的键
isSetText = true;
Object value = entry.getValue();//传参类实体的value值
if (value instanceof String) {// 文本替换
System.out.println("key==" + key);
//Text.Contains作用:用于判断一个字符串中是否包含某个值
if (text.contains(key)) {
//强行换行
//text = text.replace(key, value.toString());
String[] newtext = value.toString().split("\n");
if(newtext.length>0) {
for (int f = 0; f < newtext.length; f++) {
if (f == 0) {
run.setText(newtext[f].trim());
} else {
// run.addCarriageReturn();//硬回车
// 换行
run.addBreak();
run.setText(newtext[f].trim());
}
}
text = text.replace(key, "");
}else {
text = text.replace(key, value.toString());
}
}
}
}
}
if (isSetText) {
run.setText(text, 0);
}
}
}
}
}
}
}
更多推荐
所有评论(0)