参考http://my.oschina.net/u/1398304/blog/338863
自己的代码
// 上传xls文件 var button = $('#importExcel'); log(button); new AjaxUpload(button, { action : 'phoneNoMarket/xlsupload', name : 'file', onSubmit : function(file, ext) { if (!(ext && /^(xls)$/.test(ext))) { alert('文件格式不正确,请选择 xls 格式的文件!', '系统提示'); return false; } this.disable(); }, onComplete : function(file, response) { this.enable(); var k = response.replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", "").replace("</pre>", ""); k=eval('('+k+')'); importlist = k.importData; convtohtml2add(k.importData); return false; } });写在$(function(){});里面
onsubmit提交之前
oncomplete执行完了
$('#importExcel');是一个超链接,也可以是<div>,button总之是一个对象
java:mybatis+springMVC
/** * 上传excel文件 * * @param request * @param response * @param session * @param file * @return */ @RequestMapping(value = "/xlsupload", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" }) public @ResponseBody String xlsupload(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam("file") MultipartFile file) { String strResult = ""; CondQueryRepHmglView repview = new CondQueryRepHmglView(); List<HmglAddGroupNumRepView> pagedata = new ArrayList<HmglAddGroupNumRepView>(); Workbook workbook; if (!file.isEmpty()) { try { // 文件保存路径 String filePath = request.getSession().getServletContext() .getRealPath("/") + "upload/" + file.getOriginalFilename(); File newfile = new File(filePath); if (!newfile.exists()) { // 转存文件 file.transferTo(new File(filePath)); } else { newfile.delete(); file.transferTo(new File(filePath)); } workbook = Workbook.getWorkbook(new File(filePath)); // 得到excel第一页的内容 Sheet sheet = workbook.getSheet(0); String delimiter = ","; List<String> dataList = new ArrayList<String>(); for (int i = 1; i < sheet.getRows(); i++) { String string = ""; for (int j = 0; j < sheet.getColumns(); j++) { // sheet.getCell(j,i).getContents();得到指定单元格的内容 string += sheet.getCell(j, i).getContents().equals("") ? " " + delimiter : sheet.getCell(j, i).getContents() + delimiter; } dataList.add(string); } for (int i = 0; i < dataList.size(); i++) { String data = dataList.get(i); String dataArray[] = data.split(","); HmglAddGroupNumRepView repRecord = new HmglAddGroupNumRepView(); // 手机号码 repRecord.setPhonenumber(dataArray[0]); // 省份 TODO: // 城市 repRecord.setAreaname(dataArray[2]); // 运营商名称 repRecord.setOperatorsname(dataArray[3]); // 新增时间 repRecord.setCreatedatetime(""); // 选定时间 repRecord.setSelectdatetime(dataArray[4]); // 推荐人号码 repRecord.setAngentno(dataArray[5]); // 状态 :默认未选中 0 repRecord.setIsselect("0"); pagedata.add(repRecord); } } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } repview.setImportData(pagedata); strResult = JsonUtil.toJson(repview); return strResult; }