使用layui从服务器上下载docx文件的流程

前端html内容

 <button class="layui-btn xiaMore">下载模板说明</button> 

前端jquery内容

//模板说明下载(通过执行ajax操作)
	  $(".xiaMore").click(function () {
   
	    $.ajax({
	   		type:"get",
	   		url:'${pageContext.request.contextPath }/headword/newfilesm',
	   		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="域名"+"文件的路径";
		    				   //关闭弹出框
		    					layer.close(index); 
		    				
		           		   }, function(index){
		    				  //取消按钮
		    			  });
				      
			       }
		          else if(res.code==5){
			        layer.msg('模板说明下载失败',{icon:5,time:1000},function(){
						//刷新本页面
						//location.reload();
				   });
		         }
	   		},
	   		error:function(){
	   			layer.msg('下载模板说明出现异常');
	   		}
	   	});
	    
	}); 

后台下载功能接口内容

 //新下载模板说明文件
	     @ResponseBody
	     @RequestMapping(value="/newfilesm")
	   	public JSONObject newfilesm(HttpServletRequest request)		
	   	{ 
	  	    //模板存在的位置
	  	   String fileoriname = request.getSession().getServletContext().getRealPath("")  + "/statics/uploadfiles/explay.docx";
			 System.out.println("fileoriname====="+fileoriname); 
	  	    
			  //模板说明下载到指定的位置
			    String filenowname=request.getSession().getServletContext().getRealPath("")+"/statics/uploadfiles/moban.docx";
				  
			 //String filenowname="D:/moban.docx";//模板说明下载到指定的位置
	   	   
			 JSONObject  jsonObject=new JSONObject();
	   	  
	   	    boolean blu= WordUtil.generateWord(null, fileoriname, filenowname);
	   	  	  if(blu)
	  			   {   
	  		 		jsonObject.put("msg", "下载模板说明成功");
	  		 		 jsonObject.put("code", 6);
	  		 		jsonObject.put("fileUrl", "/record/statics/uploadfiles/moban.docx");
				 		
	  			   }
	  			   else
	  			   {
	  				   jsonObject.put("msg", "没有读到文件");  
	  				   jsonObject.put("code", 5);
	  			   }
	  			
	   	  return jsonObject;	
	   	}
	     

插件 WordUtil类 功能接口内容

/**
 * 
 */
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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曦月合一

你的鼓励是我们前进的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值