java按照xls模板,实现导出


/**
 * jxl2导出工具类
 * 
 * @Description <p>
 *            
 *              </p>
 *              <p>
 *              Company:/
 *              </p>
 * @author
 * @version 1.0
 * @Date 2018年7月9日
 * @Rewrite 修改记录
 */
public class JxlsUtils {

	/** jxls模版文件目录 */
	private final static String TEMPLATE_PATH = "excel";

	/**
	 * 导出excel
	 * 
	 * @param is
	 *            - excel文件流
	 * @param os
	 *            - 生成模版输出流
	 * @param beans
	 *            - 模版中填充的数据
	 * @throws IOException
	 */
	public static void exportExcel(InputStream is, OutputStream os,
			Map<String, Object> beans) throws IOException {
		Context context = new Context();
		if (beans != null) {
			for (String key : beans.keySet()) {
				context.putVar(key, beans.get(key));
			}
		}

		JxlsHelper jxlsHelper = JxlsHelper.getInstance();
		Transformer transformer = jxlsHelper.createTransformer(is, os);
		JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer
				.getTransformationConfig().getExpressionEvaluator();
		Map<String, Object> funcs = new HashMap<String, Object>();
		funcs.put("jx", new JxlsUtils()); // 添加自定义功能
		evaluator.getJexlEngine().setFunctions(funcs);
		jxlsHelper.processTemplate(context, transformer);
		os.close();
		is.close();
	}

	/**
	 * 导出excel
	 * 
	 * @param xlsPath
	 *            excel文件
	 * @param outPath
	 *            输出文件
	 * @param beans
	 *            模版中填充的数据
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void exportExcel(String xlsPath, String outPath,
			Map<String, Object> beans) throws FileNotFoundException,
			IOException {
		exportExcel(new FileInputStream(xlsPath),
				new FileOutputStream(outPath), beans);
	}

	/**
	 * 导出excel(直接导出到固定目录)
	 * 
	 * @param xls
	 *            excel文件
	 * @param out
	 *            输出文件
	 * @param beans
	 *            模版中填充的数据
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void exportExcel(File xls, File out, Map<String, Object> beans)
			throws FileNotFoundException, IOException {
		exportExcel(new FileInputStream(xls), new FileOutputStream(out), beans);
	}

	/**
	 * 导出excel(带下载)
	 * 
	 * @param templatePath
	 *            excel模板在resources/excel下的相对路径,例如:jbxx/JBXXML_EXPORT.xlsx
	 * @param fileName
	 *            下载文件默认文件名
	 * @param beans
	 *            模版中填充的数据,将要导出的额数据放到bean里面
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void exportExcel(String templatePath, String fileName,
			Map<String, Object> beans, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		// 初始化导出模板
		File templateFile = JxlsUtils.getTemplate(templatePath);

		String[] temps = templatePath.split("\\.");
		String suffix = temps[temps.length - 1];

		// 初始化导出临时文件
		String excelPath = JxlsUtils.class.getClassLoader()
				.getResource(TEMPLATE_PATH).getPath();
		UserContext userContext = ContextHolder.getUserContext();// 获取用户信息
		String tmpName = "tmp_" + userContext.getUserId() + "." + suffix;
		File outFile = new File(excelPath.replaceAll("%20", " "), tmpName);

		// 导出到临时文件
		exportExcel(new FileInputStream(templateFile), new FileOutputStream(
				outFile), beans);

		// 根据临时文件下载
		downFile(outFile, fileName, response);

	}

	public static void downFile(File file, String fileName,
			HttpServletResponse response) throws IOException {
		String[] temps = file.getName().split("\\.");
		String suffix = temps[temps.length - 1];
		// 设置文件名
		fileName = fileName.split("\\.")[0] + "." + suffix;
		// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
		response.setHeader("Content-Type",
				"application/vnd.ms-excel;charset=UTF-8");
		// 设置文件名编码
		response.setHeader("Content-Disposition", "attachment;filename="
				+ java.net.URLEncoder.encode(fileName, "UTF-8"));
		InputStream inputStream = new FileInputStream(file);
		// 3.通过response获取ServletOutputStream对象(out)
		ServletOutputStream out = response.getOutputStream();
		int b = 0;
		byte[] buffer = new byte[512];
		while (b != -1) {
			b = inputStream.read(buffer);
			// 4.写到输出流(out)中
			out.write(buffer);
		}
		inputStream.close();
		out.close();
		out.flush();
	}

	/**
	 * 获取jxls模版文件
	 */
	public static File getTemplate(String name) {
		String templatePath = JxlsUtils.class.getClassLoader()
				.getResource(TEMPLATE_PATH).getPath();
		File template = new File(templatePath.replaceAll("%20", " "), name);
		if (template.exists()) {
			return template;
		}
		return null;
	}

