Example usage for org.apache.poi.xssf.usermodel XSSFSheet rowIterator

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet rowIterator

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFSheet rowIterator.

Prototype

@Override
@SuppressWarnings("unchecked")
public Iterator<Row> rowIterator() 

Source Link

Usage

From source file:com.adobe.acs.commons.data.Spreadsheet.java

License:Apache License

/**
 * Parse out the input file synchronously for easier unit test validation
 *
 * @return List of files that will be imported, including any renditions
 * @throws IOException if the file couldn't be read
 *//*from  w  ww.j av a  2s  .c o m*/
private void parseInputFile(InputStream file) throws IOException {

    XSSFWorkbook workbook = new XSSFWorkbook(file);

    final XSSFSheet sheet = workbook.getSheetAt(0);
    rowCount = sheet.getLastRowNum();
    final Iterator<Row> rows = sheet.rowIterator();

    Row firstRow = rows.next();
    headerRow = readRow(firstRow).stream().map(v -> v != null ? convertHeaderName(v.toString()) : null)
            .collect(Collectors.toList());
    headerTypes = readRow(firstRow).stream().map(Variant::toString)
            .collect(Collectors.toMap(this::convertHeaderName, this::detectTypeFromName, this::upgradeToArray));

    Iterable<Row> remainingRows = () -> rows;
    dataRows = StreamSupport.stream(remainingRows.spliterator(), false).map(this::buildRow)
            .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}

From source file:com.adobe.acs.commons.mcp.impl.processes.AssetFolderCreator.java

License:Apache License

/**
 * Parses the input Excel file and creates a list of AssetFolderDefinition objects to process.
 *
 * @param manager the action manager//from   ww  w . ja  v  a2s .  com
 * @throws IOException
 */
public void parseAssetFolderDefinitions(ActionManager manager) throws Exception {
    manager.withResolver(rr -> {
        final XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
        // Close the InputStream to prevent resource leaks.
        excelFile.close();

        final XSSFSheet sheet = workbook.getSheetAt(0);
        final Iterator<Row> rows = sheet.rowIterator();

        while (rows.hasNext()) {
            parseAssetFolderRow(rows.next());
        }
        log.info("Finished Parsing and collected [ {} ] asset folders for creation.",
                assetFolderDefinitions.size());
    });
}

From source file:com.adobe.acs.commons.mcp.impl.processes.TagCreator.java

License:Apache License

/**
 * Parses the input Excel file and creates a list of TagDefinition objects to process.
 *
 * @param manager the action manager/*  w  w  w  .  ja  va  2 s. c  om*/
 * @throws IOException
 */
@SuppressWarnings({ "squid:S3776", "squid:S1141" })
public void parseTags(ActionManager manager) throws Exception {
    manager.withResolver(rr -> {
        final XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
        final XSSFSheet sheet = workbook.getSheetAt(0);
        final Iterator<Row> rows = sheet.rowIterator();
        final String tagsRootPath = new TagRootResolver(rr).getTagsLocationPath();

        if (tagsRootPath == null) {
            record(ReportRowSatus.FAILED_TO_PARSE,
                    "Abandoning Tag parsing. Unable to determine AEM Tags root (/content/cq:tags vs /etc/tags). Please ensure the path exists and is accessible by the user running Tag Creator.",
                    "N/A", "N/A");
            return;
        }

        while (rows.hasNext()) {
            final Row row = rows.next();
            final Iterator<Cell> cells = row.cellIterator();

            int cellIndex = 0;
            // The previousTagId is reset on each new row.
            String previousTagId = null;

            while (cells.hasNext()) {
                final Cell cell = cells.next();

                final String cellValue = StringUtils.trimToNull(cell.getStringCellValue());
                if (StringUtils.isBlank(cellValue)) {
                    // Hitting a blank cell means its the end of this row; don't process anything past this
                    break;
                }

                // Generate a tag definition that will in turn be used to drive the tag creation
                TagDefinition tagDefinition = getTagDefinition(primary, cellIndex, cellValue, previousTagId,
                        tagsRootPath);

                if (tagDefinition == null) {
                    tagDefinition = getTagDefinition(fallback, cellIndex, cellValue, previousTagId,
                            tagsRootPath);
                }

                if (tagDefinition == null) {
                    log.warn("Could not find a Tag Data Converter that accepts value [ {} ]; skipping...",
                            cellValue);
                    // Record parse failure
                    record(ReportRowSatus.FAILED_TO_PARSE, cellValue, "", "");
                    // Break to next Row
                    break;
                } else {
                    /* Prepare for next Cell */
                    cellIndex++;
                    previousTagId = tagDefinition.getId();

                    if (tagDefinitions.get(tagDefinition.getId()) == null) {
                        tagDefinitions.put(tagDefinition.getId(), tagDefinition);
                    }
                }
            }
        }
        log.info("Finished Parsing and collected [ {} ] tags for import.", tagDefinitions.size());
    });
}

