天天看点

freemarker导出excel

1  将设置好格式的excel另存为xml

freemarker导出excel

2  放到项目中,我的在

freemarker导出excel

3  获取数据

@RequestMapping("/exportModel.dox")
	public void ExportModel(HttpServletRequest request, HttpServletResponse response, String startTime,String endTime ) throws Exception {

        //数据获取
        StatisticsModelExport exp = new StatisticsModelExport();
		Map<String, Map<String, Map<String, String>>> data = exp.modelSheet(dataAnalysisServiceImpl, startTime, endTime);

		String dateStr = new SimpleDateFormat("MMdd").format(Calendar.getInstance().getTime());
		String fileName = "模板导出-" + dateStr + ".xls";

		// 导出
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/x-download;");
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(fileName.getBytes("gb2312"), "ISO8859-1"));

		Configuration config = new Configuration();
		//指定默认编码格式
		config.setDefaultEncoding("UTF-8");
		//设置模版文件的路径
		config.setClassForTemplateLoading(DataGroupAggsController.class, "/");
		//获得模版包
		Template template = config.getTemplate("model.xml");
		//定义输出流,注意必须指定编码
		Writer writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
		try {
			template.process(data, writer);
		} catch (TemplateException e) {
			e.printStackTrace();
		}

	}
           

4  数据填充

用excel打开model.xml文件(还是刚刚放到项目中的那个xml文件),将表达式填充到单元格中(由于我的sheet也比较多,每个sheet也又包含多个表格,所以我的结构是比较复杂的三重map结构)

freemarker导出excel

我的map格式如下所示

freemarker导出excel

5  将填充了表达式的xml文件替换项目中的模板

6  结束

继续阅读