freemarker word 导出

1、ajax 请求不支持流操作,所以不能用来请求下载路径来处理业务。
处理业务之前的准备工作:(可以百度去查找相关资料,因为word文件本来就是一个xml格式的文件)
(1)、先用word 画好模板,然后另存为.XML格式的文件,用notpad++打开文件整理格式,保存之后修改后缀名为ftl格式文件,直接放到项目的包下边。

前端js处理:

function word() {
		var selectRows = $('#billTable').bootstrapTable('getSelections');
		//点击下载按钮触发的事件  
		window.location.href = '${CtxPath}/storeadmin/ec/bill/bill/dowload.do?ids='+ selectRows[0].id; //参数自己定
}

后台代码:

@RequestMapping("dowload")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String ids = RequestUtil.getParameterNullSafe(request, "ids");
		//String ids=request.getParameter("ids");
		
		List<BillPo> billPo = billRepository.getBillBYyId(ids);

		Map<String, Object> dataMap = new HashMap<String, Object>();
		BeanUtils.copyProperties(dataMap, billPo.get(0));
		dataMap.put("name", billPo.get(0).getName());
		dataMap.put("address", billPo.get(0).getAddress());
		dataMap.put("telephone", billPo.get(0).getTelephone());

		dataMap.put("phone", billPo.get(0).getPhone());
		dataMap.put("mail", billPo.get(0).getMail());
		dataMap.put("chargeState", billPo.get(0).getChargeState());

		dataMap.put("eleCode", billPo.get(0).getEleCode());
		dataMap.put("eleLast", billPo.get(0).getEleLast());
		dataMap.put("eleNow", billPo.get(0).getEleNow());
		dataMap.put("eleUse", billPo.get(0).getEleUse());
		dataMap.put("elePrice", billPo.get(0).getElePrice());
		dataMap.put("eleAmount", billPo.get(0).getEleAmount());

		dataMap.put("watCode", billPo.get(0).getWatCode());
		dataMap.put("watLast", billPo.get(0).getWatLast());
		dataMap.put("watNow", billPo.get(0).getWatNow());
		dataMap.put("watUse", billPo.get(0).getWatUse());
		dataMap.put("watPrice", billPo.get(0).getWatPrice());
		dataMap.put("watAmount", billPo.get(0).getWatAmount());

		dataMap.put("gesCode", billPo.get(0).getGesCode());
		dataMap.put("gesLast", billPo.get(0).getGesLast());
		dataMap.put("gesNow", billPo.get(0).getGesNow());
		dataMap.put("gesUse", billPo.get(0).getGesUse());
		dataMap.put("gesPrice", billPo.get(0).getGesPrice());
		dataMap.put("gesAmount", billPo.get(0).getGesAmount());

		dataMap.put("roomRent", billPo.get(0).getRoomRent());
		dataMap.put("eleSharing", billPo.get(0).getEleSharing());
		dataMap.put("watSharing", billPo.get(0).getWatSharing());
		dataMap.put("propertyManagementFee", billPo.get(0).getPropertyManagementFee());
		dataMap.put("netFee", billPo.get(0).getNetFee());
		dataMap.put("parkingFee", billPo.get(0).getParkingFee());

		dataMap.put("hygieneFee", billPo.get(0).getHygieneFee());
		dataMap.put("otherFee", billPo.get(0).getOtherFee());
		dataMap.put("totalFee", billPo.get(0).getTotalFee());
		dataMap.put("accountBalance", billPo.get(0).getAccountBalance());
		dataMap.put("amountFee", billPo.get(0).getAmountFee());
		// 写入doc创建文件
		WordPrint.downLoad(dataMap, "物业收费通知.doc", "物业收费通知.ftl", request, response);
	}

工具类:freemarker 处理下载。

package com.dkm.storeadmin.common;

import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.Desktop;
import java.io.*;
import java.util.Map;

/**
 * @author :cj
 * @name :WordPrint
 * @description:
 * @date :2018年10月29日13:12:01
 */
public class WordPrint {
	/**
	 * @description:生成表单文件
	 * @param dataMap
	 * @param fileName
	 * @param tempName
	 */
	public static String createWord(Map dataMap, String fileName,
			String tempName, HttpServletRequest request) {
		
		// 创建配置实例
		Configuration configuration = new Configuration();

		// 设置编码
		configuration.setDefaultEncoding("UTF-8");

		// ftl模板文件统一放至 下面
		configuration.setClassForTemplateLoading(WordPrint.class,
				"/com/dkm/storeadmin/temps/");

		//此路径获取tomcat 发布的路径,不能生成在工作空间。
		String path = request.getSession().getServletContext()
				.getRealPath("/temp");
		String outFilePath = path + "/" + fileName;
		//System.out.println(outFilePath);
		try {
			Template template = configuration.getTemplate(tempName,"utf-8");
			File outFile = new File(outFilePath);

			// 如果输出目标文件夹不存在,则创建
			if (!outFile.getParentFile().exists()) {
				outFile.getParentFile().mkdirs();
			}

			// 将模板和数据模型合并生成文件
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(outFile), "UTF-8"));

			// 生成文件
			template.process(dataMap, out);

			// 关闭流
			out.flush();
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outFilePath;
	}

	public static void downLoad(Map dataMap, String fileName, String tempName,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String outFilePath = createWord(dataMap, fileName, tempName, request);
		System.out.println(outFilePath);
		File file = new File(outFilePath);

		String realFileName = file.getName();
		//此代码设置文件头,请求浏览器当作文件来处理。
		realFileName = new String(realFileName.getBytes("GBK"), "ISO-8859-1");

		try {
			InputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.setCharacterEncoding("utf-8");
			response.reset();
			response.setContentType("application/file");
			response.setHeader("Content-disposition", "inline;filename=\""
					+ realFileName + "\";");
			response.addHeader("Content-Length", "" + file.length());
			
			OutputStream toClient = new BufferedOutputStream(
					response.getOutputStream());
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			file.delete();
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Apache POI 和 FreeMarker 来实现 Word 导出。具体步骤如下: 1. 引入依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> ``` 2. 编写模板文件,例如 `template.ftl`: ```xml <?xml version="1.0" encoding="UTF-8"?> <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:body> <w:p> <w:r> <w:t>${title}</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>${content}</w:t> </w:r> </w:p> </w:body> </w:document> ``` 3. 编写 Java 代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import java.io.*; import java.util.HashMap; import java.util.Map; public class WordExportUtil { public static void export(Map<String, Object> dataMap, String templatePath, String outputPath) throws Exception { // 1. 创建 Configuration 对象 Configuration configuration = new Configuration(Configuration.VERSION_2_3_31); configuration.setDefaultEncoding("UTF-8"); // 2. 加载模板文件 Template template = configuration.getTemplate(templatePath); // 3. 创建 Word 文档对象 XWPFDocument document = new XWPFDocument(); // 4. 填充数据到 Word 文档中 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); template.process(dataMap, outputStreamWriter); outputStreamWriter.flush(); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(line); } // 5. 输出 Word 文档 FileOutputStream fileOutputStream = new FileOutputStream(outputPath); document.write(fileOutputStream); fileOutputStream.close(); } } ``` 其中,`dataMap` 是模板中需要填充的数据,`templatePath` 是模板文件的路径,`outputPath` 是输出文件的路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值