From source file:com.adobe.acs.commons.mcp.util.Spreadsheet.java

License:Apache License

/**
 * Parse out the input file synchronously for easier unit test validation
 *
 * @return List of files that will be imported, including any renditions
 * @throws IOException if the file couldn't be read
 *//*w  w w.  j  a  v  a  2s.  c  o  m*/
private void parseInputFile(InputStream file) throws IOException {

    XSSFWorkbook workbook = new XSSFWorkbook(file);

    final XSSFSheet sheet = workbook.getSheetAt(0);
    rowCount = sheet.getLastRowNum();
    final Iterator<Row> rows = sheet.rowIterator();

    headerRow = readRow(rows.next()).stream().map(this::convertHeaderName).collect(Collectors.toList());

    Iterable<Row> remainingRows = () -> rows;
    dataRows = StreamSupport.stream(remainingRows.spliterator(), false).map(this::buildRow)
            .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}

From source file:com.axelor.apps.admin.service.AsciiDocExportService.java

License:Open Source License

private void processSheet(Iterator<XSSFSheet> iterator, FileWriter fw) throws IOException {

    if (!iterator.hasNext()) {
        return;//from  w w  w .j  a v a  2  s  .c  om
    }

    XSSFSheet sheet = iterator.next();

    //      fw.write("\n\n== " + sheet.getSheetName());

    hasMenu = false;

    processRow(sheet.rowIterator(), fw);

    processSheet(iterator, fw);
}

From source file:com.axelor.apps.admin.service.ViewDocExportService.java

License:Open Source License

