List of usage examples for org.apache.poi.ss.usermodel Sheet getLastRowNum
int getLastRowNum();
From source file:com.ssic.education.provider.controller.ProSupplierController.java
/** * ??/* w w w . ja va 2 s . c o m*/ * * @param file * @param request * @param response * @return * @author chenminghai * @throws IOException */ @RequestMapping("/supplierImport") @ResponseBody public Json supplierImport(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { Json j = new Json(); SessionInfo info = (SessionInfo) request.getSession().getAttribute(ConfigUtil.SESSIONINFONAME); // ???id String supplierId = info.getSupplierId(); String errorMsg = null; Map<String, Map<ProSupplierReceiver, ProSupplier>> map = new HashMap(); Set<String> set = new HashSet(); try (Workbook wb = WorkbookFactory.create(file.getInputStream());) { Sheet sheet = wb.getSheetAt(0); Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.M.d"); if (sheet == null) { return null; } for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { if (errorMsg != null) { break; } Map<ProSupplierReceiver, ProSupplier> suppliers = new HashMap(); ProSupplier supplier = null; ProSupplierReceiver psr = null; Row row = sheet.getRow(rowNum); int n = 0; for (int i = 0; i < row.getLastCellNum(); i++) { if (errorMsg != null) { break; } Cell cell = row.getCell(i); String value = ParseExcelUtil.getStringCellValue(cell); if (value != null) { value = value.trim(); } if (i == 0) { // ?? if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "???????"; break; } ProSupplier s = supplierService.findProSupplierByName(value, supplierId); if (s != null) { errorMsg = "" + (rowNum + 1) + "??????"; break; } if (map.get(value) != null) { errorMsg = "" + (rowNum + 1) + "????????"; break; } supplier = new ProSupplier(); supplier.setSupplierName(value); supplier.setCreateTime(now); supplier.setUpdater(info.getId()); supplier.setLastUpdateTime(now); supplier.setStat(1); } else if (i == 1) { // ??? if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "??????"; break; } supplier.setAddress(value); // } else if (i == 2) { // // ? // if (StringUtils.isBlank(value)) { // n += 1; // break; // } // supplier.setFoodServiceCode(value); // } else if (i == 2) { // if (StringUtils.isBlank(value)) { // n += 1; // break; // } // supplier.setFoodBusinessCode(value); } else if (i == 2) { if (StringUtils.isBlank(value)) { n += 1; continue; } supplier.setFoodCirculationCode(value); } else if (i == 3) { if (StringUtils.isBlank(value)) { if (n == 1) { errorMsg = "" + (rowNum + 1) + "???"; } break; } supplier.setFoodProduceCode(value); // } else if (i == 6) { // if (StringUtils.isBlank(value)) { // if (n == 4) { // errorMsg = "" + (rowNum + 1) // + "?????"; // } // break; // } // supplier.setBusinessLicense(value); // } else if (i == 7 && !StringUtils.isBlank(value)) { // // ??? // int x = srService.findBySupplierCode(value, supplierId); // if (x != 0) { // errorMsg = "" + (rowNum + 1) + "?????"; // break; // } // if(value!=null&& !StringUtils.isBlank(value)){ // int s=set.size(); // set.add(value); // if(s==set.size()){ // errorMsg = "" + (rowNum + 1) + "???????"; // break; // } // } // psr = new ProSupplierReceiver(); // psr.setSupplierCode(value); } else if (i == 4) { // ? if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "????"; break; } supplier.setCorporation(value); } else if (i == 5) { // ?? if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "????"; break; } supplier.setContactWay(value); } } if (supplier != null && errorMsg == null) { supplier.setId(UUID.randomUUID().toString()); supplier.setSupplierType(0); supplier.setReviewed((byte) 1); if (psr == null) { psr = new ProSupplierReceiver(); } psr.setId(UUID.randomUUID().toString()); psr.setSupplierId(supplier.getId()); psr.setReceiverId(supplierId); psr.setCreateTime(new Date()); psr.setLastUpdateTime(psr.getCreateTime()); suppliers.put(psr, supplier); map.put(supplier.getSupplierName(), suppliers); } } } catch (EncryptedDocumentException | InvalidFormatException e) { errorMsg = "Excel??"; } if (errorMsg != null) { j.setMsg(errorMsg); j.setSuccess(false); } else { int r = supplierService.importSupplier(map); j.setMsg("?" + r + "??"); j.setSuccess(true); } return j; }
From source file:com.ssic.education.provider.controller.WaresController.java
@RequestMapping(value = "/import") @ResponseBody//from w w w . ja v a2 s .co m /** * ?excel * * @param file * @param request * @param response * @return * @author zhangjiwei * @since 2016.5.21 */ public Json importExcel(@RequestParam("filename") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { Json j = new Json(); SessionInfo info = (SessionInfo) request.getSession().getAttribute(ConfigUtil.SESSIONINFONAME); // ?id String supplierId = info.getSupplierId(); String errorMsg = null; // ?excellist List<ProWares> list = new ArrayList(); Set<String> set = new HashSet(); // ?excel try (Workbook wb = WorkbookFactory.create(file.getInputStream());) { Sheet sheet = wb.getSheetAt(0); if (sheet == null) { return null; } Date now = new Date(); for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { if (errorMsg != null) { break; } ProWares dto = new ProWares(); Row row = sheet.getRow(rowNum); for (int i = 0; i < row.getLastCellNum(); i++) { if (errorMsg != null) { break; } Cell cell = row.getCell(i); String value = ParseExcelUtil.getStringCellValue(cell); if (value != null) { value = value.trim(); } if (i == 0) { if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "?????"; break; } // ??? dto.setWaresName(value); } else if (i == 1) { if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "??????"; break; } // ? dto.setAmountUnit(value); } else if (i == 2) { // ? dto.setSpec(value); } else if (i == 3) { if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "???"; break; } // ? try { dto.setWaresType(ProductClass.fromName(value)); if (dto.getWaresType() == null) { errorMsg = "" + (rowNum + 1) + "???"; break; } } catch (Exception e) { errorMsg = "" + (rowNum + 1) + "???"; break; } } else if (i == 4) { // ? if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "????"; break; } dto.setManufacturer(value); // ??? ProWares pw = waresService.findProWarsByNameSpecManu(dto.getWaresName(), dto.getAmountUnit(), dto.getManufacturer(), supplierId); if (pw != null) { errorMsg = "" + (rowNum + 1) + "???"; break; } String mark = dto.getWaresName() + "," + dto.getAmountUnit() + "," + dto.getManufacturer(); int m = set.size(); set.add(mark); if (m == set.size()) { errorMsg = "" + (rowNum + 1) + "?????"; break; } // } else if (i == 4 && StringUtils.isNotBlank(value)) { // // ?? // dto.setEnName(value); // } else if (i == 5 && StringUtils.isNotBlank(value)) { // // ??? // dto.setBarCode(value); // } else if (i == 6 && StringUtils.isNotBlank(value)) { // // ?? // dto.setCustomCode(value); } else if (i == 5 && StringUtils.isNotBlank(value)) { // ? try { dto.setShelfLife(Integer.parseInt(value)); } catch (Exception e) { errorMsg = "" + (rowNum + 1) + "?????"; break; } } else if (i == 6) { // ??? if (dto.getShelfLife() != null) { if (StringUtils.isBlank(value)) { errorMsg = "" + (rowNum + 1) + "????"; break; } dto.setUnit(value); } else { if (StringUtils.isNotBlank(value)) { dto.setShelfLife(0); dto.setUnit(value); } } } else if (i == 7 && StringUtils.isNotBlank(value)) { // dto.setPlace(value); } } if (errorMsg != null) { break; } dto.setSupplierId(supplierId); dto.setWay(0); dto.setDishes(false); dto.setCreator(info.getId()); dto.setCreateTime(now); dto.setUpdater(info.getId()); dto.setLastUpdateTime(now); dto.setStat(1); list.add(dto); } } catch (EncryptedDocumentException | InvalidFormatException e) { errorMsg = "Excel??"; } if (errorMsg != null) { // TODO ??? j.setMsg(errorMsg); j.setSuccess(false); return j; } else { // ? waresService.addProWares(list); j.setMsg("??"); j.setSuccess(true); return j; } }
From source file:com.ssy.havefun.f3d.F3DDaoImpl.java
@Override public List<F3DEntity> doImport() throws IOException { List<F3DEntity> list = new ArrayList<>(); Workbook wb;/*ww w.j a v a2s .c o m*/ try { wb = WorkbookFactory.create(new File("C:/Users/jsun/Downloads/2015.xls")); Sheet sheet = wb.getSheetAt(2); for (int i = 0; i < sheet.getLastRowNum() + 1; i++) { Row row = sheet.getRow(i); F3DEntity f3d = new F3DEntity(); for (int j = 0; j < 10; j++) { Cell cell = row.getCell(j); String value = getCellValue(cell); switch (j) { case 0: f3d.setsId(Integer.parseInt(value)); break; case 1: f3d.setDate(value.replaceAll("-", "").substring(0, 8)); break; case 2: char[] values = value.toCharArray(); f3d.setFirst(Integer.parseInt(String.valueOf(values[0]))); f3d.setSecond(Integer.parseInt(String.valueOf(values[1]))); f3d.setThird(Integer.parseInt(String.valueOf(values[2]))); break; case 3: break; case 4: f3d.setSale(Integer.parseInt(value)); break; case 5: f3d.setDirect(Integer.parseInt(value)); break; case 6: break; case 7: f3d.setThirdCombination(Integer.parseInt(value)); break; case 8: break; case 9: f3d.setSixCombination(Integer.parseInt(value)); break; } } System.out.println(f3d.toString()); list.add(f3d); } } catch (InvalidFormatException ex) { Logger.getLogger(F3DDaoImpl.class.getName()).log(Level.SEVERE, null, ex); } return list; }
From source file:com.svi.uzabase.logic.ExtractData.java
private List<String> extractCompanyNames() { List<String> companyList = new ArrayList<>(); try {//w ww .j ava2 s . co m FileInputStream inputStream = new FileInputStream(new File(COMPANY_EXCEL_PATH)); Workbook workbook = new HSSFWorkbook(inputStream); Row row; Cell cell; Sheet sheet; sheet = workbook.getSheetAt(0); for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { row = sheet.getRow(rowIndex); for (int colIndex = 0; colIndex < row.getLastCellNum(); colIndex++) { cell = row.getCell(colIndex); cell.setCellType(Cell.CELL_TYPE_STRING); if (colIndex == 1) { companyList.add(cell.getStringCellValue().toUpperCase()); } } } //Closes opened documents inputStream.close(); workbook.close(); } catch (IOException ex) { Logger.getLogger(ExtractData.class.getName()).log(Level.SEVERE, null, ex); } return companyList; }
From source file:com.swordlord.gozer.components.csv.GCsvList.java
License:Open Source License
private void createRows(Sheet sheet) { DataBindingMember dbMember = _obList.getDataBindingMember(); DataBindingContext dbc = getFrameExtension().getDataBindingContext(); DataBindingManager dbManager = dbc.getDataBindingManager(dbMember); List<DataRowBase> subList = null; String strOrdering = _obList.getOrdering(); if ((strOrdering != null) && (strOrdering.length() > 0)) { OrderingParam orderingParam = new OrderingParam(strOrdering, true, false); subList = dbManager.getRows(dbMember, orderingParam); } else {/*w ww . j a v a2s.co m*/ subList = dbManager.getRows(dbMember); } if ((subList == null) || (subList.size() == 0)) { return; } int nColumns = 0; LinkedList<ObjectBase> children = _obList.getChildren(); if (children.size() > 0) { // TODO fix this hack nColumns = children.size(); } Iterator<DataRowBase> it = subList.iterator(); while (it.hasNext()) { Row row = sheet.createRow(sheet.getLastRowNum() + 1); DataRowBase dataRow = it.next(); for (int i = 0; i < nColumns; i++) { final ObjectBase child = children.get(i); Cell cell = row.createCell(i); if ((child.getClass().equals(GField.class)) || (child.getClass().equals(GCodeField.class))) { DataBinding dataBindingChild = child.getDataBinding(); Object oValue = dataBindingChild.getFormattedValue(dataRow); String strValue = oValue == null ? "" : oValue.toString(); cell.setCellValue(strValue); } } } }
From source file:com.tecacet.jflat.excel.PoiExcelReader.java
License:Apache License
protected void readSheet(Sheet sheet, FlatFileReaderCallback<T> callback) { for (int rowIndex = sheet.getFirstRowNum(); rowIndex <= sheet.getLastRowNum(); rowIndex++) { Row row = sheet.getRow(rowIndex); if (rowIndex < skipLines + sheet.getFirstRowNum()) { continue; }// w ww .j av a2 s . co m String[] tokens = readRow(row); T bean = rowMapper.getRow(tokens, rowIndex + 1); callback.processRow(rowIndex, tokens, bean); } }
From source file:com.vaadin.addon.spreadsheet.Spreadsheet.java
License:Open Source License
private int getLastNonBlankRow(Sheet sheet) { for (int r = sheet.getLastRowNum(); r >= 0; r--) { Row row = sheet.getRow(r);/*w ww. ja v a 2s . co m*/ if (row != null) { for (short c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) { Cell cell = row.getCell(c); if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) { return r; } } } } return 0; }
From source file:com.vaadin.addon.spreadsheet.SpreadsheetFactory.java
License:Open Source License
/** * Calculate size-related values for the sheet. Includes row and column * counts, actual row heights and column widths, and hidden row and column * indexes./*from ww w . j a v a 2 s . c om*/ * * @param spreadsheet * @param sheet */ static void calculateSheetSizes(final Spreadsheet spreadsheet, final Sheet sheet) { // Always have at least the default amount of rows int rows = sheet.getLastRowNum() + 1; if (rows < spreadsheet.getDefaultRowCount()) { rows = spreadsheet.getDefaultRowCount(); } spreadsheet.getState().rows = rows; final float[] rowHeights = new float[rows]; int cols = 0; int tempRowIndex = -1; final ArrayList<Integer> hiddenRowIndexes = new ArrayList<Integer>(); for (Row row : sheet) { int rIndex = row.getRowNum(); // set the empty rows to have the default row width while (++tempRowIndex != rIndex) { rowHeights[tempRowIndex] = spreadsheet.getState().defRowH; } if (row.getZeroHeight()) { rowHeights[rIndex] = 0.0F; hiddenRowIndexes.add(rIndex + 1); } else { rowHeights[rIndex] = row.getHeightInPoints(); } int c = row.getLastCellNum(); if (c > cols) { cols = c; } } if (rows > sheet.getLastRowNum() + 1) { float defaultRowHeightInPoints = sheet.getDefaultRowHeightInPoints(); int lastRowNum = sheet.getLastRowNum(); // if sheet is empty, also set height for 'last row' (index // zero) if (lastRowNum == 0) { rowHeights[0] = defaultRowHeightInPoints; } // set default height for the rest for (int i = lastRowNum + 1; i < rows; i++) { rowHeights[i] = defaultRowHeightInPoints; } } spreadsheet.getState().hiddenRowIndexes = hiddenRowIndexes; spreadsheet.getState().rowH = rowHeights; // Always have at least the default amount of columns if (cols < spreadsheet.getDefaultColumnCount()) { cols = spreadsheet.getDefaultColumnCount(); } spreadsheet.getState().cols = cols; final int[] colWidths = new int[cols]; final ArrayList<Integer> hiddenColumnIndexes = new ArrayList<Integer>(); for (int i = 0; i < cols; i++) { if (sheet.isColumnHidden(i)) { colWidths[i] = 0; hiddenColumnIndexes.add(i + 1); } else { colWidths[i] = ExcelToHtmlUtils.getColumnWidthInPx(sheet.getColumnWidth(i)); } } spreadsheet.getState().hiddenColumnIndexes = hiddenColumnIndexes; spreadsheet.getState().colW = colWidths; }
From source file:com.waveconn.Excel2MySQL.java
License:Apache License
void dbImport() { FileInputStream excel_file = null; try {/* w w w. j a v a2s. co m*/ excel_file = new FileInputStream(new File(excel_file_path)); } catch (FileNotFoundException e) { System.out.println("File not found: " + excel_file_path); System.exit(-3); } try { workbook = WorkbookFactory.create(excel_file); evaluator = workbook.getCreationHelper().createFormulaEvaluator(); formatter = new DataFormatter(true); Sheet sheet = null; Row row = null; int lastRowNum = 0; System.out.println("Reading excel file content from " + excel_file_path); // Discover how many sheets there are in the workbook.... int numSheets = workbook.getNumberOfSheets(); // and then iterate through them. for (int i = 0; i < numSheets; i++) { // Get a reference to a sheet and check to see if it contains any rows. sheet = workbook.getSheetAt(i); if (sheet.getPhysicalNumberOfRows() > 0) { // Note down the index number of the bottom-most row and // then iterate through all of the rows on the sheet starting // from the very first row - number 1 - even if it is missing. // Recover a reference to the row and then call another method // which will strip the data from the cells and build lines lastRowNum = sheet.getLastRowNum(); int start = 0; if (!is_read_first_line) start = 1; for (int j = start; j <= lastRowNum; j++) { row = sheet.getRow(j); this.rowToData(row); } } } } catch (IOException e) { e.printStackTrace(); System.out.println("IOException: " + excel_file_path); System.exit(-4); } catch (InvalidFormatException e) { e.printStackTrace(); System.out.println("Invalid Format: " + excel_file_path); System.exit(-5); } finally { if (excel_file != null) { try { excel_file.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("IOException: " + excel_file_path); System.exit(-6); } } } //put valid rows into DB System.out.println("Inserting valid rows into DB table " + db_url + "/" + db_table); insertDB(); System.out.println(); //save invalid rows if any int errs = errorRows.size(); if (errs > 0) { saveError(); } else { System.out.println("There is no invalid row"); } }
From source file:com.xn.interfacetest.service.impl.TestCaseServiceImpl.java
License:Open Source License
private StringBuffer readExcel(String path) throws Exception { // ?Excel/* www . j av a 2s. c o m*/ InputStream excelFile = new FileInputStream(path); //????? StringBuffer failCaseNumbers = new StringBuffer(""); try { Workbook wb = WorkbookFactory.create(new File(path)); Sheet sheet = wb.getSheetAt(0); // int rowNum = sheet.getLastRowNum() + 1; logger.info("rowNum" + rowNum); //?1 Row row = sheet.getRow(0); int colNum = row.getPhysicalNumberOfCells(); //? logger.info("colNum" + colNum); // 2, for (int i = 1; i < rowNum; i++) { TestCaseDto caseDto = new TestCaseDto(); logger.info("??" + i); row = sheet.getRow(i); //??? //?---? String number = getCellFormatValue(row.getCell(0)) + ""; //? if (!checkCaseNumberUnique(number)) { failCaseNumbers.append("?").append(number) .append("??"); continue; } caseDto.setNumber(number); //?---?? caseDto.setName(getCellFormatValue(row.getCell(1)) + ""); //?---?? caseDto.setDescription(getCellFormatValue(row.getCell(2)) + ""); //?---?id,?id?id? if (StringUtils.isBlank(getCellFormatValue(row.getCell(3)) + "") || !checkInterfaceIdExist(Long.parseLong(getCellFormatValue(row.getCell(3)) + ""))) { failCaseNumbers.append("?").append(number) .append("???id") .append(row.getCell(3)).append(""); continue; } caseDto.setInterfaceId(Long.parseLong(getCellFormatValue(row.getCell(3)) + "")); //5?---? caseDto.setCustomParams(getCellFormatValue(row.getCell(4)) + ""); caseDto.setCustomParamsType(ParamsGroupTypeEnum.CUSTOM.getId()); //6?---? caseDto.setCustomParamsType(AppendParamEnum.getIdByName(getCellFormatValue(row.getCell(5)) + "")); //10- if ("SINGLE".equals(getCellFormatValue(row.getCell(9))) || "MUTIPLE".equals(getCellFormatValue(row.getCell(9)))) { caseDto.setType(getCellFormatValue(row.getCell(9)) + ""); } else { failCaseNumbers.append("?").append(number) .append("???\"MUTIPLE\"\"SINGLE\""); continue; } caseDto = this.save(caseDto); logger.info("?" + caseDto.toString()); //7?---? String assertJson = getCellFormatValue(row.getCell(6)) + ""; if (StringUtils.isNotBlank(assertJson)) { try { //?? saveParamsAsserts(assertJson, caseDto); } catch (Exception e) { logger.error("?", e); failCaseNumbers.append("?").append(number).append( "???,??"); } } //8-? String prepareStr = getCellFormatValue(row.getCell(7)) + ""; if (StringUtils.isNotBlank(prepareStr)) { try { saveDataOperate(prepareStr, caseDto.getId(), OperationTypeEnum.PREPARE.getId(), failCaseNumbers); caseDto.setDataPrepare(1); // update(caseDto); } catch (Exception e) { logger.error("?sql", e); failCaseNumbers.append("?").append(number).append( "????,??" + e.getMessage() + ""); } } //9-? String clearStr = getCellFormatValue(row.getCell(8)) + ""; if (StringUtils.isNotBlank(clearStr)) { try { saveDataOperate(clearStr, caseDto.getId(), OperationTypeEnum.CLEAR.getId(), failCaseNumbers); caseDto.setDataClear(1); // update(caseDto); } catch (Exception e) { logger.error("?sql", e); failCaseNumbers.append("?").append(number).append( "????,??" + e.getMessage() + ""); } } else { continue; } } } catch (FileNotFoundException e) { logger.error("excel", e); throw e; } catch (IOException e) { logger.error("?excel", e); throw e; } finally { return failCaseNumbers; } }