首先在jsp页面中要有按钮
<a href="##" class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="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'"
onclick="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;
}
}
本文介绍如何使用JSP实现数据的导出和导入功能。通过编写特定的Java代码,可以将数据库中的数据导出到Excel表格,并且能够从Excel文件中读取数据并保存到数据库中。
194

被折叠的 条评论
为什么被折叠?



