java基于Excel模板导出

jsp页面(导出按钮):

<button class="btn btn-primary layui-operation" type="button" id="downLoad" onclick="downLoadBtn()" style="margin-left:10px;">
            <i class="fa fa-sign-out"></i>&nbsp;&nbsp;<span class="bold">导出</span>
</button>

ajax请求:

function downLoadBtn(){
        window.location.href='${ctx}/quyu/administrativecode/sysArea/exportExcelTemplate'
    }

controller:

	@ResponseBody
	@RequestMapping(value = "exportExcelTemplate")
	public void exportExcelTemplate(SysArea sysArea, HttpServletRequest request, HttpServletResponse response) {
		try {
			String fileName = "行政区划数据模板" + DateUtils.getDate("yyyy-MM-dd HH:mm:ss") + ".xlsx";
			//查询行政区划列表
			List<SysArea> list = sysAreaService.findList(sysArea);
			ExportExcel excelTemplate = new ExportExcel("行政区划数据", SysArea.class, 2).setDataList(list);

			//导出
			excelTemplate.write(response, fileName).dispose();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

ExportExcel工具类:

	/**
	 * 添加数据(通过annotation.ExportField添加数据)
	 * @return list 数据列表
	 */
	public <E> ExportExcel setDataList(List<E> list){
		for (E e : list){
			int colunm = 0;
			Row row = this.addRow();
			StringBuilder sb = new StringBuilder();
			for (Object[] os : annotationList){
				ExcelField ef = (ExcelField)os[0];
				Object val = null;
				// Get entity value
				try{
					if (StringUtils.isNotBlank(ef.value())){
						val = Reflections.invokeGetter(e, ef.value());
					}else{
						if (os[1] instanceof Field){
							val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
						}else if (os[1] instanceof Method){
							val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
						}
					}
					// If is dict, get dict label
					if (StringUtils.isNotBlank(ef.dictType())){
						val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
					}
				}catch(Exception ex) {
					// Failure to ignore
					log.info(ex.toString());
					val = "";
				}
				this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
				sb.append(val + ", ");
			}
			log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
		}
		return this;
	}

   /**
	 * 输出到客户端
	 * @param fileName 输出文件名
	 */
	public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
		response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
        response.setHeader("filename", Encodes.urlEncode(fileName));
        write(response.getOutputStream());
		return this;
	}

    /**
	 * 清理临时文件
	 */
	public ExportExcel dispose(){
		wb.dispose();
		return this;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值