Example usage for org.apache.poi.ss.usermodel Row getPhysicalNumberOfCells

List of usage examples for org.apache.poi.ss.usermodel Row getPhysicalNumberOfCells

Introduction

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

Prototype

int getPhysicalNumberOfCells();

Source Link

Document

Gets the number of defined cells (NOT number of cells in the actual row!).

Usage

From source file:monthly.organizer.MonthlyOrganizer.java

@Override
public void start(Stage primaryStage) {
    wbo = new XSSFWorkbook();
    try {/*from   ww w  .ja  v a  2  s . co  m*/
        Button merge = new Button("merge");
        Button folder = new Button("Choose Folder");
        Button file = new Button("Choose Save File");
        Label fileLoc = new Label("Not Selected");
        Label folderLoc = new Label("Not Selected");
        folder.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent arg0) {
                DirectoryChooser folderChooser = new DirectoryChooser();
                folderChooser.setTitle("Choose Folder Containing Files");
                selectedFolder = folderChooser.showDialog(primaryStage);
                //folderLoc.setText(selectedFolder.getName());
                if (null == selectedFolder)
                    folderLoc.setText("No Folder Selected");
                else
                    folderLoc.setText(selectedFolder.getName());
            }

        });

        file.setOnAction(new EventHandler<ActionEvent>() {

            @SuppressWarnings("deprecation")
            @Override
            public void handle(ActionEvent arg0) {

                FileChooser fileSaver = new FileChooser();
                fileSaver.setTitle("Create Save File");
                fileSaver.getExtensionFilters().addAll(new ExtensionFilter(
                        "ExceBeaconController bc = new BeaconController();ll Files", "*.xlsx"));

                outputFile = fileSaver.showSaveDialog(primaryStage);
                //outputFile = new File("/home/camen/Desktop" + "/Final_Books" + LocalDate.now() + ".xlsx");
                if (null == outputFile)
                    fileLoc.setText("No File Selected");
                else
                    fileLoc.setText(outputFile.getName());
            }
        });

        merge.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                try {
                    outputStream = new FileOutputStream(outputFile);
                } catch (FileNotFoundException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
                try (

                        Stream<Path> paths = Files.walk(Paths.get(selectedFolder.getPath()))) {
                    paths.forEach(filePath -> {
                        if (Files.isRegularFile(filePath)
                                && !filePath.toString().equals(selectedFolder.toPath().toString())) {
                            //System.out.println(filePath);
                            fileNum++;
                            FileInputStream inputStream;

                            try {
                                inputStream = new FileInputStream(filePath.toString());

                                wb = new XSSFWorkbook(inputStream);

                                CreationHelper createHelper = wbo.getCreationHelper();
                                Sheet sheetOut = wbo.createSheet(filePath.getFileName().toString());
                                //add client name to beacon controller
                                clients.add(new Client(filePath.getFileName().toString()));
                                clientNum++;
                                //System.out.println(clientNum + "");
                                Row rowOut = sheetOut.createRow(0);
                                Cell cellOut;
                                cellOut = rowOut.createCell(0);
                                cellOut.setCellValue(createHelper.createRichTextString("Week"));
                                cellOut = rowOut.createCell(1);
                                cellOut.setCellValue(createHelper.createRichTextString("Behavior/Decel"));
                                cellOut = rowOut.createCell(2);
                                cellOut.setCellValue(createHelper.createRichTextString("Data Input Total"));
                                cellOut = rowOut.createCell(3);
                                cellOut.setCellValue(createHelper.createRichTextString("Measurment Type"));
                                cellOut = rowOut.createCell(4);
                                cellOut.setCellValue(createHelper.createRichTextString("Measurment Unit"));
                                cellOut = rowOut.createCell(5);
                                cellOut.setCellValue(
                                        createHelper.createRichTextString("Total Time for Week (Mins)"));
                                int rowCount = 1;
                                for (int k = 0; k < wb.getNumberOfSheets(); k++) {
                                    Sheet sheet = wb.getSheetAt(k);
                                    double weekTotal = 0;
                                    double timeTotal = 0;
                                    boolean replace = false;
                                    String decelName = null;
                                    String replaceName = null;
                                    Random rand = null;
                                    int n = 0;
                                    String measType = null;
                                    String measUnit = null;
                                    String replacedName = null;
                                    String replacedNameOld = null;
                                    LocalDateTime date = null;
                                    int weekNum = -1;
                                    int lastWeek = -1;
                                    int year = 0;
                                    int rows = sheet.getPhysicalNumberOfRows();
                                    //System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows
                                    //+ " row(s).");
                                    for (int r = 0; r < rows; r++) {

                                        Row row = sheet.getRow(r);
                                        if (row == null) {
                                            continue;
                                        }

                                        int cells = row.getPhysicalNumberOfCells();
                                        //System.out.println("\nROW " + row.getRowNum() + " has " + cells
                                        //+ " cell(s).");
                                        for (int c = 0; c < cells; c++) {
                                            Cell cell = row.getCell(c);
                                            if (cell == null) {
                                                //c++;
                                                cells++;
                                            } else {
                                                switch (cell.getCellTypeEnum()) {
                                                case STRING:
                                                    if (r == 0 && cell.getRichStringCellValue().getString()
                                                            .contains("Replacement"))
                                                        replace = true;
                                                    if (r == 0 && replace == true && c == 1) {
                                                        replaceName = cell.getRichStringCellValue().getString();
                                                        rand = new Random();
                                                        n = rand.nextInt(20) + 1;
                                                    } else if (r == 0 && replace == false && c == 1)
                                                        decelName = cell.getRichStringCellValue().getString();
                                                    else if (r == 0 && replace == true && c == 2)
                                                        replacedName = cell.getRichStringCellValue()
                                                                .getString();
                                                    if (r == 1 && c == 0)
                                                        measType = cell.getRichStringCellValue().getString();
                                                    if (r == 1 && c == 1)
                                                        measUnit = cell.getRichStringCellValue().getString();
                                                    //System.out.println(cell.getRichStringCellValue().getString());
                                                    break;
                                                case NUMERIC:
                                                    if (DateUtil.isCellDateFormatted(cell)) {
                                                        date = cell.getDateCellValue().toInstant()
                                                                .atZone(ZoneId.systemDefault()).toLocalDate()
                                                                .atTime(LocalTime.NOON);
                                                        year = date.getYear();
                                                        weekNum = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
                                                        if (lastWeek == -1)
                                                            lastWeek = weekNum;
                                                        c++;
                                                        cell = row.getCell(c);
                                                        weekTotal += cell.getNumericCellValue();
                                                        c++;
                                                        //cell = row.getCell(c);
                                                        //timeTotal += cell.getNumericCellValue();
                                                    } else {
                                                        System.out.println(cell.getNumericCellValue());

                                                    }
                                                    break;
                                                case BOOLEAN:
                                                    //System.out.println(cell.getBooleanCellValue());
                                                    break;
                                                case FORMULA:
                                                    //System.out.println(cell.getCellFormula());
                                                    break;
                                                case BLANK:
                                                    //System.out.println();
                                                    break;
                                                default:
                                                    //System.out.println();
                                                }

                                                //System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE="
                                                //+ value);
                                            }
                                        } //System.out.println(lastWeek + " " + weekNum + " " + weekTotal);
                                        if (lastWeek != weekNum && lastWeek != -1) {

                                            //weekCount ++;
                                            rowOut = sheetOut.createRow(rowCount);
                                            Cell cell = rowOut.createCell(0);
                                            cell.setCellValue(createHelper.createRichTextString(date.getMonth()
                                                    + ", Week " + weekNum + " of Year: " + date.getYear()));

                                            //create random number to choose behavior

                                            cell = rowOut.createCell(1);
                                            if (replace == true) {
                                                cell.setCellValue(
                                                        createHelper.createRichTextString(replaceName));
                                                //client.addValue((((date.getYear() - 2014)*53) + weekNum), weekTotal, Arrays.binarySearch(Client.behaviors, replaceName));

                                                //addvalue to random behavior chosen for the week
                                                clients.get(clientNum).addValue(
                                                        (((date.getYear() - 2014) * 53) + weekNum), weekTotal,
                                                        n);
                                                //System.out.println((((date.getYear() - 2014)*53) + weekNum) + " " + weekTotal + " " + Client.behaviors[n] + " " + clients.get(clientNum).getName());
                                            }

                                            else
                                                cell.setCellValue(createHelper.createRichTextString(decelName));
                                            cell = rowOut.createCell(2);
                                            cell.setCellValue(weekTotal);
                                            cell = rowOut.createCell(3);
                                            cell.setCellValue(createHelper.createRichTextString(measType));
                                            cell = rowOut.createCell(4);
                                            cell.setCellValue(createHelper.createRichTextString(measUnit));
                                            //System.out.println(months[wR[weekNum].month-1] + " week " + (wR[weekNum].monthWeek) + ", " + (year+1900) + ": " + weekTotal + " Measurment Type: " + measType + " Measument Unit: " + measUnit);
                                            weekTotal = 0;
                                            lastWeek = weekNum;
                                            //newWeek = false;
                                            rowCount++;
                                        }

                                    }
                                    //if(replace == true)
                                    //System.out.println(replaceName + " for " + replacedName);
                                    //else
                                    //System.out.println(decelName);

                                }
                                //controller.addClient(clients.get(clientNum));
                                //controller.getClients().forEach((names) -> {
                                //System.out.println(names.getName());
                                //});

                                wb.close();

                                inputStream.close();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    });
                    wbo.write(outputStream);
                    wbo.close();
                    outputStream.close();
                    final FXMLLoader loader = new FXMLLoader(getClass().getResource("beacon.fxml"));
                    final Stage stage = new Stage(StageStyle.DECORATED);
                    stage.setScene(new Scene((Pane) loader.load()));
                    final BeaconController controller = loader.<BeaconController>getController();
                    controller.addClients(clients);
                    controller.setFields(true);
                    stage.showAndWait();
                    //getHostServices().showDocument(outputFile.toURI().toURL().toExternalForm());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

        });

        VBox root = new VBox();
        root.setId("pane");
        folder.setId("button");
        file.setId("button");
        merge.setId("button");
        root.getStylesheets().addAll(this.getClass().getResource("buttonStyle.css").toExternalForm());
        root.setPadding(new Insets(180, 200, 30, 200));
        root.setAlignment(Pos.BASELINE_CENTER);
        root.getChildren().addAll(folder, folderLoc, file, fileLoc, merge);
        root.setSpacing(10);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.squirrel_sql.plugins.dataimport.importer.excel.ExcelFileImporter.java

License:Open Source License

public String[][] getPreview(int noOfLines) throws IOException {
    String[][] data = null;//w  w  w.j a  v a 2 s  .c  om
    Workbook wb = null;
    Sheet sht = null;
    try {
        wb = WorkbookFactory.create(importFile);
        sht = getSheet(wb);
    } catch (InvalidFormatException fe) {
        throw new IOException(fe.toString());
    }

    int y = 0;
    int x = 0;
    int maxLines = (noOfLines < sht.getPhysicalNumberOfRows()) ? noOfLines : sht.getPhysicalNumberOfRows();
    Row row = sht.getRow(0);
    data = new String[maxLines][row.getPhysicalNumberOfCells()];

    for (y = 0; y < maxLines; y++) {
        for (x = 0; x < row.getPhysicalNumberOfCells(); x++) {
            data[y][x] = row.getCell(x).toString();
        }
    }
    return data;
}

From source file:nl.meine.scouting.solparser.writer.ExcelWriterTest.java

License:Open Source License

@Test
public void testUpdates() throws Throwable {
    instance.write();//ww w .j a v  a2 s .  c  om
    instance.postprocess(sorter.getOrder());
    instance.closeWriter();

    File twopersons = ParserTest.getResource("twopersons_update.csv");
    Parser p = new Parser(twopersons, SorterFactory.createSorter(SorterFactory.SORTER_ONLYALL));

    p.read(true);
    persons = p.getAllPersons();
    sortedPersons = p.getSortedPersons();

    instance = new ExcelWriter("dummy.xls");
    instance.setAllPersons(allPersons);
    instance.setSortedPersons(sortedPersons);
    instance.init();
    instance.write();
    instance.postprocess(sorter.getOrder());
    instance.closeWriter();

    Workbook wb = instance.workbook;
    Sheet s = wb.getSheetAt(0);
    assertEquals(4, s.getPhysicalNumberOfRows());
    // lidnummer: 161616 is nieuw
    // lidnummer 16: straat geupdatet
    // lidnummer 1616 alles gelijk
    for (int i = 1; i < s.getPhysicalNumberOfRows(); i++) {
        Row r = s.getRow(i);
        Cell lidnummer = r.getCell(0);
        if (lidnummer.getStringCellValue().equals("16")) {
            Cell straat = r.getCell(6);
            Cell huisnummer = r.getCell(7);
            assertEquals(ExcelWriter.COLOR_UPDATED, straat.getCellStyle().getFillForegroundColor());
            assertEquals(ExcelWriter.COLOR_UPDATED, huisnummer.getCellStyle().getFillForegroundColor());
        } else if (lidnummer.getStringCellValue().equals("1616")) {
            for (int j = 0; j < r.getPhysicalNumberOfCells(); j++) {
                Cell c = r.getCell(j);
                assertEquals(IndexedColors.AUTOMATIC.index, c.getCellStyle().getFillForegroundColor());
            }
        } else if (lidnummer.getStringCellValue().equals("161616")) {
            for (int j = 0; j < r.getPhysicalNumberOfCells(); j++) {
                Cell c = r.getCell(j);
                assertEquals(ExcelWriter.COLOR_NEW, c.getCellStyle().getFillForegroundColor());
            }
        }
    }
}

From source file:org.bdxjug.api.infrastructure.sheet.xlsx.XlsxSheet.java

License:Apache License

@Override
public <T> List<T> readLines(Function<String[], T> lineMapping, String sheetName) {
    List<T> results = new ArrayList<>();
    org.apache.poi.ss.usermodel.Sheet worksheet = sheetByName(sheetName)
            .orElseThrow(IllegalStateException::new);
    int nbRows = worksheet.getPhysicalNumberOfRows();
    for (int i = 1; i < nbRows; i++) {
        Row row = worksheet.getRow(i);
        if (!isRowEmpty(row)) {
            int nbCells = row.getPhysicalNumberOfCells();
            String[] values = new String[nbCells];
            for (int j = 0; j < nbCells; j++) {
                Cell cell = row.getCell(j);
                if (isEmpty(cell)) {
                    values[j] = "";
                } else if (isDate(cell)) {
                    values[j] = getDateValue(cell);
                } else if (isFormula(cell) || isNumeric(cell)) {
                    values[j] = getNumericValue(cell).toPlainString();
                } else {
                    values[j] = cell.toString().trim();
                }/*from w  w w .j av a2s .  c om*/
            }
            results.add(lineMapping.apply(values));
        }
    }
    return results;
}

From source file:org.corpus_tools.peppermodules.spreadsheet.Spreadsheet2SaltMapper.java

License:Apache License

/**
 * get the primary text tiers and their annotations of the given document
 * //from  w  w  w. ja va  2 s.c o m
 * @param workbook
 * @param timeline
 */
private void getPrimTextTiers(Workbook workbook, STimeline timeline) {
    // get all primary text tiers
    String primaryTextTier = getProps().getPrimaryText();
    // seperate string of primary text tiers into list by commas
    List<String> primaryTextTierList = Arrays.asList(primaryTextTier.split("\\s*,\\s*"));

    TreeSet<String> annosWithoutPrim = new TreeSet<>();

    if (workbook != null) {
        // get corpus sheet
        Sheet corpusSheet;
        // default ("Tabelle1"/ first sheet)
        if (getProps().getCorpusSheet().equals("Tabelle1")) {
            corpusSheet = workbook.getSheetAt(0);
        } else {
            // get corpus sheet by name
            corpusSheet = workbook.getSheet(getProps().getCorpusSheet());
        }
        // end of the excel file
        int lastRow = corpusSheet.getLastRowNum();
        mapLinenumber2STimeline(lastRow, timeline);

        if (corpusSheet != null) {

            // row with all names of the annotation tiers (first row)
            Row headerRow = corpusSheet.getRow(0);
            // List for each primary text and its annotations
            HashMap<Integer, Integer> annoPrimRelations = new HashMap<>();

            List<Integer> primTextPos = new ArrayList<Integer>();
            if (headerRow != null) {

                // iterate through all tiers and save tiers (column number)
                // that hold the primary data

                int currColumn = 0;

                List<String> emptyColumnList = new ArrayList<>();
                while (currColumn < headerRow.getPhysicalNumberOfCells()) {
                    if (headerRow.getCell(currColumn) == null
                            || headerRow.getCell(currColumn).toString().isEmpty()) {
                        String emptyColumn = CellReference.convertNumToColString(currColumn);
                        emptyColumnList.add(emptyColumn);
                        currColumn++;
                        continue;
                    } else {
                        if (!emptyColumnList.isEmpty()) {
                            for (String emptyColumn : emptyColumnList) {
                                SpreadsheetImporter.logger.warn("Column \"" + emptyColumn + "\" in document \""
                                        + getResourceURI().lastSegment() + "\" has no name.");
                            }
                            emptyColumnList = new ArrayList<>();
                        }

                        boolean primWasFound = false;

                        String tierName = headerRow.getCell(currColumn).toString();
                        if (primaryTextTierList.contains(tierName)) {
                            // current tier contains primary text
                            // save all indexes of tier containing primary
                            // text
                            primTextPos.add(currColumn);
                            primWasFound = true;
                        } else {
                            // current tier contains (other) annotations
                            if (tierName.matches(".+\\[.+\\]") || getProps().getAnnoPrimRel() != null
                                    || getProps().getShortAnnoPrimRel() != null) {

                                if (tierName.matches(".+\\[.+\\]")) {
                                    // the belonging primary text was set by
                                    // the annotator
                                    String primTier = tierName.split("\\[")[1].replace("]", "");
                                    setAnnotationPrimCouple(primTier, annoPrimRelations, currColumn, headerRow);
                                    primWasFound = true;
                                }

                                String primOfAnnoFromConfig = getPrimOfAnnoPrimRel(tierName.split("\\[")[0]);

                                if (primOfAnnoFromConfig != null) {
                                    // current tier is an annotation and the
                                    // belonging primary text was set by
                                    // property
                                    setAnnotationPrimCouple(primOfAnnoFromConfig, annoPrimRelations, currColumn,
                                            headerRow);
                                    primWasFound = true;
                                }

                            } else if (primaryTextTierList.size() == 1 && getProps().getAnnoPrimRel() == null
                                    && getProps().getShortAnnoPrimRel() == null) {
                                // There is only one primary text so we can
                                // safely assume this is the one
                                // the annotation is connected to.
                                setAnnotationPrimCouple(primaryTextTierList.get(0), annoPrimRelations,
                                        currColumn, headerRow);
                                primWasFound = true;
                            }
                        }
                        if (!primWasFound) {
                            annosWithoutPrim.add(tierName);
                        }
                        currColumn++;
                    }
                }
            }

            final Map<String, SLayer> layerTierCouples = getLayerTierCouples();
            Table<Integer, Integer, CellRangeAddress> mergedCells = null;
            if (corpusSheet.getNumMergedRegions() > 0) {
                mergedCells = calculateMergedCellIndex(corpusSheet.getMergedRegions());
            }
            int progressTotalNumberOfColumns = 0;
            if (!primTextPos.isEmpty()) {
                progressTotalNumberOfColumns = setPrimText(corpusSheet, primTextPos, annoPrimRelations,
                        headerRow, mergedCells, layerTierCouples);
            } else {
                SpreadsheetImporter.logger
                        .warn("No primary text for the document \"" + getResourceURI().lastSegment()
                                + "\" found. Please check the spelling of your properties.");
            }

            setAnnotations(annoPrimRelations, corpusSheet, mergedCells, layerTierCouples,
                    progressTotalNumberOfColumns);
        }
        if (getProps().getMetaAnnotation()) {
            setDocMetaData(workbook);
        }

        // report if any column was not included
        if (!annosWithoutPrim.isEmpty()) {
            SpreadsheetImporter.logger.warn(
                    "No primary text column found for columns\n- {}\nin document {}. This means these columns are not included in the conversion!",
                    Joiner.on("\n- ").join(annosWithoutPrim), getResourceURI().toFileString());
        }
    }
}

From source file:org.deidentifier.arx.gui.view.impl.wizard.ImportWizardPageExcel.java

License:Open Source License

/**
 * Reads in preview data//  ww  w  . j  ava2  s  . c o  m
 *
 * This goes through up to {@link ImportWizardModel#previewDataMaxLines} lines
 * within the appropriate file and reads them in. It uses
 * {@link ImportAdapter} in combination with
 * {@link ImportConfigurationExcel} to actually read in the data.
 */
private void readPreview() throws IOException {

    /* Reset preview data */
    previewData.clear();

    /* Parameters from the user interface */
    final String location = comboLocation.getText();
    final int sheetIndex = comboSheet.getSelectionIndex();
    final boolean containsHeader = btnContainsHeader.getSelection();

    /* Variables needed for processing */
    Sheet sheet = workbook.getSheetAt(sheetIndex);
    Iterator<Row> rowIterator = sheet.iterator();
    ImportConfigurationExcel config = new ImportConfigurationExcel(location, sheetIndex, containsHeader);
    wizardColumns = new ArrayList<ImportWizardModelColumn>();

    /* Check whether there is at least one row in sheet and retrieve it */
    if (!rowIterator.hasNext()) {
        throw new IOException("Sheet contains no actual data");
    }

    /* Get first row */
    Row firstRow = rowIterator.next();

    /* Check whether there is at least one column in row */
    if (firstRow.getPhysicalNumberOfCells() < 1) {
        throw new IOException("First row contains no data");
    }

    /* Iterate over columns and add them */
    for (int i = 0; i < firstRow.getPhysicalNumberOfCells(); i++) {

        ImportColumn column = new ImportColumnExcel(i, DataType.STRING);
        ImportWizardModelColumn wizardColumn = new ImportWizardModelColumn(column);

        wizardColumns.add(wizardColumn);
        config.addColumn(column);
    }

    /* Create adapter to import data with given configuration */
    ImportAdapter importAdapter = ImportAdapter.create(config);

    /* Get up to {ImportData#previewDataMaxLines} lines for previewing */
    int count = 0;
    while (importAdapter.hasNext() && (count <= ImportWizardModel.previewDataMaxLines)) {
        previewData.add(importAdapter.next());
        count++;
    }

    /* Remove first entry as it always contains name of columns */
    previewData.remove(0);

    /* Check whether there is actual any data */
    if (previewData.size() == 0) {
        throw new IOException("No actual data in file");
    }

    /* Disable redrawing once redesign is finished */
    tablePreview.setRedraw(false);

    /* Remove all of the old columns */
    while (tablePreview.getColumnCount() > 0) {
        tablePreview.getColumns()[0].dispose();
    }

    /* Add new columns */
    for (ImportWizardModelColumn column : wizardColumns) {

        TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewerPreview, SWT.NONE);
        tableViewerColumn.setLabelProvider(
                new ExcelColumnLabelProvider(((ImportColumnExcel) column.getColumn()).getIndex()));

        TableColumn tableColumn = tableViewerColumn.getColumn();
        tableColumn.setWidth(100);

        if (btnContainsHeader.getSelection()) {
            tableColumn.setText(column.getColumn().getAliasName());
            tableColumn.setToolTipText("Column #" + ((ImportColumnExcel) column.getColumn()).getIndex());
        }
        ColumnViewerToolTipSupport.enableFor(tableViewerPreview, ToolTip.NO_RECREATE);
    }

    /* Setup preview table */
    tableViewerPreview.setInput(previewData);
    tablePreview.setHeaderVisible(btnContainsHeader.getSelection());
    tablePreview.setVisible(true);
    tablePreview.layout();
    tablePreview.setRedraw(true);
}

From source file:org.deidentifier.arx.io.ImportConfigurationExcel.java

License:Open Source License

/**
 * Sets the indexes based on the header/*from  w w  w  . j a  va 2  s  .  co  m*/
 * 
 * @param row
 */
public void prepare(Row row) {

    for (ImportColumn c : super.getColumns()) {
        ImportColumnExcel column = (ImportColumnExcel) c;
        if (!column.isIndexSpecified()) {
            boolean found = false;
            for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
                row.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
                if (row.getCell(i).getStringCellValue().equals(column.getName())) {
                    found = true;
                    column.setIndex(i);
                }
            }
            if (!found) {
                throw new IllegalArgumentException(
                        "Index for column '" + column.getName() + "' couldn't be found");
            }
        }
    }
}

