public String importNotice(MultipartFile file) throws IOException { File f = null; if (file.equals("") || file.getSize() <= 0) { file = null; } else { InputStream ins = null; ins = file.getInputStream(); f = new File(file.getOriginalFilename()); ExcelUtil.inputStreamToFile(ins, f); ins.close(); } FileInputStream fis = new FileInputStream(f); Workbook wb = null; try { if (ExcelUtil.isExcel2003(f.getPath())) { wb = new HSSFWorkbook(fis); // 创建2003版本Excel工作簿对象 } else if (ExcelUtil.isExcel2007(f.getPath())) { wb = new XSSFWorkbook(fis); // 创建2007版本Excel工作簿对象 } else { System.out.println("未知版本的Excel !!!"); } Sheet sheet = wb.getSheetAt(0); // 获取第1个工作表 List<XcNotice> list = new ArrayList<XcNotice>(); int count = 0; for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); count ++; Cell cell1 = row.getCell(1); cell1.setCellType(Cell.CELL_TYPE_STRING); String id = cell1.getStringCellValue();//id Cell cell2 = row.getCell(2); cell2.setCellType(Cell.CELL_TYPE_STRING); String xcjhid = cell2.getStringCellValue();//巡察计划id Cell cell3 = row.getCell(3); cell3.setCellType(Cell.CELL_TYPE_STRING); String title = cell3.getStringCellValue();//公告标题 XcNotice xcNotice = new XcNotice(); xcNotice.setId(id); xcNotice.setXcjhId(xcjhid); xcNotice.setTitle(title); } for (int i = 0; i < list.size(); i++) { XcNotice xcNotice = list.get(i); XcNotice oldxcNotice = (XcNotice) getObjectById(XcNotice.class, xcNotice.getId()); if(oldxcNotice == null){ this.createObj(xcNotice); }else{ xcNotice.setSort(oldxcNotice.getSort()); BeanUtil.copyNotNullProperties2Bean(xcNotice, oldxcNotice); this.updateObj(oldxcNotice); } } return "导入成功,新增数据" + count + "条"; }catch (Exception e) { e.printStackTrace(); return "导入失败,新增数据0条"; } finally { fis.close(); } }
public static boolean isExcel2003(String filePath){ try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath)); if(POIFSFileSystem.hasPOIFSHeader(bis)) { System.out.println("Excel版本为excel2003及以下"); return true; } } catch (IOException e) { e.printStackTrace(); return false; } return false; }
public static boolean isExcel2007(String filePath){ try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath)); if(POIXMLDocument.hasOOXMLHeader(bis)) { System.out.println("Excel版本为excel2007及以上"); return true; } } catch (IOException e) { e.printStackTrace(); return false; } return false; }
public static void inputStreamToFile(InputStream inputStream, File file) throws IOException { try (FileOutputStream outputStream = new FileOutputStream(file)) { int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } }