Example usage for org.apache.poi.ss.usermodel Sheet getLastRowNum

List of usage examples for org.apache.poi.ss.usermodel Sheet getLastRowNum

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Sheet getLastRowNum.

Prototype

int getLastRowNum();

Source Link

Document

Gets the last row on the sheet Note: rows which had content before and were set to empty later might still be counted as rows by Excel and Apache POI, so the result of this method will include such rows and thus the returned value might be higher than expected!

Usage

From source file:net.illustrato.ctrl.CtrlCore.java

private Row copyRow(Workbook workbook, Sheet worksheet, int sourceRowNum, int destinationRowNum) {
    // Get the source / new row
    Row newRow = worksheet.getRow(destinationRowNum);
    Row sourceRow = worksheet.getRow(sourceRowNum);

    // If the row exist in destination, push down all rows by 1 else create a new row
    if (newRow != null) {
        worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
    } else {//from w w  w  .j a  v a2s .co  m
        newRow = worksheet.createRow(destinationRowNum);
    }

    // Loop through source columns to add to new row
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        // Grab a copy of the old/new cell
        Cell oldCell = sourceRow.getCell(i);
        Cell newCell = newRow.createCell(i);

        // If the old cell is null jump to next cell
        if (oldCell == null) {
            newCell = null;
            continue;
        }

        // Copy style from old cell and apply to new cell
        CellStyle newCellStyle = workbook.createCellStyle();
        newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
        newCell.setCellStyle(newCellStyle);

        // Set the cell data type
        newCell.setCellType(oldCell.getCellType());

        // Set the cell data value
        switch (oldCell.getCellType()) {
        case HSSFCell.CELL_TYPE_BLANK:
            newCell.setCellValue(oldCell.getStringCellValue());
            break;
        case HSSFCell.CELL_TYPE_FORMULA:
            newCell.setCellFormula(oldCell.getCellFormula());
            //Si tenemos que modificar la formulario lo podemos hacer como string
            //oldCell.getCellFormula().replace("A"+sourceRowNum, "A"+destinationRowNum)
            break;
        case HSSFCell.CELL_TYPE_NUMERIC:
            newCell.setCellValue(oldCell.getNumericCellValue());
            break;
        case HSSFCell.CELL_TYPE_STRING:
            newCell.setCellValue(oldCell.getRichStringCellValue());
            break;
        }
    }
    return newRow;
}

From source file:net.lizhaoweb.maker.code.java.model.excel.read.ExcelFileReader.java

License:Open Source License

