首先在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;
}
}