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

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

Introduction

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

Prototype

int getPhysicalNumberOfRows();

Source Link

Document

Returns the number of physically defined rows (NOT the number of rows in the sheet)

Usage

From source file:fi.hsl.parkandride.itest.AbstractReportingITest.java

License:EUPL

protected List<String> findRowWithColumn(Sheet sheet, int columnNumber, String content) {
    for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
        final Row row = sheet.getRow(i);
        final List<String> dataFromRow = getDataFromRow(row);
        if (dataFromRow.contains(content)) {
            return dataFromRow;
        }/*from w  w w . j  a  va2s . c  om*/
    }
    throw new NoSuchElementException(
            String.format("Row with column at %d: <%s> not found", columnNumber, content));
}

From source file:fi.hsl.parkandride.itest.AbstractReportingITest.java

License:EUPL

void checkSheetContents(AutoCloseableSoftAssertions softly, Workbook workbook, int sheetIndex,
        List<String>... rows) {
    Sheet sheet = workbook.getSheetAt(sheetIndex);
    softly.assertThat(sheet.getPhysicalNumberOfRows()).as("Number of rows").isEqualTo(rows.length);
    for (int i = 0; i < rows.length; i++) {
        final List<String> dataFromRow = getDataFromRow(sheet, i);
        softly.assertThat(dataFromRow).as("Row index %d", i).containsExactlyElementsOf(rows[i]);
    }/*  ww  w .  j  a v a2  s  .co  m*/
}

From source file:fi.hsl.parkandride.itest.HubsAndFacilitiesReportITest.java

License:EUPL

private void checkHubsAndFacilities_facilityInfo(Workbook workbook) {
    final Sheet facilities = workbook.getSheetAt(1);
    assertThat(facilities.getPhysicalNumberOfRows()).isEqualTo(2);
    final List<String> facilityInfo = getDataFromRow(facilities, 1);
    assertThat(facilityInfo).containsSequence(facility1.name.fi, String.join(", ", facility1.aliases),
            hub.name.fi, operator1.name.fi, translationService.translate(facility1.status),
            facility1.statusDescription.fi,
            String.format(Locale.ENGLISH, "%.4f", facility1.location.getCentroid().getX()),
            String.format(Locale.ENGLISH, "%.4f", facility1.location.getCentroid().getY()), "", "08:00 - 18:00",
            "08:00 - 18:00", facility1.openingHours.info.fi,
            "" + facility1.builtCapacity.entrySet().stream()
                    .filter(entry -> asList(motorCapacities).contains(entry.getKey()))
                    .mapToInt(entry -> entry.getValue()).sum(),
            "" + facility1.builtCapacity.entrySet().stream()
                    .filter(entry -> asList(bicycleCapacities).contains(entry.getKey()))
                    .mapToInt(entry -> entry.getValue()).sum(),
            "" + facility1.builtCapacity.getOrDefault(CAR, 0),
            "" + facility1.builtCapacity.getOrDefault(DISABLED, 0),
            "" + facility1.builtCapacity.getOrDefault(ELECTRIC_CAR, 0),
            "" + facility1.builtCapacity.getOrDefault(MOTORCYCLE, 0),
            "" + facility1.builtCapacity.getOrDefault(BICYCLE, 0),
            "" + facility1.builtCapacity.getOrDefault(BICYCLE_SECURE_SPACE, 0));
}

From source file:fi.hsl.parkandride.itest.HubsAndFacilitiesReportITest.java

License:EUPL