private Set<FieldInformation> analysisSheet(Configuration configuration, Sheet sheet) {
    if (configuration == null) {
        throw new IllegalArgumentException("The configuration is null");
    }/*w  w w  . j  av  a2s .  co m*/
    if (sheet == null) {
        throw new IllegalArgumentException("The sheet is null");
    }

    // Sheet 
    int rowSize = sheet.getLastRowNum();
    if (rowSize < 1) {
        throw new IllegalArgumentException("The sheet rows number less than 1");
    }

    // Sheet 
    Row titleRow = sheet.getRow(0);
    if (titleRow == null) {
        throw new IllegalArgumentException("The sheet title row is not found");
    }

    // Sheet 
    int columnSize = titleRow.getLastCellNum();
    if (columnSize < 1) {
        throw new IllegalArgumentException("The sheet columns number less than 1");
    }

    // ?
    Map<Integer, FieldInformation> fieldInformationMap = new HashMap<Integer, FieldInformation>();

    // ??
    ExecutorService fieldNameExecutorService = Executors.newCachedThreadPool();
    List<Future<Map<Integer, String>>> fieldNameFutureList = new ArrayList<Future<Map<Integer, String>>>();

    // ? Sheet 
    for (int columnIndex = 0; columnIndex < columnSize; columnIndex++) {
        FieldInformation fieldInformation = new FieldInformation();
        Cell cell = titleRow.getCell(columnIndex);
        String titleContent = cell.getStringCellValue();
        fieldInformation.setTitle(titleContent);
        fieldInformation.setDescribe(titleContent);
        fieldInformation.setType("String");
        fieldInformationMap.put(columnIndex, fieldInformation);

        // ???
        Future<Map<Integer, String>> classNameFuture = fieldNameExecutorService
                .submit(new TranslateCallable(this.getTranslator(), configuration, columnIndex, titleContent));
        fieldNameFutureList.add(classNameFuture);
    }

    // ? Sheet ?
    for (int rowIndex = 1; rowIndex <= rowSize; rowIndex++) {
        Row dataRow = sheet.getRow(rowIndex);
        if (dataRow == null) {// 
            continue;
        }
        if (dataRow.getLastCellNum() < columnSize) {// ?
            continue;
        }
        for (int columnIndex = 0; columnIndex < columnSize; columnIndex++) {
            FieldInformation fieldInformation = fieldInformationMap.get(columnIndex);
            Cell cell = dataRow.getCell(columnIndex);
            CellType cellType = cell.getCellTypeEnum();
            if (CellType.BOOLEAN == cellType) {
                fieldInformation.setType("java.lang.Boolean");
            } else if (CellType.NUMERIC == cellType) {
                try {
                    Date dateValue = cell.getDateCellValue();
                    if (dateValue == null) {
                        fieldInformation.setType("java.lang.Double");
                    } else {
                        fieldInformation.setType("java.util.Date");
                    }
                } catch (Exception e) {
                    fieldInformation.setType("java.lang.Double");
                }
            }
        }
    }

    // ??
    for (Future<Map<Integer, String>> future : fieldNameFutureList) {
        try {
            Map<Integer, String> fieldNameMap = future.get();
            for (Map.Entry<Integer, String> fieldNameMapEntry : fieldNameMap.entrySet()) {
                Integer key = fieldNameMapEntry.getKey();
                String value = fieldNameMapEntry.getValue();
                fieldInformationMap.get(key).setName(StringUtil.uncapitalize(value));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    fieldNameExecutorService.shutdown();

    Set<FieldInformation> result = new HashSet<FieldInformation>(fieldInformationMap.values());
    return result;
}

From source file:net.morphbank.loadexcel.ReadExternalLinks.java

License:Open Source License

public int GetRows(Sheet sheet) {
    Sheet temp = sheet;
    return temp.getLastRowNum();
}

From source file:net.morphbank.loadexcel.SheetReader.java

License:Open Source License

public Cell[] getColumnCells(String sheetName, int fieldNum) {
    Sheet sheet = getSheet(sheetName);
    int numRows = sheet.getLastRowNum() + 1;
    Cell[] column = new Cell[numRows];
    for (int index = 0; index < numRows; index++) {
        column[index] = sheet.getRow(index).getCell(fieldNum);
    }/*from   w  w  w.  ja  v  a2 s  .c o m*/
    return column;
}

From source file:net.morphbank.loadexcel.SheetReader.java

License:Open Source License

/**
 * public method for retrieving the number of rows
 * /* w  w  w.  ja v a  2s .c o m*/
 * @param sheet
 * @return
 */
public int GetRows(String sheetName) {
    Sheet sheet = getSheet(sheetName);
    if (sheet == null)
        return 0;
    return sheet.getLastRowNum();
}

From source file:net.morphbank.mbsvc3.mapsheet.MapSheetImage.java

License:Open Source License

public String[][] getUserProperties() {
    if (this.image instanceof XlsFieldMapper) {
        Sheet links = ((XlsFieldMapper) this.image).getLinks();
        int cols = links.getRow(0).getLastCellNum();
        int rows = links.getLastRowNum();
        userProperties = new String[rows + 1][cols + 1];

        int i, j;
        i = j = 0;/*  w  w w. jav a2 s.  c  o  m*/
        for (Row row : links) {
            j = 0;
            for (Cell cell : row) {
                userProperties[i][j] = cell.getStringCellValue();
                j++;
            }
            i++;
        }
        return userProperties;
    }
    return null;
}

From source file:net.morphbank.mbsvc3.mapsheet.MapSheetSpecimen.java

License:Open Source License

public String[][] getUserProperties() {
    if (this.specimen instanceof XlsFieldMapper) {
        Sheet links = ((XlsFieldMapper) this.specimen).getLinks();
        int cols = links.getRow(0).getLastCellNum();
        if (cols != 4) {
            MorphbankConfig.SYSTEM_LOGGER.info("Wrong number of colums in Excel spreadsheet.");
            return null;
        }/*from  w  ww  .j ava  2 s.c  o  m*/

        cols = 4;
        int rows = links.getLastRowNum();
        userProperties = new String[rows + 1][cols + 1];
        int i, j;
        i = j = 0;
        for (Row row : links) {
            j = 0;
            for (Cell cell : row) {
                userProperties[i][j] = cell.getStringCellValue();
                j++;
            }
            i++;
        }

        return userProperties;
    }
    return null;
}

From source file:net.morphbank.mbsvc3.mapsheet.MapSheetView.java

License:Open Source License

public String[][] getUserProperties() {
    if (this.view instanceof XlsFieldMapper) {
        Sheet links = ((XlsFieldMapper) this.view).getLinks();
        int cols = links.getRow(0).getLastCellNum();
        int rows = links.getLastRowNum();
        userProperties = new String[rows + 1][cols + 1];
        int i = 0;
        int j = 0;
        for (Row row : links) {
            j = 0;//  www  .j  a v  a  2  s  .c om
            for (Cell cell : row) {
                userProperties[i][j] = cell.getStringCellValue();
                j++;
            }
            i++;
        }
        return userProperties;
    }
    return null;
}

From source file:net.sf.dvstar.swirl.desktopdbf.data.ExcelTableModel.java

License:Open Source License

/**
 * Called to convert the contents of the currently opened workbook into
 * a CSV file./*from  w ww  . jav  a  2s. c  om*/
 */
private void convertToCSV() {
    Sheet sheet = null;
    Row row = null;
    int lastRowNum = 0;
    ArrayList<ArrayList> csvSheetData = null;
    this.bookData = new ArrayList<ArrayList>();
    maxRowWidths = new ArrayList<Integer>();
    this.maxColumnWidths = new ArrayList<Integer>();

    //        System.out.println("Converting files contents to CSV format.");

    // Discover how many sheets there are in the workbook....
    int numSheets = this.workbook.getNumberOfSheets();

    // and then iterate through them.
    for (int i = 0; i < 1 /*numSheets*/; i++) { // !!!! Only ONE Sheet !!!!

        maxRowWidth = 0;
        // Get a reference to a sheet and check to see if it contains
        // any rows.
        sheet = this.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
            // for inclusion in the resylting CSV file.
            lastRowNum = sheet.getLastRowNum();
            csvSheetData = new ArrayList<ArrayList>();
            for (int j = 0; j <= lastRowNum; j++) {
                row = sheet.getRow(j);
                csvSheetData.add(this.rowToCSV(row));
            }
            this.getBookData().add(csvSheetData);
            this.maxRowWidths.add(new Integer(getMaxRowWidth()));
        }
    }
}

From source file:net.sf.excelutils.ExcelUtils.java

License:Apache License

/**
 * parse Excel Template File//from w  w w.  j a  va  2  s  .  com
 * 
 * @param context datasource
 * @param sheet Workbook sheet
 */
public static void parseSheet(Object context, Workbook wb, Sheet sheet) throws ExcelException {
    try {
        ExcelParser.parse(context, wb, sheet, sheet.getFirstRowNum(), sheet.getLastRowNum());
        try {
            // remove the last #page
            int breaks[] = sheet.getRowBreaks();
            if (breaks.length > 0) {
                sheet.removeRowBreak(breaks[breaks.length - 1]);
            }
        } catch (Exception ne) {
        }
    } catch (Exception e) {
        throw new ExcelException("parseSheet error: ", e);
    } finally {
        ExcelUtils.context.set(null);
    }
}