本文實(shí)例講述了JSP上傳excel及excel插入至數(shù)據(jù)庫(kù)的方法。分享給大家供大家參考。具體如下:
此導(dǎo)入excel是與pojo綁定的,(缺點(diǎn))excle表頭必須是pojo的字段值
1. html頁(yè)面:
form id="myform" method="post" enctype="multipart/form-data"> table> tr> td>/td> td> input type="file" name="filepath" id="filepath" class="easyui-validatebox" required=true validType="equalLength[4]" missingMessage="文件!" value="" /> /td> /tr> tr align="center"> td colspan="2"> a id="btn1" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" style="width: 60px" onclick="subForm();">OK/a> a id="btn2" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" style="width: 60px" onclick="closeDig();">Cancel/a> /td> /tr> /table> /form> script type="text/javascript"> function subForm(){ if($('#myform').form('validate')){ /** var filepath = $("#filepath").val(); alert(filepath); $.ajax({ url: 'excleImport', typs: "post", data: {"filepath":filepath}, async: false, error: function(request) { $('#dg').datagrid('reload'); closeDig(); $.messager.alert("操作提示", "操作成功!","info"); }, success: function(data) { alert("success"); } }); **/ var filepath = $("#filepath").val(); var re = /(\\+)/g; var filename = filepath.replace(re,"#"); //對(duì)路徑字符串進(jìn)行剪切截取 var one = filename.split("#"); //獲取數(shù)組中最后一個(gè),即文件名 var two = one[one.length-1]; //再對(duì)文件名進(jìn)行截取,以取得后綴名 var three = two.split("."); //獲取截取的最后一個(gè)字符串,即為后綴名 var last = three[three.length-1]; //添加需要判斷的后綴名類型 var tp = "xls,xlsx"; //返回符合條件的后綴名在字符串中的位置 var rs = tp.indexOf(last); if(rs != -1){ $("#myform").attr("action","excleImport"); $("#myform").submit(); }else{ $.messager.alert("操作提示", "您選擇的上傳文件不是有效xls或者xlsx文件!","error"); return false; } } else { $.messager.alert("操作提示", "請(qǐng)選擇上傳文件!","error"); } } /script>
2. java代碼:
@RequestMapping("/excleImport") public void excleImport(HttpServletRequest request) throws IOException, Exception { request.setCharacterEncoding("utf-8"); //設(shè)置編碼 //獲得磁盤文件條目工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //獲取文件需要上傳到的路徑 String path = request.getRealPath("/upload/kaku"); File uploadDir = new File(path); if (!uploadDir.exists()) { uploadDir.mkdirs(); } factory.setRepository(uploadDir); //設(shè)置 緩存的大小,當(dāng)上傳文件的容量超過(guò)該緩存時(shí),直接放到 暫時(shí)存儲(chǔ)室 factory.setSizeThreshold(1024*1024) ; //高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory); //可以上傳多個(gè)文件 ListFileItem> list = (ListFileItem>)upload.parseRequest(request); for(FileItem item : list) { //獲取表單的屬性名字 String name = item.getFieldName(); //如果獲取的 表單信息是普通的 文本 信息 if(item.isFormField()) { //獲取用戶具體輸入的字符串 ,名字起得挺好,因?yàn)楸韱翁峤贿^(guò)來(lái)的是 字符串類型的 String value = item.getString() ; request.setAttribute(name, value); } //對(duì)傳入的非 簡(jiǎn)單的字符串進(jìn)行處理 ,比如說(shuō)二進(jìn)制的 圖片,電影這些 else { /** * 以下三步,主要獲取 上傳文件的名字 */ //獲取路徑名 String value = item.getName() ; //索引到最后一個(gè)反斜杠 int start = value.lastIndexOf("\\"); //截取 上傳文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start+1); //文件后綴名 String prefix = filename.substring(filename.lastIndexOf(".") + 1); CardCenter cardCenter = new CardCenter(); request.setAttribute(name, filename); //真正寫到磁盤上 //它拋出的異常 用exception 捕捉 //item.write( new File(path,filename) );//第三方提供的 //手動(dòng)寫的 //OutputStream out = new FileOutputStream(new File(path,filename)); InputStream in = item.getInputStream() ; ListCardCenter> listFromExcel = (ListCardCenter>)ExelUtil.exportListFromExcel(in, prefix, cardCenter); this.cardCenterService.excleImport(listFromExcel); /*int length = 0 ; byte [] buf = new byte[1024] ; System.out.println("獲取上傳文件的總共的容量:"+item.getSize()); // in.read(buf) 每次讀到的數(shù)據(jù)存放在 buf 數(shù)組中 while( (length = in.read(buf) ) != -1) { //在 buf 數(shù)組中 取出數(shù)據(jù) 寫到 (輸出流)磁盤上 out.write(buf, 0, length); } */ in.close(); //out.close(); } } }
3. java代碼:
public class ExelUtil { //第一列開(kāi)始 private static int start = 0; //最后一列序號(hào) private static int end =0; public static String getSubString(String str){ return str.substring(0,str.lastIndexOf(".")); } /** * 方法描述:由Excel文件的Sheet導(dǎo)出至List * @param file * @param sheetNum * @return * @throws IOException * @author * @date 2013-3-25 下午10:44:26 * @comment */ public static List?> exportListFromExcel(File file, String fileFormat,Object dtoobj) throws IOException { return exportListFromExcel(new FileInputStream(file), fileFormat,dtoobj); } /** * 方法描述:由Excel流的Sheet導(dǎo)出至List * @param is * @param extensionName * @param sheetNum * @return * @throws IOException * @author * @date 2013-3-25 下午10:44:03 * @comment */ public static List?> exportListFromExcel(InputStream is,String fileFormat,Object dtoobj) throws IOException { Workbook workbook = null; if (fileFormat.equals(BizConstant.XLS)) { workbook = new HSSFWorkbook(is); } else if (fileFormat.equals(BizConstant.XLSX)) { workbook = new XSSFWorkbook(is); } return exportListFromExcel(workbook,dtoobj); } /** * 方法描述:由指定的Sheet導(dǎo)出至List * @param workbook * @param sheetNum * @return * @author * @date 2013-3-25 下午10:43:46 * @comment */ private static ListObject> exportListFromExcel(Workbook workbook ,Object dtoobj) { ListObject> list = new ArrayListObject>(); String[] model = null; Sheet sheet = workbook.getSheetAt(0); // 解析公式結(jié)果 FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); int minRowIx = sheet.getFirstRowNum(); int maxRowIx = sheet.getLastRowNum(); for (int rowIx = minRowIx; rowIx = maxRowIx; rowIx++) { Object obj = null; if(rowIx==minRowIx){ start = sheet.getRow(rowIx).getFirstCellNum(); end = sheet.getRow(rowIx).getLastCellNum(); } Row row = sheet.getRow(rowIx); StringBuilder sb = new StringBuilder(); for (int i = start; i end; i++) { Cell cell = row.getCell(new Integer(i)); CellValue cellValue = evaluator.evaluate(cell); if (cellValue == null) { sb.append(BizConstant.SEPARATOR+null); continue; } // 經(jīng)過(guò)公式解析,最后只存在Boolean、Numeric和String三種數(shù)據(jù)類型,此外就是Error了 // 其余數(shù)據(jù)類型,根據(jù)官方文檔,完全可以忽略 switch (cellValue.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: sb.append(BizConstant.SEPARATOR + cellValue.getBooleanValue()); break; case Cell.CELL_TYPE_NUMERIC: // 這里的日期類型會(huì)被轉(zhuǎn)換為數(shù)字類型,需要判別后區(qū)分處理 if (DateUtil.isCellDateFormatted(cell)) { sb.append(BizConstant.SEPARATOR + cell.getDateCellValue()); } else { sb.append(BizConstant.SEPARATOR + cellValue.getNumberValue()); } break; case Cell.CELL_TYPE_STRING: sb.append(BizConstant.SEPARATOR + cellValue.getStringValue()); break; case Cell.CELL_TYPE_FORMULA: break; case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_ERROR: break; default: break; } } if(rowIx==minRowIx){ String index = String.valueOf(sb); String realmodel =index.substring(1, index.length()); model =realmodel.split(","); }else{ String index = String.valueOf(sb); String realvalue =index.substring(1, index.length()); String[] value =realvalue.split(","); //字段映射 try { dtoobj =dtoobj.getClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } obj = reflectUtil(dtoobj,model,value); list.add(obj); } } return list; } /** * 方法描述:字段映射賦值 * @param objOne * @param listName * @param listVales * @return * @author * @date 2013-3-25 下午10:53:43 * @comment */ @SuppressWarnings("deprecation") private static Object reflectUtil(Object objOne, String[] listName, String[] listVales) { Field[] fields = objOne.getClass().getDeclaredFields(); for (int i = 0; i fields.length; i++) { fields[i].setAccessible(true); for (int j = 0; j listName.length; j++) { if (listName[j].equals(fields[i].getName())) { try { if (fields[i].getType().getName().equals(java.lang.String.class.getName())) { // String type if(listVales[j]!=null){ fields[i].set(objOne, listVales[j]); }else{ fields[i].set(objOne, ""); } } else if (fields[i].getType().getName().equals(java.lang.Integer.class.getName()) || fields[i].getType().getName().equals("int")) { // Integer type if(listVales[j]!=null){ fields[i].set(objOne, (int)Double.parseDouble(listVales[j])); }else{ fields[i].set(objOne, -1); } }else if(fields[i].getType().getName().equals("Date")){ //date type if(listVales[j]!=null){ fields[i].set(objOne, Date.parse(listVales[j])); } }else if(fields[i].getType().getName().equals("Double") ||fields[i].getType().getName().equals("float")){ //double if(listVales[j]!=null){ fields[i].set(objOne, Double.parseDouble(listVales[j])); }else{ fields[i].set(objOne, 0.0); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } } return objOne; } }
希望本文所述對(duì)大家的JSP程序設(shè)計(jì)有所幫助。
標(biāo)簽:宿州 紅河 云浮 丹東 江西 青島 西藏 貴州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《JSP上傳excel及excel插入至數(shù)據(jù)庫(kù)的方法》,本文關(guān)鍵詞 JSP,上傳,excel,及,插入,至,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。