private void checkHubsAndFacilities_hubInfo(Workbook workbook) {
    final Sheet hubs = workbook.getSheetAt(0);
    assertThat(hubs.getPhysicalNumberOfRows()).isEqualTo(2);

    final List<String> hubInfo = getDataFromRow(hubs, 1);
    assertThat(hubInfo).containsExactly(hub.name.fi,
            String.join(", ",
                    toArray(hub.address.streetAddress.fi, hub.address.postalCode, hub.address.city.fi)),
            String.format(Locale.ENGLISH, "%.4f", hub.location.getX()),
            String.format(Locale.ENGLISH, "%.4f", hub.location.getY()),
            "" + facility1.builtCapacity.entrySet().stream()
                    .filter(entry -> asList(motorCapacities).contains(entry.getKey()))
                    .mapToInt(entry -> entry.getValue()).sum(),
            "" + facility1.builtCapacity.entrySet().stream()
                    .filter(entry -> asList(bicycleCapacities).contains(entry.getKey()))
                    .mapToInt(entry -> entry.getValue()).sum(),
            "" + facility1.builtCapacity.getOrDefault(CAR, 0),
            "" + facility1.builtCapacity.getOrDefault(DISABLED, 0),
            "" + facility1.builtCapacity.getOrDefault(ELECTRIC_CAR, 0),
            "" + facility1.builtCapacity.getOrDefault(MOTORCYCLE, 0),
            "" + facility1.builtCapacity.getOrDefault(BICYCLE, 0),
            "" + facility1.builtCapacity.getOrDefault(BICYCLE_SECURE_SPACE, 0), facility1.name.fi);
}

From source file:fi.hsl.parkandride.itest.RequestLogITest.java

License:EUPL

@Test
public void report_RequestLog_emptyReport() {
    generateDummyRequestLog();/*  ww w. ja va2 s.c  om*/

    // Defaults to DAY interval, the month is empty so report should be empty
    final ReportParameters params = baseParams(BASE_DATE_TIME.minusMonths(2).toLocalDate());
    final Response whenPostingToReportUrl = postToReportUrl(params, REQUEST_LOG, adminUser);
    // If this succeeds, the response was a valid excel file
    withWorkbook(whenPostingToReportUrl, workbook -> {
        assertThat(workbook.getSheetName(0)).isEqualTo("Rajapintakutsut");
        assertThat(workbook.getSheetName(1)).isEqualTo("Selite");

        final Sheet sheet = workbook.getSheetAt(0);
        assertThat(getDataFromRow(sheet, 0)).containsExactly("Pivmr", "Lhde", "Polku",
                "Kutsujen mr");
        assertThat(sheet.getPhysicalNumberOfRows()).isEqualTo(1);
    });
}

From source file:fi.hsl.parkandride.itest.RequestLogITest.java

License:EUPL

@Test
public void report_RequestLog_nonExistentUrl_andUrlOutsideApi() {
    withDate(BASE_DATE_TIME, () -> {/*from   w  w  w .j  a v  a 2 s.  c o m*/
        when().get(UrlSchema.API + "/foobarbazqux");
        when().get(UrlSchema.DOCS);
    });
    batchingRequestLogService.updateRequestLogs();

    // Defaults to DAY interval, the month is empty so report should be empty
    final ReportParameters params = baseParams(BASE_DATE_TIME.toLocalDate());
    final Response whenPostingToReportUrl = postToReportUrl(params, REQUEST_LOG, adminUser);
    // If this succeeds, the response was a valid excel file
    withWorkbook(whenPostingToReportUrl, workbook -> {
        // No requests logged
        final Sheet sheet = workbook.getSheetAt(0);
        assertThat(sheet.getPhysicalNumberOfRows()).isEqualTo(1);
    });
}

From source file:fsart.diffTools.converter.ToCSV.java

License:Apache License

/**
 * Called to convert the contents of the currently opened workbook into
 * a CSV file.// ww  w  .  j ava  2 s.c o m
 */
public void convertToCSV() {
    Sheet sheet = null;
    Row row = null;
    int lastRowNum = 0;
    this.csvData = new ArrayList<ArrayList<String>>();

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

    // Discover how many sheets there are by the workbook....
    int numSheets = this.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 = 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 by the resylting CSV file.
            lastRowNum = sheet.getLastRowNum();
            for (int j = 0; j <= lastRowNum; j++) {
                row = sheet.getRow(j);
                this.rowToCSV(row);
            }
        }
    }
}

From source file:fsart.diffTools.converter.ToCSV.java

License:Apache License

