java生成word文档到服务器,并下载

前台js只需要一个方法,

1.Action:说明:dataMap是需要展示的数据,

String rootPath = SaveFileUtil.FILE_PATH;此处是为了判断盘符的,win系统和linux系统情况

/**
	 * 
	* @Description: 生成单
	* @date 2017年4月10日 下午4:29:04
	* @version 1.0
	* @param
	 */
	public void makeDispatch(){
		try {
			String weekuuid=request.getParameter("weekuuid");
			String dayuuid=request.getParameter("dayuuid");
			String doflag="sh";
		
			String mondaygroupper=weekPlanTaskService.queryPerson(dayuuid,doflag);
			
			String checkPer=weekPlanTaskService.queryCheckById(dayuuid);
			
			String puuid = UserUtil.getPersonUuid();
			Map person = getPerson(puuid);
			
			String userDeptName = (String)person.get("DEPT_NAME");//机构
			//获取编号---编号  
			String BUILD_NO=weekPlanTaskService.queryBuildNo();
			//路径
			String rootPath = SaveAndroidSubmitFileUtil.FILE_PATH;
			String dispatchPath = Configuration.getString("dispatch") + DateUtil.getCurrentDate("yyyyMMdd") + "/dispatch/";
			String path=rootPath+dispatchPath;//路径
			String template = "", fileName = ""; // 模版名和文件名
			Map<String, Object> dataMap = new HashMap<String, Object>(); // 要导出到word的数据
			dataMap.clear();
			template = "checkDispatchDoc.ftl";
			fileName = "么么单.doc";
			dataMap.put("CLIENTNAME", mondaygroupper);
			dataMap.put("CHECKPER", checkPer);
			dataMap.put("ORGNAME", userDeptName);
			dataMap.put("NO", BUILD_NO);
			// 导出word
			DocumentHandler doc = new DocumentHandler();
			String docFlag = doc.createDocNew(dataMap, path, fileName, template);
			elog.debug("hughman: " + docFlag);
			//保存到数据库
			String wordPath = dispatchPath + fileName;
			Map m=new HashMap();
			m.put("BUILD_PERSON", puuid);
			m.put("DOC_URL", wordPath);
			m.put("BUILD_NO", BUILD_NO);
			m.put("dayuuid", dayuuid);
			weekPlanTaskService.ModifyDispatch(m);
			//返回路径
			String filepath=dispatchPath+fileName;
			response.getWriter().write("{\"filepath\":\""+ filepath + "\"}");		
		} catch (Exception e) {
			LogUtil.error(e);
			e.printStackTrace();
		}
	}

2.判断盘符:

/**
 * 保存台上传到的文件
 */
public class SaveFileUtil {
	public static String FILE_PATH = "";	//文件地址
	public static String IMAGE_DEFAULT = "/include/images/default.jpg";
	
	static {
		Properties prop = System.getProperties();
		String os = prop.getProperty("os.name");
		if (os.indexOf("win") >= 0 || os.indexOf("Win") >= 0) {
			FILE_PATH = Configuration.getString("WIN_FILE_UPLOAD_PATH");
		} else {
			FILE_PATH = Configuration.getString("FILE_UPLOAD_PATH");
		}
	}

3.这里涉及获取编码:首先去库里查询 最大编码,然后再次基础上+1,编码的格式的 当前年与文件数的之和

 //生成编码
    public String queryBuildNo(){
    	String BuildNo=weekPlanTaskMapper.queryBuildNo();
    	String year=DateUtil.getCurrentDate("yyyy");
    	if(BuildNo.isEmpty()||BuildNo==""||BuildNo.equals("")){
    		BuildNo=year+"0001";
    	}else{
    		String Peryear=BuildNo.substring(0, 4);
    		String num=BuildNo.substring(4, 8);
    		int endNum = Integer.parseInt(num);
    		//年份是当年 就加1  不是的话换年份
    		if(Peryear.equals(year)){
    			endNum=endNum+1;
    			String NUM=String.valueOf(endNum);
    			if(NUM.length()==1){
    				NUM="000"+NUM;
    			}else if(NUM.length()==1){
    				NUM="00"+NUM;
    			}else if(NUM.length()==1){
    				NUM="0"+NUM;
    			}
    			BuildNo=Peryear+NUM;
    		}else{
    			BuildNo=year+"0001";
    		}
    	}
    	return BuildNo;
    }

4.模板的生成,首先将自己需要的word模板制作好,然后,需要导出的部门使用dataMap的字段写好,然后另存为xml格式,改名为ftl,然后搜索刚刚的字段,全部写成${字段} 即可,将ftl文件放到java的src的路径下,即可;

5.生成word的方法

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * @description 导出word文档的公共类
 * @author 
 * @date 
 */
public class DocumentHandler {

	private Configuration configuration = null;

	public DocumentHandler() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
	}
	/**
	 * 
	 * @param dataMap 要填入模本的数据文件
	 * @param path 输出文档的路径
	 * @param fileName 输出文档的名称
	 * @param templateName 模版文件名称
	 * @return flag 0000导出成功 0001模版不存在 0002文件编码异常 0003模版异常 0004导出异常
	 */
	public String createDocNew(Map<String, Object> dataMap, String path,
			String fileName, String templateName) {
		String flag = "0000";
		try {
			// 设置模本装置方法和路径,包名
			configuration.setClassForTemplateLoading(this.getClass(), "/com/icss/apcd/util/template");
			// .ftl为要装载的模板
			Template template = configuration.getTemplate(templateName);
			// 输出文档路径及名称
			File outFile = new File(path);
			if (!outFile.exists()) {
				outFile.mkdirs();
			}
			outFile = new File(path + fileName);
			/*
			 * 此处对流的编码不可或缺,使用main()单独调用时,应该可以
			 * 但是如果是web请求导出时导出后word文档就会打不开,并且报XML文件错误,主要是编码格式不正确,无法解析
			 */
			FileOutputStream fos = new FileOutputStream(outFile);
			OutputStreamWriter osWriter = new OutputStreamWriter(fos, "UTF-8");
			Writer writer = new BufferedWriter(osWriter);
			template.process(dataMap, writer);
			writer.close();
			fos.close();
		} catch (FileNotFoundException e) {
			flag = "0001";
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			flag = "0002";
			e.printStackTrace();
		} catch (TemplateException e) {
			flag = "0003";
			e.printStackTrace();
		} catch (IOException e) {
			flag = "0004";
			e.printStackTrace();
		}
		return flag;
	}

}

完结--生成word就此结束

 

 

下面的下载该word

/**
	 * 下载文件
	 */
	public String downLoadFile() {
		
		String fileName="么么单.doc";//fileName的后缀名决定下载的文件类型
		String dayuuid=request.getParameter("dayuuid");
		String url=weekPlanTaskService.getURLById(dayuuid);
		response.setContentType( "application/msword");
		//response.setContentType("images/x-dcx");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		try {
			// 这个就就是弹出下载对话框的关键代码
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			String rootPath = SaveAndroidSubmitFileUtil.FILE_PATH;
			File resFile = new File(rootPath + url);
			InputStream input = new FileInputStream(resFile);
			ServletOutputStream out = response.getOutputStream();
			byte[] buffer = new byte[1024];
			int i = 0;
			while ((i = input.read(buffer)) != -1) {
				out.write(buffer, 0, i);
			}
			input.close();
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

 

转载于:https://my.oschina.net/u/3053442/blog/876973

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值