List of usage examples for org.apache.poi.ss.usermodel Sheet getLastRowNum
int getLastRowNum();
From source file:com.opendoorlogistics.core.tables.io.PoiIO.java
License:Open Source License
/** * Schema table can contain multiple tables... * @param sheet//from ww w .j a v a2 s. co m */ private static SchemaSheetInformation importSchemaTables(Sheet sheet, ExecutionReport report) { List<ODLTableReadOnly> tables = new ArrayList<>(); // schema tables are separated by empty rows int lastRow = sheet.getLastRowNum(); int firstRow = sheet.getFirstRowNum(); int firstNonEmptyRow = -1; int nbCols = 0; for (int x = firstRow; x <= lastRow; x++) { // check for completely empty row Row row = sheet.getRow(x); boolean isEmptyRow = true; for (int y = 0; row != null && y <= row.getLastCellNum(); y++) { if (isEmptyCell(row, y) == false) { isEmptyRow = false; } } if (isEmptyRow || x == lastRow) { // dump table if row was empty or on last row, but we previously had a non empty row if (firstNonEmptyRow != -1) { ODLDatastoreAlterable<ODLTableAlterable> tmpDs = ODLDatastoreImpl.alterableFactory.create(); ODLTableAlterable table = tmpDs.createTable(sheet.getSheetName(), -1); importSheetSubset(table, sheet, null, true, firstNonEmptyRow, isEmptyRow ? x - 1 : x, nbCols); tables.add(table); } firstNonEmptyRow = -1; } else if (firstNonEmptyRow == -1) { // initialise table if we've just found the first non empty row firstNonEmptyRow = x; nbCols = 0; for (int y = 0; y <= row.getLastCellNum(); y++) { if (isEmptyCell(row, y)) { break; } else { nbCols = y + 1; } } } } return readSchemaFromODLTables(tables, report); }
From source file:com.opendoorlogistics.studio.LoadedDatastore.java
License:Open Source License
private void updateWorkbookWithModifications(Workbook wb, ExecutionReport report) { // parse the original tables; these will be held in the datastore with the same index as the sheet int nbOriginal = originalLoadedDs.getTableCount(); if (nbOriginal != wb.getNumberOfSheets()) { throw new RuntimeException(); }//from w ww .j a va2s. co m ArrayList<ODLTableReadOnly> oldOnesToReadd = new ArrayList<>(); for (int i = nbOriginal - 1; i >= 0; i--) { ODLTableReadOnly originalTable = originalLoadedDs.getTableAt(i); ODLTableReadOnly newTable = ds.getTableByImmutableId(originalTable.getImmutableId()); if (newTable == null) { // table was deleted wb.removeSheetAt(i); } else if (DatastoreComparer.isSame(originalTable, newTable, DatastoreComparer.CHECK_ALL) == false) { Sheet sheet = wb.getSheetAt(i); boolean sameStructure = DatastoreComparer.isSameStructure(originalTable, newTable, DatastoreComparer.CHECK_ALL); if (sameStructure) { // re-write all values but skip the header row int nbOversized = 0; for (int iRow = 0; iRow < newTable.getRowCount(); iRow++) { int iTargetRow = iRow + 1; Row row = sheet.getRow(iTargetRow); if (row == null) { row = sheet.createRow(iTargetRow); } int nc = newTable.getColumnCount(); for (int col = 0; col < nc; col++) { Cell cell = row.getCell(col); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_FORMULA) { // don't set the value of formula cells... continue; } if (cell == null) { cell = row.createCell(col); } String sval = TableUtils.getValueAsString(newTable, iRow, col); if (sval != null && sval.length() > PoiIO.MAX_CHAR_COUNT_IN_EXCEL_CELL) { nbOversized++; } cell.setCellValue(sval); } } // delete any rows after the last row (including 1 for the header) int lastOKRow = newTable.getRowCount(); while (sheet.getLastRowNum() > lastOKRow) { sheet.removeRow(sheet.getRow(sheet.getLastRowNum())); } if (nbOversized > 0 && report != null) { report.log(PoiIO.getOversizedWarningMessage(nbOversized, newTable.getName())); ; } } else { // delete and replace. replace after parsing all original tables as we can get table name conflicts wb.removeSheetAt(i); oldOnesToReadd.add(newTable); } } } // re-add any totally replaced tables for (ODLTableReadOnly table : oldOnesToReadd) { Sheet sheet = wb.createSheet(table.getName()); if (sheet != null) { PoiIO.exportTable(sheet, table, report); } } // add new tables at the end for (int i = 0; i < ds.getTableCount(); i++) { ODLTableReadOnly newTable = ds.getTableAt(i); if (originalLoadedDs.getTableByImmutableId(newTable.getImmutableId()) == null) { // new table... Sheet sheet = wb.createSheet(newTable.getName()); if (sheet != null) { PoiIO.exportTable(sheet, newTable, report); } } } }
From source file:com.opengamma.financial.security.equity.GICSCodeDescription.java
License:Open Source License
/** * Load S&P GICS code mappings from an Apace POI HSSFWorkbook * @param workbook HSSFWorkbook to parse S&P GCIS Excel * @param gicsMap Map to add mappings to *//*from w ww .j ava 2s .c om*/ static void processGICSExcelWorkbook(Workbook workbook, Map<String, String> gicsMap) { //Assume 1 sheet Sheet sheet = workbook.getSheetAt(0); if (sheet == null) { return; } for (int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); if (row == null) { continue; } for (int cellNum = 0; cellNum < row.getPhysicalNumberOfCells(); cellNum++) { Cell cell = row.getCell(cellNum, Row.CREATE_NULL_AS_BLANK); if (isNumeric(cell)) { //worst case if the Excel file is in an incorrect (or updated) format // is that number -> random or empty string mappings will be created gicsMap.put(getGICSCellValue(cell), getGICSCellValue(row, cellNum + 1)); } } } }
From source file:com.openitech.db.model.ExcelDataSource.java
License:Apache License
@Override public boolean loadData(boolean reload, int oldRow) { boolean result = false; if (isDataLoaded && !reload) { return false; }/*w w w . j av a 2 s . co m*/ if (sourceFile != null) { try { Workbook workBook = WorkbookFactory.create(new FileInputStream(sourceFile)); // HSSFWorkbook workBook = new HSSFWorkbook(new FileInputStream(sourceFile)); Sheet sheet = workBook.getSheetAt(0); DataFormatter dataFormatter = new DataFormatter(Locale.GERMANY); FormulaEvaluator formulaEvaluator = workBook.getCreationHelper().createFormulaEvaluator(); int lastRowNum = sheet.getLastRowNum(); boolean isFirstLineHeader = true; //count = sheet. - (isFirstLineHeader ? 1 : 0); int tempCount = 0; for (int j = 0; j <= lastRowNum; j++) { //zane se z 0 Row row = row = sheet.getRow(j); if (row == null) { continue; } // display row number in the console. System.out.println("Row No.: " + row.getRowNum()); if (isFirstLineHeader && row.getRowNum() == 0) { populateHeaders(row); continue; } tempCount++; Map<String, DataColumn> values; if (rowValues.containsKey(row.getRowNum())) { values = rowValues.get(row.getRowNum()); } else { values = new HashMap<String, DataColumn>(); rowValues.put(row.getRowNum(), values); } // once get a row its time to iterate through cells. int lastCellNum = row.getLastCellNum(); for (int i = 0; i <= lastCellNum; i++) { DataColumn dataColumn = new DataColumn(); Cell cell = row.getCell(i); if (cell == null) { continue; } System.out.println("Cell No.: " + cell.getColumnIndex()); System.out.println("Value: " + dataFormatter.formatCellValue(cell)); if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { dataColumn = new DataColumn(dataFormatter.formatCellValue(cell, formulaEvaluator)); } else { dataColumn = new DataColumn(dataFormatter.formatCellValue(cell)); } switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: { // cell type numeric. System.out.println("Numeric value: " + cell.getNumericCellValue()); dataColumn = new DataColumn(dataFormatter.formatCellValue(cell)); break; } case Cell.CELL_TYPE_STRING: // cell type string. System.out.println("String value: " + cell.getStringCellValue()); dataColumn = new DataColumn(dataFormatter.formatCellValue(cell)); break; case Cell.CELL_TYPE_BOOLEAN: // cell type string. System.out.println("String value: " + cell.getBooleanCellValue()); dataColumn.setValue(cell.getBooleanCellValue(), Boolean.class); break; case Cell.CELL_TYPE_FORMULA: // cell type string. System.out.println( "Formula value: " + dataFormatter.formatCellValue(cell, formulaEvaluator)); dataColumn = new DataColumn(dataFormatter.formatCellValue(cell, formulaEvaluator)); break; default: dataColumn.setValue(cell.getStringCellValue(), String.class); break; } values.put(getColumnName(cell.getColumnIndex()).toUpperCase(), dataColumn); } } count = tempCount; isDataLoaded = true; //se postavim na staro vrstico ali 1 if (oldRow > 0) { absolute(oldRow); } else { first(); } result = true; } catch (Exception ex) { Logger.getLogger(ExcelDataSource.class.getName()).log(Level.SEVERE, null, ex); result = false; } } return result; }
From source file:com.ostrichemulators.semtool.poi.main.POIReader.java
License:Open Source License
public static ImportData readNonloadingSheet(Workbook workbook) { ImportData id = new ImportData(); int sheets = workbook.getNumberOfSheets(); for (int sheetnum = 0; sheetnum < sheets; sheetnum++) { Sheet sheet = workbook.getSheetAt(sheetnum); String sheetname = workbook.getSheetName(sheetnum); // we need to shoehorn the arbitrary data from a spreadsheet into our // ImportData class, which has restrictions on the data...we're going // to do it by figuring out the row with the most columns, and then // naming all the columns with A, B, C...AA, AB... // then load everything as if it was plain data // first, figure out our max number of columns int rows = sheet.getLastRowNum(); int maxcols = Integer.MIN_VALUE; for (int r = 0; r <= rows; r++) { Row row = sheet.getRow(r);// w ww. j av a2 s .c o m if (null != row) { int cols = (int) row.getLastCellNum(); if (cols > maxcols) { maxcols = cols; } } } // second, make "properties" for each column LoadingSheetData nlsd = new LoadingSheetData(sheetname, "A"); for (int c = 1; c < maxcols; c++) { nlsd.addProperty(Integer.toString(c)); } // lastly, fill the sheets for (int r = 0; r <= rows; r++) { Row row = sheet.getRow(r); if (null != row) { Map<String, Value> propmap = new HashMap<>(); int lastpropcol = row.getLastCellNum(); for (int c = 1; c <= lastpropcol; c++) { String val = getString(row.getCell(c)); if (!val.isEmpty()) { propmap.put(Integer.toString(c), VF.createLiteral(val)); } } nlsd.add(getString(row.getCell(0)), propmap); } } if (!nlsd.isEmpty()) { id.add(nlsd); } } return id; }
From source file:com.pactera.edg.am.metamanager.extractor.adapter.mapping.helper.AmCommonCodeDeleteDataGenerator.java
License:Open Source License
/** * @return HashMap<,LinkedHashMap<, ?>> */// www .j a va 2s . co m public Map<String, List<Map<String, String>>> generateDeleteData() { // ? Map<String, List<Map<String, String>>> deleteDatas = new HashMap<String, List<Map<String, String>>>( deleteDataBos.size()); // ?? Collections.reverse(deleteDataBos); for (DeleteDataBo deleteDataBo : deleteDataBos) { if (!INCLUDING_CLASSIFIERS.contains(deleteDataBo.getClassifierId())) { // ?????? continue; } Sheet sheet = wBook.getSheet(deleteDataBo.getSheetName()); // ? int maxRowNum = (deleteDataBo.getDEnd() >= deleteDataBo.getDStart()) ? deleteDataBo.getDEnd() - 1 : sheet.getLastRowNum(); List<Map<String, String>> deleteDataList = new ArrayList<Map<String, String>>(); for (int rowIndex = deleteDataBo.getDStart() - 1; rowIndex <= maxRowNum; rowIndex++) { try { Row row = sheet.getRow(rowIndex); if (row == null) continue; boolean rowIsBlank = rowIsBlank(row); if (rowIsBlank) // ?NULL,?CELL?NULL''?? continue; Map<String, int[]> pathPosition = deleteDataBo.getPathPosition(); Map<String, String> deleteData = new LinkedHashMap<String, String>(pathPosition.size()); // ??? boolean dataIsNormal = true; for (Iterator<String> classifierIdIter = pathPosition.keySet().iterator(); classifierIdIter .hasNext();) { String classifierId = classifierIdIter.next(); int[] positions = pathPosition.get(classifierId); // ?NULL''? String value = getCode(POIExcelUtil.getCellValue(positions, row)); if (value.equals("")) { // ?,?.. dataIsNormal = false; break; } deleteData.put(classifierId, value); } //if (dataIsNormal) { // ?,?? deleteDataList.add(deleteData); //} } catch (Exception e) { // ?? e.printStackTrace(); } } deleteDatas.put(deleteDataBo.getClassifierId(), deleteDataList); } return deleteDatas; }
From source file:com.pactera.edg.am.metamanager.extractor.adapter.mapping.helper.AmProductDeleteDataGenerator.java
License:Open Source License
/** * @return HashMap<,LinkedHashMap<, ?>> *//* w w w .j a v a2s. com*/ public Map<String, List<Map<String, String>>> generateDeleteData() { // ? Map<String, List<Map<String, String>>> deleteDatas = new HashMap<String, List<Map<String, String>>>( deleteDataBos.size()); // ?? Collections.reverse(deleteDataBos); for (DeleteDataBo deleteDataBo : deleteDataBos) { if (!INCLUDING_CLASSIFIERS.contains(deleteDataBo.getClassifierId())) { // ?????? continue; } Sheet sheet = wBook.getSheet(deleteDataBo.getSheetName()); // ? int maxRowNum = (deleteDataBo.getDEnd() >= deleteDataBo.getDStart()) ? deleteDataBo.getDEnd() - 1 : sheet.getLastRowNum(); List<Map<String, String>> deleteDataList = new ArrayList<Map<String, String>>(); for (int rowIndex = deleteDataBo.getDStart() - 1; rowIndex <= maxRowNum; rowIndex++) { try { Row row = sheet.getRow(rowIndex); if (row == null) continue; boolean rowIsBlank = rowIsBlank(row); if (rowIsBlank) // ?NULL,?CELL?NULL''?? continue; Map<String, int[]> pathPosition = deleteDataBo.getPathPosition(); Map<String, String> deleteData = new LinkedHashMap<String, String>(pathPosition.size()); // ??? boolean dataIsNormal = true; for (Iterator<String> classifierIdIter = pathPosition.keySet().iterator(); classifierIdIter .hasNext();) { String classifierId = classifierIdIter.next(); int[] positions = pathPosition.get(classifierId); // ?NULL''? String value = getCode(POIExcelUtil.getCellValue(positions, row)); if (value.equals("")) { // ?,?.. dataIsNormal = false; break; } deleteData.put(classifierId, value); } //if (dataIsNormal) { // ?,?? deleteDataList.add(deleteData); //} } catch (Exception e) { // ?? e.printStackTrace(); } } if ("AmProduct".equals(deleteDataBo.getClassifierId())) { if (deleteDatas.get(deleteDataBo.getClassifierId()) == null) deleteDatas.put(deleteDataBo.getClassifierId(), deleteDataList); } else { deleteDatas.put(deleteDataBo.getClassifierId(), deleteDataList); } } return deleteDatas; }
From source file:com.pactera.edg.am.metamanager.extractor.adapter.mapping.helper.AmTemplateDeleteDataGenerator.java
License:Open Source License
/** * @return HashMap<,LinkedHashMap<, ?>> *//*from w ww.j ava 2 s .com*/ public Map<String, List<Map<String, String>>> generateDeleteData() { // ? Map<String, List<Map<String, String>>> deleteDatas = new HashMap<String, List<Map<String, String>>>( deleteDataBos.size()); // ?? Collections.reverse(deleteDataBos); for (DeleteDataBo deleteDataBo : deleteDataBos) { if (!INCLUDING_CLASSIFIERS.contains(deleteDataBo.getClassifierId())) { // ?????? continue; } Sheet sheet = wBook.getSheet(deleteDataBo.getSheetName()); // ? int maxRowNum = (deleteDataBo.getDEnd() >= deleteDataBo.getDStart()) ? deleteDataBo.getDEnd() - 1 : sheet.getLastRowNum(); List<Map<String, String>> deleteDataList = new ArrayList<Map<String, String>>(); for (int rowIndex = deleteDataBo.getDStart() - 1; rowIndex <= maxRowNum; rowIndex++) { try { Row row = sheet.getRow(rowIndex); if (row == null) continue; boolean rowIsBlank = rowIsBlank(row); if (rowIsBlank) // ?NULL,?CELL?NULL''?? continue; Map<String, int[]> pathPosition = deleteDataBo.getPathPosition(); Map<String, String> deleteData = new LinkedHashMap<String, String>(pathPosition.size()); // ??? boolean dataIsNormal = true; for (Iterator<String> classifierIdIter = pathPosition.keySet().iterator(); classifierIdIter .hasNext();) { String classifierId = classifierIdIter.next(); int[] positions = pathPosition.get(classifierId); // ?NULL''? String value = getCode(POIExcelUtil.getCellValue(positions, row)); if (value.equals("")) { // ?,?.. dataIsNormal = false; break; } deleteData.put(classifierId, value); } if (dataIsNormal) { // ?,?? deleteDataList.add(deleteData); } } catch (Exception e) { // ?? e.printStackTrace(); } } deleteDatas.put(deleteDataBo.getClassifierId(), deleteDataList); } return deleteDatas; }
From source file:com.pactera.edg.am.metamanager.extractor.adapter.mapping.helper.MappingDeleteDataGenerator.java
License:Open Source License
/** * @return HashMap<,LinkedHashMap<, ?>> *///w w w. j av a2 s . co m public Map<String, List<Map<String, String>>> generateDeleteData() { // ? Map<String, List<Map<String, String>>> deleteDatas = new HashMap<String, List<Map<String, String>>>( deleteDataBos.size()); // ?? Collections.reverse(deleteDataBos); for (DeleteDataBo deleteDataBo : deleteDataBos) { if (!INCLUDING_CLASSIFIERS.contains(deleteDataBo.getClassifierId())) { // ?????? continue; } Sheet sheet = wBook.getSheet(deleteDataBo.getSheetName()); // ? int maxRowNum = (deleteDataBo.getDEnd() >= deleteDataBo.getDStart()) ? deleteDataBo.getDEnd() - 1 : sheet.getLastRowNum(); List<Map<String, String>> deleteDataList = new ArrayList<Map<String, String>>(); for (int rowIndex = deleteDataBo.getDStart() - 1; rowIndex <= maxRowNum; rowIndex++) { try { Row row = sheet.getRow(rowIndex); if (row == null) continue; boolean rowIsBlank = rowIsBlank(row); if (rowIsBlank) // ?NULL,?CELL?NULL''?? continue; Map<String, int[]> pathPosition = deleteDataBo.getPathPosition(); Map<String, String> deleteData = new LinkedHashMap<String, String>(pathPosition.size()); // ??? boolean dataIsNormal = true; for (Iterator<String> classifierIdIter = pathPosition.keySet().iterator(); classifierIdIter .hasNext();) { String classifierId = classifierIdIter.next(); int[] positions = pathPosition.get(classifierId); // ?NULL''? String value = getCode(POIExcelUtil.getCellValue(positions, row)); if (value.equals("")) { // ?,?.. dataIsNormal = false; break; } deleteData.put(classifierId, value); } //if (dataIsNormal) { // ?,?? deleteDataList.add(deleteData); //} } catch (Exception e) { // ?? e.printStackTrace(); } } deleteDatas.put(deleteDataBo.getClassifierId(), deleteDataList); } try { deleteRelObj(deleteDatas); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } return deleteDatas; }
From source file:com.qihang.winter.poi.excel.export.template.ExcelExportOfTemplateUtil.java
License:Apache License
/** * Sheet ?,?? ,??// www . ja v a2 s .c o m * * @param teplateParams * @param pojoClass * @param dataSet * @param workbook */ private void addDataToSheet(Class<?> pojoClass, Collection<?> dataSet, Sheet sheet, Workbook workbook) throws Exception { if (workbook instanceof XSSFWorkbook) { super.type = com.qihang.winter.poi.excel.entity.enmus.ExcelType.XSSF; } // ?? Map<String, Integer> titlemap = getTitleMap(sheet); Drawing patriarch = sheet.createDrawingPatriarch(); // Field[] fileds = com.qihang.winter.poi.util.PoiPublicUtil.getClassFields(pojoClass); com.qihang.winter.poi.excel.annotation.ExcelTarget etarget = pojoClass .getAnnotation(com.qihang.winter.poi.excel.annotation.ExcelTarget.class); String targetId = null; if (etarget != null) { targetId = etarget.value(); } // ?? List<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity> excelParams = new ArrayList<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity>(); getAllExcelField(null, targetId, fileds, excelParams, pojoClass, null); // ?? sortAndFilterExportField(excelParams, titlemap); short rowHeight = getRowHeight(excelParams); int index = teplateParams.getHeadingRows() + teplateParams.getHeadingStartRow(), titleHeight = index; //?,? sheet.shiftRows(teplateParams.getHeadingRows() + teplateParams.getHeadingStartRow(), sheet.getLastRowNum(), getShiftRows(dataSet, excelParams), true, true); if (excelParams.size() == 0) { return; } Iterator<?> its = dataSet.iterator(); while (its.hasNext()) { Object t = its.next(); index += createCells(patriarch, index, t, excelParams, sheet, workbook, rowHeight); } // ?? mergeCells(sheet, excelParams, titleHeight); }