public void convertToCSV(String sheetName) {
    Sheet sheet = null;
    Row row = null;/*from w ww.  j a  v  a 2  s . co  m*/
    int lastRowNum = 0;
    this.csvData = new ArrayList<ArrayList<String>>();

    int numSheetsToConvert = this.workbook.getSheetIndex(sheetName);

    // Get a reference to a sheet and check to see if it contains
    // any rows.
    if (sheetName != null && !sheetName.equals("")) {
        sheet = this.workbook.getSheet(sheetName);
    }
    if (sheet == null) {
        sheet = this.workbook.getSheetAt(0);
    }
    if (sheet != null && 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 by the resylting CSV file.
        lastRowNum = sheet.getLastRowNum();
        for (int j = 0; j <= lastRowNum; j++) {
            row = sheet.getRow(j);
            this.rowToCSV(row);
        }
    }
}

From source file:gov.nih.nci.evs.app.neopl.ExcelToCSV.java

License:Open Source License

private void convertToCSV() {
    Sheet sheet = null;
    Row row = null;//ww  w  .  j av  a  2  s  . c o m
    int lastRowNum = 0;
    this.csvData = new ArrayList<ArrayList<String>>();

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

    int numSheets = this.workbook.getNumberOfSheets();
    for (int i = 0; i < numSheets; i++) {
        sheet = this.workbook.getSheetAt(i);
        if (sheet.getPhysicalNumberOfRows() > 0) {
            lastRowNum = sheet.getLastRowNum();
            /*
            for(int j = 0; j <= lastRowNum; j++) {
            row = sheet.getRow(j);
            this.rowToCSV(row);
            }
            */
            for (int j = 1; j <= lastRowNum; j++) {
                row = sheet.getRow(j);
                this.rowToCSV(row);
            }
        }
        //sheet.createFreezePane(0,1); // this will freeze the header row
    }

}

From source file:gtu._work.ui.SqlCreaterUI.java

License:Open Source License

private void executeBtnPreformed() {
    try {/*  ww w .j  a v a 2  s. co m*/
        logArea.setText("");
        File srcFile = JCommonUtil.filePathCheck(excelFilePathText.getText(), "?", false);
        if (srcFile == null) {
            return;
        }
        if (!srcFile.getName().endsWith(".xlsx")) {
            JCommonUtil._jOptionPane_showMessageDialog_error("excel");
            return;
        }
        if (StringUtils.isBlank(sqlArea.getText())) {
            return;
        }
        File saveFile = JCommonUtil._jFileChooser_selectFileOnly_saveFile();
        if (saveFile == null) {
            JCommonUtil._jOptionPane_showMessageDialog_error("?");
            return;
        }

        String sqlText = sqlArea.getText();

        StringBuffer sb = new StringBuffer();
        Map<Integer, String> refMap = new HashMap<Integer, String>();
        Pattern sqlPattern = Pattern.compile("\\$\\{(\\w+)\\}", Pattern.MULTILINE);
        Matcher matcher = sqlPattern.matcher(sqlText);
        while (matcher.find()) {
            String val = StringUtils.trim(matcher.group(1)).toUpperCase();
            refMap.put(ExcelUtil.cellEnglishToPos(val), val);
            matcher.appendReplacement(sb, "\\$\\{" + val + "\\}");
        }
        matcher.appendTail(sb);
        appendLog(refMap.toString());

        sqlText = sb.toString();
        sqlArea.setText(sqlText);

        Configuration cfg = new Configuration();
        StringTemplateLoader stringTemplatge = new StringTemplateLoader();
        stringTemplatge.putTemplate("aaa", sqlText);
        cfg.setTemplateLoader(stringTemplatge);
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate("aaa");

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(saveFile), "utf8"));

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(bis);
        Sheet sheet = xssfWorkbook.getSheetAt(0);
        for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
            Row row = sheet.getRow(j);
            if (row == null) {
                continue;
            }
            Map<String, Object> root = new HashMap<String, Object>();
            for (int index : refMap.keySet()) {
                root.put(refMap.get(index), formatCellType(row.getCell(index)));
            }
            appendLog(root.toString());

            StringWriter out = new StringWriter();
            temp.process(root, out);
            out.flush();
            String writeStr = out.getBuffer().toString();
            appendLog(writeStr);

            writer.write(writeStr);
            writer.newLine();
        }
        bis.close();

        writer.flush();
        writer.close();

        JCommonUtil._jOptionPane_showMessageDialog_info("? : \n" + saveFile);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}