前几天在做项目时,有导入excel文件,之前已经有写好的现成的导入方法,但客户的要求是能导入.xlsx文件,但我们的方法只能导入.xls的文件。在网上找了一些方法,在eclipse中没有报错,但是编译的时候报错是找不到文件,后来从 poi官网 上下载最新的jar包(3.13),导入项目,再次编译没有报错,
但是在导入文件的时候还会是报错,后俩查看日志的时候发现是jar包冲突,因为本人是用的ofbiz做项目,ofbiz中自带的poi的jar包是3.10的,可能是
不兼容.xlsx的导入方法,所以在我导入最新poi的jar包,编译的时候没有报错,但是在调用方法的时候,两个jar包冲突了,果断把3.10的清除,重新编译,启动,果然两种格式的文件都能够导入。被注释掉的是以前的代码:
1 public static List<Map> importExcel(HttpServletRequest request, List filedNames) 2 throws IOException 3 { 4 List<Map> resultList = FastList.newInstance(); 5 try 6 { 7 FileItemFactory factory = new DiskFileItemFactory(); 8 ServletFileUpload upload = new ServletFileUpload(factory); 9 List<FileItem> lst = upload.parseRequest(request); 10 FileItem fi = null; 11 for (int i = 0; i < lst.size(); i++) 12 { 13 14 fi = lst.get(i); 15 String filePath = fi.getName(); 16 String fileType = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()); 17 if (!fi.isFormField()) 18 { 19 InputStream inputStream = new BufferedInputStream(fi.getInputStream()); 20 Workbook workbook = null; 21 if (fileType.equals("xls")) { 22 workbook = new HSSFWorkbook(inputStream); 23 } else if (fileType.equals("xlsx")) { 24 //workbook = new XSSFWorkbook(inputStream); 25 workbook = WorkbookFactory.create(inputStream); 26 } 30 //Workbook workbook = Workbook.getWorkbook(inputStream); 31 //workbook.getSheetAt(arg0) 32 Sheet sheet1 = workbook.getSheetAt(0); 33 //workbook.getSheetName(arg0) 34 int r = 1; 35 for(Row row:sheet1){ 36 if(r!=1){ 37 Map map = FastMap.newInstance(); 38 for (int f = 0; f < filedNames.size(); f++) 39 { 40 map.put(filedNames.get(f), row.getCell(f)); 41 } 42 } 43 r++; 44 } 45 46 47 /* while (r < sheet1.get) 48 { 49 if(UtilValidate.isNotEmpty(sheet1.getCell(0, r).getContents())){ 50 Map map = FastMap.newInstance(); 51 for (int f = 0; f < filedNames.size(); f++) 52 { 53 map.put(filedNames.get(f), sheet1.getCell(f, r).getContents()); 54 } 55 resultList.add(map); 56 } 57 r++; 58 }*/ 59 } 60 } 61 62 } catch (Exception e) 63 { 64 e.printStackTrace(); 65 Debug.logError(e, module); 66 } 67 return resultList; 68 }