Java实现Excel的导入导出

首先在jsp页面中要有按钮

<a href="##" class="easyui-linkbutton" data-options="iconCls:'icon-add'" οnclick="outdata()">导出</a>
<form id="fileForm" enctype="multipart/form-data" method="post"><input class="easyui-filebox" name="file" 
accept ="application/vnd.ms-excel"><a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-print'"
 οnclick="indate()">导入</a> </form>
<script type="text/javascript">
function outdata(){
        //根据自己的包名
        window.location.href="${ctx}/user_hobby/outdata.action";
}
function indate(){
	$('#fileForm').form('submit', {    
	    url:"${ctx}/user_hobby/indata.action",    
	    onSubmit: function(){    
	    	return $(this).form('validate');
	    },    
	    success:function(data){  
	    	var data = eval("("+data+")");
	    	if (data.success) {
	    		$("#user_hobby_datagrid").datagrid("reload");
			}else {
				$.messager.alert('提示',data.errmsg);
			}
	    }    
	});  
}
</script>
插入配置文件ExcelUtils.java

然后在controller层里编写

        @RequestMapping("outdata")
	@ResponseBody
	public void outdata(HttpServletResponse response){
		Shop shop = new Shop();
		shop.setRows(100);
		List<Shop> shopalldata = shopService.getalldata(shop);
                //根据自己的表写列名
                String coulumNames[] = {"商品名称","商品描述","商品价格","状态"};
		String coulums[] = {"sname","sdesc","price","zt"};
		ExcelUtils.exportExcel(response, shopalldata, coulumNames, coulums, "商品信息", "商品信息");
	}
	@RequestMapping("indata")
	@ResponseBody
	public Map<String, Object> indata(MultipartFile file){
			HashMap<String,Object> hashMap = new HashMap<String, Object>();
			try {
				String[][] strings = ExcelUtils.readexcellByInput(file.getInputStream(), file.getOriginalFilename(), 1);
				for (int i = 0; i < strings.length; i++) {
					Shop shop = new Shop();
					shop.setSname(strings[i][0]+"001");
					shop.setSdesc(strings[i][1]);
					shop.setPrice(strings[i][2]);
					shop.setZt(strings[i][3]);
					shopService.save(shop,null);
				}
				hashMap.put("success", true);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				hashMap.put("success", false);
				hashMap.put("errmsg", e.getMessage());
			}
			return hashMap;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值