	// 日期格式化
	public String dateFmt(Date date, String fmt) {
		if (date == null) {
			return null;
		}
		try {
			SimpleDateFormat dateFmt = new SimpleDateFormat(fmt);
			return dateFmt.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 返回第一个不为空的对象
	public Object defaultIfNull(Object... objs) {
		for (Object o : objs) {
			if (o != null)
				return o;
		}
		return null;
	}

	// if判断
	public Object ifelse(boolean b, Object o1, Object o2) {
		return b ? o1 : o2;
	}

	// 超链接
	public WritableCellValue myHyperlink(String address, String title) {
		return new WritableHyperlink(address, title);
	}
	
	/**
	 * 导出设置背景颜色、生成下拉菜单
	 * @Description 描述
	 * @author 
	 * @version 版本
	 * @param map:当前行的数据
	 * @param columns:单元格对应的字段
	 * @param splitItem:下拉看选项,如果为null或者空字符串,认为不设置下拉选项
	 * @return
	 * @return WritableCellValue
	 * @lastAuthor 
	 * @lastDate 2018年7月27日
	 * @Rewrite 修改记录
	 */
	public WritableCellValue showColorAndDownlist(Map<String,Object> map,String columns,String splitItem){
		return new ColorAndDroupCellValue(map, columns, splitItem);
	}

	// 按值显示背景色
	public WritableCellValue showColor(Map<String,Object> map,String columns) {
		return new ColorCellValue(map, columns);
	}

	// 生成下拉菜单
	public WritableCellValue downlist(String splitItem, String value) {
		return new DropdownCellValue(splitItem, value);
	}

}

Controler层

 @RequestMapping("/excelJb")
    @ResponseBody
    public void excelJb(HttpServletResponse response, @RequestParam(value = "arrStr") String arrStr, Ke40Dto ke40Dto) {
        try {
        	//用来存查询出的数据
            HashMap<String, Object> beans = new HashMap<>();
            arrStr = arrStr.substring(0, arrStr.length() - 1);
            //调用service层查询要导出的数据
            List<Map<String, Object>> downList = bfshService.nTRExcelJb("410000", arrStr); 
            beans.put("rows", downList);
            //模板路径
            String templatePath = "sb/JBXX.xls";
            //导出模板命名
            String fileName = "经办信息";
            //执行导出
            JxlsUtils.exportExcel(templatePath, fileName, beans, response);
        } catch (Exception ex) {
            RecordLog.errorlog(this.getClass().getName(), ex.toString().replaceAll("\"", "'").replaceAll("\n", ""), "错误编码", arrStr);
        }
    }

serivce层

@Override
	public List<Map<String, Object>> nTRExcelJb(String aaa027,String bke168) {
		//查询出的数据返回
		List<Map<String, Object>> list = new ArrayList<>();
		//调用Dao层查询导出的数据
		List<Ke40Dto> ke40Dtos = bfshDao.Jbcxexcel(bke168);
		//遍历查询出的对象,并将所需要展示再exl中的数据存储到map中
		for (Ke40Dto ke40Dto1 : ke40Dtos){
			Map<String, Object> map = new HashMap<>();
			//解析json字符串
			Ke40Dto ke40Dto = JsonUtils.toBean(ke40Dto1.getBaa008(), Ke40Dto.class);
			String baf002 = "";
			if (StringUtils.isNotEmpty(ke40Dto.getBae119())){
				baf002 = DBUtils.getString("select distinct baf002 from af12 where bae119 =? ", new Object[]{ ke40Dto.getBae119()}); //付款人开户行
			}
			map.put("aaa027",ke40Dto1.getAaa027());//经办机构编码
			map.put("aae008",ke40Dto1.getAae008());//大行编码
			map.put("aae009",ke40Dto.getAae009());//开户人名称
			map.put("aae010",ke40Dto.getAae010());//银行账号
			map.put("bae119",ke40Dto.getBae119());//大额联行号
			map.put("baf002",baf002);//开户行名称
			map.put("aae030",ke40Dto1.getAae030());//开始日期
			map.put("aae031",ke40Dto1.getAae031());//结束日期
			list.add(map);
		}
		return list;
	}
	
Dao层
查询所需要导出的数据
public List<Ke40Dto> Jbcxexcel(String bke168 ){
		StringBuffer sql = new StringBuffer();
		List<Object> params = new ArrayList<>();
		sql.append(" select b.bke168, b.aab034, b.aaa027,b.aae140,b.baa004,b.baa009, b.aae030,b.aae031, b.aae100,b.baa008");
		sql.append(" from ke40 b where b.aae100 = '1'  and b.baa004 in ( '300001','300002','300003')  and b.aae100 = '1'");
		sql.append(" and to_char(sysdate, 'yyyyMMdd') between b.aae030 AND nvl(b.aae031, '30000101')");
		sql.append(" and b.bke168 in (").append(bke168).append(")");
		return DBUtils.query(sql.toString(), Ke40Dto.class, params.toArray());
	}

在这里插入图片描述

在这里插入图片描述

注:模板中的备注必须要加,模板导出按照备注中设置的,遍历放进xls中;模板中的字段必须与Service中设置的相对应。否则取不到值

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值