List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt
@Override public XSSFSheet getSheetAt(int index)
From source file:db.pj.util.excel.LicenseImporter.java
License:Open Source License
@Override public List<String> importExcel() { // get workbook FileInputStream inputStream = null; XSSFWorkbook workbook = null; List<String> result = new ArrayList<String>(); result.add(""); try {// w w w . ja va 2 s. c o m inputStream = new FileInputStream(file); workbook = new XSSFWorkbook(inputStream); } catch (Exception e) { result.set(0, ""); return result; } int success = 0, fail = 0; // number of tuples UserDao userDao = DaoFactory.getUserDao(); LicenseDao licenseDao = DaoFactory.getLicenseDao(); AdministrationDao administrationDao = DaoFactory.getAdministrationDao(); XSSFSheet sheet = workbook.getSheetAt(0); XSSFRow row = null; XSSFCell cell = null; int rows = sheet.getPhysicalNumberOfRows(); for (int i = 1; i < rows; i++) { row = sheet.getRow(i); if (row == null) continue; int cells = row.getPhysicalNumberOfCells(); String[] values = new String[cells]; // read data to an array of strings for (short j = 0; j < cells; j++) { cell = row.getCell(j); if (cell == null) values[j] = null; else { switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { double d = cell.getNumericCellValue(); Date date = new Date(DateUtil.getJavaDate(d).getTime()); values[j] = date.toString(); } else { values[j] = (int) (cell.getNumericCellValue()) + ""; } break; default: values[j] = cell.getStringCellValue(); break; } } } User user = new User(); user.setUserID(IDGenerator.generateUserID(values[5] + values[6])); user.setUserPwd(StringUtil.MD5(user.getUserID())); user.setUserName(values[0]); user.setUserGender(XMLRepertory.genderStr2Num(values[1])); user.setUserIctype(Integer.parseInt(values[5])); user.setUserIcno(values[6]); user.setUserBdate(MyDateUtil.str2Date(values[2])); user.setUserPhone("00000000"); user.setUserNation(values[3]); user.setUserAddr(values[4]); user.setUserHead("user/default.png"); user.setUserHealth(0); user.setUserState(5); user.setUserPdate(new Date(System.currentTimeMillis())); License license = new License(); license.setLicnID(values[11]); license.setLicnType(values[8]); license.setLicnGdate(MyDateUtil.str2Date(values[7])); license.setLicnVdlen(Integer.parseInt(values[9])); // if point>=12, set invalid license.setLicnVinfo(Integer.parseInt(values[12])); license.setLicnValid((license.getLicnVinfo() < 12) ? 1 : 0); // license is not valid, reset health and state if (license.getLicnValid() == 0) { user.setUserHealth(-1); user.setUserState(0); } user.setLicense(license); license.setUser(user); // get administration and check whether it is valid Administration administration = administrationDao.queryAdministrationByID(values[10]); if (administration == null) { fail++; result.add("" + values[11] + ""); } else { license.setAdministration(administration); boolean re1 = userDao.addUser(user); boolean re2 = licenseDao.addLicense(license); if (re1 || re2) success++; else { fail++; result.add("" + values[11] + ""); } } } result.set(0, "" + success + "" + fail + ""); return result; }
From source file:db.pj.util.excel.PenaltyImporter.java
@Override public List<String> importExcel() { // get workbook FileInputStream inputStream = null; XSSFWorkbook workbook = null; List<String> result = new ArrayList<String>(); result.add(""); try {//from w w w . j a v a 2s .c o m inputStream = new FileInputStream(file); workbook = new XSSFWorkbook(inputStream); } catch (Exception e) { result.set(0, ""); return result; } int success = 0, fail = 0; // number of tuples LicenseDao licenseDao = DaoFactory.getLicenseDao(); PenaltyDao penaltyDao = DaoFactory.getPenaltyDao(); XSSFSheet sheet = workbook.getSheetAt(0); XSSFRow row = null; XSSFCell cell = null; int rows = sheet.getPhysicalNumberOfRows(); int cells = sheet.getRow(0).getPhysicalNumberOfCells(); for (int i = 1; i < rows; i++) { row = sheet.getRow(i); if (row == null) continue; String[] values = new String[cells]; // read data to an array of strings for (short j = 0; j < cells; j++) { cell = row.getCell(j); if (cell == null) values[j] = null; else { switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { double d = cell.getNumericCellValue(); Date date = new Date(DateUtil.getJavaDate(d).getTime()); values[j] = date.toString(); } else { values[j] = (int) (cell.getNumericCellValue()) + ""; } break; default: values[j] = cell.getStringCellValue(); break; } } } License license = licenseDao.queryLicenseByUserID(values[0]); if (license == null) { fail++; result.add("" + values[0] + "," + values[1] + "," + values[2] + ""); } else { Penalty penalty = new Penalty(); penalty.setPnltID(IDGenerator.generateUUID()); penalty.setPnltType(Integer.parseInt(values[3])); penalty.setPnltTime(MyDateUtil.str2Date(values[1])); penalty.setPnltInfo(values[2]); // set penalty point and limit if (penalty.getPnltType() == 5) { penalty.setPnltPoint(Integer.parseInt(values[5])); license.addPnltPoint(penalty.getPnltPoint()); } else { penalty.setPnltPoint(0); license.setLicnValid(0); if (penalty.getPnltType() == 3) license.setLicnLimit(MyDateUtil.getLimitDate(penalty.getPnltTime(), 100)); else license.setLicnLimit( MyDateUtil.getLimitDate(penalty.getPnltTime(), Integer.parseInt(values[4]))); } boolean re1 = licenseDao.updateLicense(license); penalty.setLicense(license); boolean re2 = penaltyDao.addPenalty(penalty); if (re1 && re2) success++; else { fail++; result.add("" + values[0] + "," + values[1] + "," + values[2] + ""); } } } result.set(0, "" + success + "" + fail + ""); return result; }
From source file:db.pj.util.excel.Phase4GradeImporter.java
@Override public List<String> importExcel() { // get workbook FileInputStream inputStream = null; XSSFWorkbook workbook = null; List<String> result = new ArrayList<String>(); result.add(""); try {/* w w w. ja v a2 s . c om*/ inputStream = new FileInputStream(file); workbook = new XSSFWorkbook(inputStream); } catch (Exception e) { result.set(0, ""); return result; } int success = 0, fail = 0; // number of tuples UserDao userDao = DaoFactory.getUserDao(); StaffDao staffDao = DaoFactory.getStaffDao(); ScheduleDao scheduleDao = DaoFactory.getScheduleDao(); ExaminationDao examinationDao = DaoFactory.getExaminationDao(); LicenseDao licenseDao = DaoFactory.getLicenseDao(); WarningDao warningDao = DaoFactory.getWarningDao(); XSSFSheet sheet = workbook.getSheetAt(0); XSSFRow row = null; XSSFCell cell = null; int rows = sheet.getPhysicalNumberOfRows(); int cells = sheet.getRow(0).getPhysicalNumberOfCells(); for (int i = 1; i < rows; i++) { row = sheet.getRow(i); if (row == null) continue; String[] values = new String[cells]; // read data to an array of strings for (short j = 0; j < cells; j++) { cell = row.getCell(j); if (cell == null) values[j] = null; else { switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: values[j] = (int) (cell.getNumericCellValue()) + ""; break; default: values[j] = cell.getStringCellValue(); break; } } } User user = userDao.queryUserByIC(Integer.parseInt(values[0]), values[1]); Schedule schedule = scheduleDao.queryScheduleByID(values[3]); Examination examination = null; if (user == null) { fail++; String ic = (Integer.parseInt(values[0]) == 1 ? "" : "") + values[1] + ""; result.add("" + ic + "" + values[3] + ""); } else if (schedule == null) { fail++; String ic = (Integer.parseInt(values[0]) == 1 ? "" : "") + values[1] + ""; result.add( "" + ic + "" + values[3] + ""); } else { examination = examinationDao.queryExaminationByUserAndSchedule(user, schedule); if (examination == null) { fail++; String ic = (Integer.parseInt(values[0]) == 1 ? "" : "") + values[1] + ""; result.add("" + ic + "" + values[3] + ""); Warning warning = new Warning(); warning.setWarnID(IDGenerator.generateUUID()); warning.setUser(user); warning.setSchedule(schedule); warning.setWarnCont(StringUtil.buildPhase14Warning(values)); warningDao.addWarning(warning); } else { examination.setStaff(staffDao.queryStaffByStaffID(values[2])); examination.setExamScore1(Integer.parseInt(values[4])); examination.setExamPass(examination.getExamScore1() >= 60 ? 1 : 0); examination.setExamFinfo(StringUtil.buildGradeFinfo(values[5])); if (examination.getExamPass() == 1 && user.getUserState() == 4) { boolean re = examinationDao.updateExamination(examination); if (re) success++; else { fail++; String ic = (Integer.parseInt(values[0]) == 1 ? "" : "") + values[1] + ""; result.add("" + ic + "" + values[3] + ""); } user.setUserState(5); License license = licenseDao.queryLicenseByUserID(user.getUserID()); if (license == null) { License newLicn = new License(); newLicn.setLicnID(IDGenerator.generateLicenseID(user.getUserID())); newLicn.setLicnType("C1"); newLicn.setLicnGdate(schedule.getSchdDate()); newLicn.setLicnVdlen(10); newLicn.setLicnValid(1); newLicn.setLicnVinfo(0); newLicn.setAdministration(schedule.getAdministration()); newLicn.setLicnLimit(null); newLicn.setUser(user); user.setLicense(license); userDao.updateUser(user); licenseDao.addLicense(newLicn); } else { license.setLicnValid(1); license.setLicnGdate(schedule.getSchdDate()); license.setLicnLimit(null); license.setLicnVinfo(0); licenseDao.updateLicense(license); } } else if (user.getUserState() < 4) { fail++; String ic = (Integer.parseInt(values[0]) == 1 ? "" : "") + values[1] + ""; result.add("" + ic + "" + values[3] + ""); } } } } result.set(0, "" + success + "" + fail + ""); return result; }
From source file:DB.TopStockDescriptionList.java
public static List<TopStockDescription> readFromFileExcel(String fileName) { List<TopStockDescription> tempTSD = new ArrayList(); String longName = ""; String shortName = ""; String explanation = ""; try {// ww w . j a v a2 s .c om ForcastUi.consoleLog("Opening filename: " + fileName); FileInputStream fIP = openExcelFileOrCreate(fileName); //Get the workbook instance for XLSX file XSSFWorkbook workbook = new XSSFWorkbook(fIP); XSSFSheet spreadsheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = spreadsheet.iterator(); XSSFRow row; while (rowIterator.hasNext()) { row = (XSSFRow) rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); // ? Cell cell = cellIterator.next(); longName = cell.getStringCellValue(); if (cellIterator.hasNext()) { cell = cellIterator.next(); shortName = cell.getStringCellValue(); if (shortName.isEmpty()) continue; } else continue; if (cellIterator.hasNext()) { cell = cellIterator.next(); explanation = cell.getStringCellValue(); if (shortName.isEmpty()) continue; } else continue; tempTSD.add(new TopStockDescription(shortName.trim(), longName.trim(), explanation.trim(), false)); } fIP.close(); } catch (FileNotFoundException e) { ErrorMessages.printErrorMsg(ErrorMessages.FILENOTFOUND, fileName); ForcastUi.consoleLog(e.getMessage()); e.printStackTrace(); } catch (IOException e) { ErrorMessages.printErrorMsg(ErrorMessages.FILECOR, fileName); ForcastUi.consoleLog(e.getMessage()); e.printStackTrace(); } catch (Exception ex) { ErrorMessages.printErrorMsg(ErrorMessages.FILECOR, fileName); ForcastUi.consoleLog(ex.getMessage()); Logger.getLogger(TopStockDescriptionList.class.getName()).log(Level.SEVERE, null, ex); } return tempTSD; }
From source file:de.contentcreation.pplive.controller.ReportingController.java
public void postProcessXLSX(Object document) { XSSFWorkbook wb = (XSSFWorkbook) document; XSSFSheet sheet = wb.getSheetAt(0); XSSFRow header = sheet.getRow(0);/*from w ww . ja va2 s. co m*/ XSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.GREEN.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); for (int i = 0; i < 11; i++) { // XSSFCell cell = header.getCell(i); sheet.autoSizeColumn(i); // cell.setCellStyle(cellStyle); } }
From source file:de.escnet.ExcelTable.java
License:Open Source License
public ExcelTable(String excel, String sheetName) throws IOException { XSSFWorkbook wb = new XSSFWorkbook(excel); evaluator = wb.getCreationHelper().createFormulaEvaluator(); theme = wb.getTheme();// www. jav a2s .com sheet = sheetName == null ? wb.getSheetAt(0) : wb.getSheet(sheetName); for (Iterator rowIt = sheet.rowIterator(); rowIt.hasNext();) { Row row = (Row) rowIt.next(); for (Iterator cellIt = row.cellIterator(); cellIt.hasNext();) { XSSFCell cell = (XSSFCell) cellIt.next(); int rowIndex = cell.getRowIndex(); rowMin = Math.min(rowMin, rowIndex); rowMax = Math.max(rowMax, rowIndex); int colIndex = cell.getColumnIndex(); colMin = Math.min(colMin, colIndex); colMax = Math.max(colMax, colIndex); } } }
From source file:de.fhg.fokus.odp.portal.uploaddata.service.Worker.java
/** * loop through all Cells and rows. Firstly, add correct keys to strings. * Secondly, parse corresponding value into correct json and add this * dataset to ckan via middleware.//from w ww . ja v a 2s . co m * * @param args * @throws Exception * * @return a String of dataset indices, which were not uploaded. */ public String readXlsx() { final StringBuilder errormessage = new StringBuilder(""); final StringBuilder resourceStringBuilder = new StringBuilder("[{"); final StringBuilder extrasStringBuilder = new StringBuilder("{"); HashMap<String, String> map = new HashMap<String, String>(); ArrayList<String> strings = new ArrayList<String>(); XSSFWorkbook workBook = null; try { workBook = new XSSFWorkbook(uploadFolder + "file.xlsx"); } catch (IOException e1) { e1.printStackTrace(); } int counter = 0; XSSFSheet sheet = workBook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: String value = cell.getRichStringCellValue().getString(); // first row, add value to strings if (counter == 0) { if (!value.startsWith("resources:") && !value.startsWith("extras:")) { map.put(value, null); } strings.add(value); break; } // compute columnIndex for later use int columnIndex = cell.getColumnIndex(); // compute parameter for later use in if-statements String parameter = strings.get(columnIndex); handleString(resourceStringBuilder, extrasStringBuilder, map, value, parameter); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { // is a date; parameter = strings.get(cell.getColumnIndex()); handleDate(map, parameter, cell, extrasStringBuilder); } else { // is a number; parameter = strings.get(cell.getColumnIndex()); handleNumber(map, parameter, cell, extrasStringBuilder); } break; default: break; } } // finish extras and resources finishParseResource(resourceStringBuilder); finishParseExtras(extrasStringBuilder); Validator.checkTagAndGroupsForEmptyValues(map); Validator.setlicenseAndNameToLowerCase(map); // add resources and extras to map map.put("resources", resourceStringBuilder.toString()); map.put("extras", extrasStringBuilder.toString()); createDataSet(errormessage, gw, map, counter); ++counter; // reset resourceStringBuilder and extrasStringBuilder resetStringBuilder(resourceStringBuilder, extrasStringBuilder); // reset map map.clear(); } if (errormessage.toString().equalsIgnoreCase("")) { // no errors return errormessage.toString(); } else { // return list of dataset indices return errormessage.substring(0, errormessage.length() - 1); } }
From source file:de.fionera.javamailer.dataProcessors.parseFilesForImport.java
/** * Gets a XLSX file and parse it/*ww w . ja v a 2s . c o m*/ * @param file The XLSX File that you want to get parsed * @return A ArrayList where the first object is a Array containing the Data and the Second the Header */ public ArrayList<Object> parseXLSXFile(File file) { int index = -1; XSSFWorkbook workbook = null; try { try { FileInputStream inputStream = new FileInputStream(file); workbook = new XSSFWorkbook(inputStream); } catch (IOException ex) { ex.printStackTrace(); } assert workbook != null; String[] strings = new String[workbook.getNumberOfSheets()]; //get all sheet names from selected workbook for (int i = 0; i < strings.length; i++) { strings[i] = workbook.getSheetName(i); } JFrame frame = new JFrame("Input Dialog"); String selectedsheet = (String) JOptionPane.showInputDialog(frame, "Which worksheet you want to import ?", "Select Worksheet", JOptionPane.QUESTION_MESSAGE, null, strings, strings[0]); if (selectedsheet != null) { for (int i = 0; i < strings.length; i++) { if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet)) index = i; } XSSFSheet sheet = workbook.getSheetAt(index); XSSFRow row = sheet.getRow(0); if (row != null) { headers = new String[row.getLastCellNum()]; for (int i = 0; i < row.getLastCellNum(); i++) { headers[i] = row.getCell(i).toString(); } } data = new String[sheet.getLastRowNum()][]; for (int j = 1; j < sheet.getLastRowNum() + 1; j++) { row = sheet.getRow(j); int rowCount = row.getLastCellNum(); String[] dataRow = new String[rowCount]; for (int i = 0; i < rowCount; i++) { XSSFCell cell = row.getCell(i, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK); dataRow[i] = cell.toString(); } data[j - 1] = dataRow; } } else { return null; } } catch (Exception e) { e.printStackTrace(); } ArrayList<Object> returnData = new ArrayList<>(); returnData.add(data); returnData.add(headers); return returnData; }
From source file:de.prokimedo.service.IcdServiceImpl.java
public List readExcel(MultipartFile file) { List<Icd> listIcd = new ArrayList(); try {//from ww w . java 2s .c om File inputWorkbook = convert(file); FileInputStream fis = new FileInputStream(inputWorkbook); // Finds the workbook instance for XLSX file XSSFWorkbook myWorkBook = new XSSFWorkbook(fis); // Return first sheet from the XLSX workbook XSSFSheet mySheet = myWorkBook.getSheetAt(0); // Get iterator to all the rows in current sheet Iterator<Row> rowIterator = mySheet.iterator(); // Traversing over each row of XLSX file while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (!row.getCell(0).toString().equals("Diagnose")) { Icd icd = new Icd(row.getCell(1).toString(), row.getCell(0).toString(), row.getCell(2).toString()); listIcd.add(icd); } } inputWorkbook.delete(); } catch (IOException ex) { Logger.getLogger(MedikamentServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } // try { // // File inputWorkbook = convert(file); // // Workbook w; // try { // w = Workbook.getWorkbook(inputWorkbook); // // Get the first sheet // Sheet sheet = w.getSheet(0); // //loop over first 10 column and lines // // for (int i = 1; i < sheet.getRows(); i++) { // // for (int j = 1; j < sheet.getColumns(); j++) { // Icd icd = new Icd(sheet.getCell(1, i).getContents(), sheet.getCell(0, i).getContents(), sheet.getCell(2, i).getContents()); // listIcd.add(icd); // // } // // } catch (BiffException e) { // System.out.println("BiffException"); // } catch (IOException ex) { // Logger.getLogger(ImageServiceImpl.class.getName()).log(Level.SEVERE, null, ex); // } // inputWorkbook.delete(); // // } catch (IOException | IndexOutOfBoundsException ex) { // Logger.getLogger(ImageServiceImpl.class.getName()).log(Level.SEVERE, null, ex); // } return listIcd; }
From source file:de.prokimedo.service.MedikamentServiceImpl.java
public List readExcel(MultipartFile file) { List<Medikament> listMed = new ArrayList(); try {/*from www . ja v a 2s .c om*/ File inputWorkbook = convert(file); FileInputStream fis = new FileInputStream(inputWorkbook); // Finds the workbook instance for XLSX file XSSFWorkbook myWorkBook = new XSSFWorkbook(fis); // Return first sheet from the XLSX workbook XSSFSheet mySheet = myWorkBook.getSheetAt(0); // Get iterator to all the rows in current sheet Iterator<Row> rowIterator = mySheet.iterator(); // Traversing over each row of XLSX file while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (!row.getCell(1).toString().equals("PZN")) { Medikament med = new Medikament(null, row.getCell(2).toString(), row.getCell(1).toString(), row.getCell(4).toString(), row.getCell(6).toString(), row.getCell(3).toString(), row.getCell(7).toString()); listMed.add(med); } } inputWorkbook.delete(); } catch (IOException ex) { Logger.getLogger(MedikamentServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return listMed; }