From source file:org.dhatim.fastexcel.reader.FastExcelReaderTest.java

License:Apache License

@ParameterizedTest
@ValueSource(strings = { "/xlsx/AutoFilter.xlsx", "/xlsx/calendar_stress_test.xlsx",
        "/xlsx/cell_style_simple.xlsx", "/xlsx/comments_stress_test.xlsx", "/xlsx/custom_properties.xlsx",
        "/xlsx/dates.xlsx", "/xlsx/defined_names_simple.xlsx", "/xlsx/ErrorTypes.xlsx",
        "/xlsx/formula_stress_test.xlsx", "/xlsx/formulae_test_simple.xlsx", "/xlsx/hyperlink_no_rels.xlsx",
        "/xlsx/hyperlink_stress_test_2011.xlsx", "/xlsx/interview.xlsx", "/xlsx/issue.xlsx",
        // "/xlsx/large_strings.xlsx",
        "/xlsx/LONumbers-2010.xlsx", "/xlsx/LONumbers-2011.xlsx", "/xlsx/LONumbers.xlsx",
        "/xlsx/merge_cells.xlsx", "/xlsx/mixed_sheets.xlsx", "/xlsx/named_ranges_2011.xlsx",
        "/xlsx/number_format_entities.xlsx", "/xlsx/phonetic_text.xlsx", "/xlsx/pivot_table_named_range.xlsx",
        "/xlsx/rich_text_stress.xlsx", "/xlsx/RkNumber.xlsx", "/xlsx/smart_tags_2007.xlsx", "/xlsx/sushi.xlsx",
        "/xlsx/text_and_numbers.xlsx", "/xlsx/world.xlsx", "/xlsx/write.xlsx",
        // "/xlsx/xlsx-stream-d-date-cell.xlsx"
})
public void testFile(String file) {
    LOGGER.info("Test " + file);
    try (InputStream inputStream = open(file); InputStream inputStream2 = open(file)) {
        try (ReadableWorkbook excel = new ReadableWorkbook(inputStream);
                Workbook workbook = WorkbookFactory.create(inputStream2)) {
            Iterator<Sheet> it = excel.getSheets().iterator();
            while (it.hasNext()) {
                Sheet sheetDef = it.next();

                org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(sheetDef.getIndex());

                try (Stream<Row> data = sheetDef.openStream()) {
                    Iterator<Row> rowIt = data.iterator();
                    Iterator<org.apache.poi.ss.usermodel.Row> itr = sheet.iterator();

                    while (rowIt.hasNext()) {
                        Row row = rowIt.next();
                        org.apache.poi.ss.usermodel.Row expected = itr.next();

                        assertThat(row.getPhysicalCellCount()).as("physical cell")
                                .isEqualTo(expected.getPhysicalNumberOfCells());
                        assertThat(row.getCellCount()).as("logical cell")
                                .isEqualTo(expected.getLastCellNum() == -1 ? 0 : expected.getLastCellNum());

                        for (int i = 0; i < row.getCellCount(); i++) {
                            Cell cell = row.getCell(i);
                            org.apache.poi.ss.usermodel.Cell expCell = expected.getCell(i);

                            assertThat(cell == null).as("cell defined " + i).isEqualTo(expCell == null);
                            if (cell != null) {
                                String cellAddr = cell.getAddress().toString();
                                assertThat(toCode(cell.getType())).as("cell type code " + cellAddr)
                                        .isEqualTo(expCell.getCellTypeEnum().getCode());

                                if (cell.getType() == CellType.NUMBER) {
                                    BigDecimal n = cell.asNumber();
                                    BigDecimal expN = new BigDecimal(getRawValue(expCell));
                                    assertThat(n).as("Number " + cellAddr).isEqualTo(expN);
                                } else if (cell.getType() == CellType.STRING) {
                                    String s = cell.asString();
                                    String expS = expCell.getStringCellValue();
                                    assertThat(s).as("String " + cellAddr).isEqualTo(expS);
                                }//from  w  w w. j  a  v  a  2  s  .  c o m
                            }
                        }
                    }
                } catch (Throwable e) {
                    throw new RuntimeException("On sheet " + sheetDef.getId() + " " + sheetDef.getName(), e);
                }
            }

        }
    } catch (Throwable e) {
        throw new RuntimeException("On file " + file, e);
    }
}

From source file:org.grible.excel.ExcelFile.java

License:Open Source License

private void setKeys() {
    generalKeys = new ArrayList<String>();
    Sheet sheet = workbook.getSheetAt(0);
    Row keysRow = sheet.getRow(0);
    for (int i = 0; i < keysRow.getPhysicalNumberOfCells(); i++) {
        generalKeys.add(keysRow.getCell(i).getStringCellValue());
    }//from  w w w.j a  va  2  s  .c  om
}

From source file:org.grible.excel.ExcelFile.java

License:Open Source License

private HashMap<String, String> getFirstRowHashBySheetName(String sheetName) {
    HashMap<String, String> result = new HashMap<String, String>();
    Sheet sheet = workbook.getSheet(sheetName);
    Row keysRow = sheet.getRow(0);
    Row valuesRow = sheet.getRow(1);//from w ww . j  ava2  s  . c o m
    for (int i = 0; i < keysRow.getPhysicalNumberOfCells(); i++) {
        result.put(getStringCellValue(keysRow.getCell(i)), getStringCellValue(valuesRow.getCell(i)));
    }
    return result;
}