private void updateDocMap(MetaFile docFile) {

    try {/* w  w  w .j a  va 2  s  .co m*/
        File doc = MetaFiles.getPath(docFile).toFile();
        FileInputStream inSteam = new FileInputStream(doc);
        XSSFWorkbook book = new XSSFWorkbook(inSteam);

        oldBook = book;

        for (XSSFSheet sheet : book) {
            String lastKey = sheet.getSheetName();
            Iterator<Row> rowIter = sheet.rowIterator();
            while (rowIter.hasNext()) {
                Row row = rowIter.next();

                String key = null;
                if (row.getRowNum() == 0) {
                    key = sheet.getSheetName();
                } else {
                    String name = getCellValue(row.getCell(4));
                    if (Strings.isNullOrEmpty(name)) {
                        name = getCellValue(row.getCell(5));
                    }

                    String type = getCellValue(row.getCell(3));
                    if (type == null) {
                        continue;
                    }
                    type = type.trim();
                    key = getCellValue(row.getCell(1)) + "," + getCellValue(row.getCell(2)) + "," + type + ","
                            + name;

                    if (addComment(lastKey, type, row)) {
                        continue;
                    } else {
                        lastKey = key;
                    }
                }

                docMap.put(key, row.getRowNum());
            }
        }

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

From source file:com.axelor.studio.service.data.validator.ValidatorService.java

License:Open Source License

public void addLog(String log, String sheetName, int rowNum) throws IOException {

    if (logFile == null) {
        logFile = File.createTempFile("ImportLog", ".xlsx");
        logBook = new XSSFWorkbook();
    }/* w  w w  .  j av a2s .c  om*/

    XSSFSheet sheet = logBook.getSheet(sheetName);

    if (sheet == null) {
        sheet = logBook.createSheet(sheetName);
        XSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("Row Number");
        titleRow.createCell(1).setCellValue("Issues");
    }

    Iterator<Row> rowIterator = sheet.rowIterator();
    Row logRow = null;
    while (rowIterator.hasNext()) {
        Row sheetRow = rowIterator.next();
        Cell cell = sheetRow.getCell(0);
        if (cell.getCellType() != Cell.CELL_TYPE_NUMERIC) {
            continue;
        }
        double value = cell.getNumericCellValue();
        if (value == rowNum + 1) {
            logRow = sheetRow;
            break;
        }
    }

    if (logRow == null) {
        logRow = sheet.createRow(sheet.getPhysicalNumberOfRows());
    }

    Cell cell = logRow.getCell(0);
    if (cell == null) {
        cell = logRow.createCell(0);
        cell.setCellValue(rowNum + 1);
    }
    cell = logRow.getCell(1);
    if (cell == null) {
        cell = logRow.createCell(1);
    }
    String oldValue = cell.getStringCellValue();
    if (oldValue == null) {
        cell.setCellValue(log);
    } else {
        cell.setCellValue(oldValue + "\n" + log);
    }

}

From source file:com.cloudera.sa.ExcelRecordReader.java

License:Apache License

@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
    FileSplit fileSplit = (FileSplit) split;
    Configuration conf = context.getConfiguration();
    Path file = fileSplit.getPath();
    FileSystem fs = file.getFileSystem(conf);
    this.in = fs.open(file);
    XSSFWorkbook workbook = new XSSFWorkbook(this.in);
    XSSFSheet sheet = workbook.getSheetAt(0);
    this.totalRows = sheet.getPhysicalNumberOfRows();
    this.processedRows = 0;
    this.rowIterator = sheet.rowIterator();
}

From source file:com.clri.servlet.ExcelUpload.java

private int processExcelFile(File file, String uploadType, int type, int category) {

    int count = 0;
    Connection connection = null;
    MajorProductionsDAO majorProductionsDAO = new MajorProductionsDAO();
    MajorCustomersDAO majorCustomersDAO = new MajorCustomersDAO();
    DataBaseConnection dbcon = new DataBaseConnection();
    MajorProductions majorProductions = new MajorProductions();
    MajorCustomers majorCustomers = new MajorCustomers();
    majorCustomers.setType(type);/*from w  w w .  j a  v  a2 s .com*/
    majorProductions.setType(type);
    majorProductions.setCategory(category);
    majorCustomers.setCategory(category);
    try {
        connection = dbcon.openConnection();
        // Creating Input Stream 
        FileInputStream myInput = new FileInputStream(file);

        // Create a workbook using the File System 
        XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);

        // Get the first sheet from workbook 
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);

        /**
         * We now need something to iterate through the cells.*
         */
        Iterator<Row> rowIter = mySheet.rowIterator();
        int rowCount = 0;
        while (rowIter.hasNext()) {
            XSSFRow row = (XSSFRow) rowIter.next();
            if (rowCount != 0) {
                if (CommonConstants.CUSTOMER_UPLOAD.equalsIgnoreCase(uploadType)) {
                    count += majorCustomersDAO.insertMajorCustomers(connection,
                            getCustomers(row, majorCustomers));
                } else {
                    count += majorProductionsDAO.insertMajorProductions(connection,
                            getProductions(row, majorProductions));
                }

            }
            rowCount++;
        }
    } catch (IOException e) {
    } finally {
        DBUtils.closeConnection(connection);
    }
    return count;

}

From source file:com.docdoku.server.esindexer.ESTools.java

License:Open Source License

private static String microsoftExcelDocumentToString(InputStream inputStream)
        throws IOException, OpenXML4JException, XmlException {
    StringBuilder sb = new StringBuilder();
    try (InputStream excelStream = new BufferedInputStream(inputStream)) {
        if (POIFSFileSystem.hasPOIFSHeader(excelStream)) { // Before 2007 format files
            POIFSFileSystem excelFS = new POIFSFileSystem(excelStream);
            ExcelExtractor excelExtractor = new ExcelExtractor(excelFS);
            sb.append(excelExtractor.getText());
        } else { // New format
            XSSFWorkbook workBook = new XSSFWorkbook(excelStream);
            int numberOfSheets = workBook.getNumberOfSheets();
            for (int i = 0; i < numberOfSheets; i++) {
                XSSFSheet sheet = workBook.getSheetAt(0);
                Iterator<Row> rowIterator = sheet.rowIterator();
                while (rowIterator.hasNext()) {
                    XSSFRow row = (XSSFRow) rowIterator.next();
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        XSSFCell cell = (XSSFCell) cellIterator.next();
                        sb.append(cell.toString());
                        sb.append(" ");
                    }//from   ww  w.  j a  v  a2 s  . c o m
                    sb.append("\n");
                }
                sb.append("\n");
            }
        }
    }
    return sb.toString();
}