Search in sources :

Example 1 with NamedCell_V1

use of com.linkedpipes.plugin.transformer.tabularuv.TabularConfig_V2.NamedCell_V1 in project etl by linkedpipes.

the class ParserXls method parseSheet.

/**
 * Parse given sheet.
 *
 * @param wb
 * @param sheetIndex
 */
public void parseSheet(Workbook wb, Integer sheetIndex) throws ParseFailed, LpException {
    LOG.debug("parseSheet({}, {})", wb.getSheetName(sheetIndex), sheetIndex);
    // for every row
    final Sheet sheet = wb.getSheetAt(sheetIndex);
    if (config.numberOfStartLinesToIgnore > sheet.getLastRowNum()) {
        // no data to parse
        return;
    }
    // generate column names
    int startRow = config.numberOfStartLinesToIgnore;
    List<String> columnNames;
    // Size of original header from file, used to expand/strip content.
    Integer tableHeaderSize = null;
    if (config.hasHeader) {
        // parse line for header
        final Row row = sheet.getRow(startRow++);
        if (row == null) {
            throw new ParseFailed("Header row is null!");
        }
        final int columnStart = row.getFirstCellNum();
        final int columnEnd = row.getLastCellNum();
        columnNames = new ArrayList<>(columnEnd);
        for (int columnIndex = columnStart; columnIndex < columnEnd; columnIndex++) {
            final Cell cell = row.getCell(columnIndex);
            if (cell == null) {
                // The cell is missing, this happen for example if
                // document is exported from gdocs. We just log and use
                // 'null' as cell value.
                LOG.info("Header cell is null ({}, {}) on '{}'!", startRow - 1, columnIndex, wb.getSheetName(sheetIndex));
                columnNames.add(null);
            } else {
                final String name = this.getCellValue(cell);
                columnNames.add(name);
            }
        }
        if (config.stripHeader) {
            // Remove trailing null values.
            int initialSize = columnNames.size();
            for (int i = columnNames.size() - 1; i > 0; --i) {
                if (columnNames.get(i) == null) {
                    columnNames.remove(i);
                } else {
                    // Non null value.
                    break;
                }
            }
            LOG.info("Removal of nulls changed header size from {} to {}", initialSize, columnNames.size());
        } else {
            LOG.debug("Header size {}", columnNames.size());
        }
        // global names will be added later
        tableHeaderSize = columnNames.size();
    } else {
        columnNames = null;
    }
    // 
    // prepare static cells
    // 
    final List<String> namedCells = new LinkedList<>();
    for (NamedCell_V1 namedCell : config.namedCells) {
        final Row row = sheet.getRow(namedCell.getRowNumber() - 1);
        if (row == null) {
            throw new ParseFailed("Row for named cell is null! (" + namedCell.getName() + ")");
        }
        final Cell cell = row.getCell(namedCell.getColumnNumber() - 1);
        if (cell == null) {
            throw new ParseFailed("Cell for named cell is null! (" + namedCell.getName() + ")");
        }
        // get value and add to namedCells
        final String value = getCellValue(cell);
        LOG.debug("static cell {} = {}", namedCell.getName(), value);
        namedCells.add(value);
    }
    // 
    if (config.rowLimit == null) {
        LOG.debug("Row limit: not used");
    } else {
        LOG.debug("Row limit: {}", config.rowLimit);
    }
    // set if for first time or if we use static row counter
    if (!config.checkStaticRowCounter || rowNumber == 0) {
        rowNumber = config.hasHeader ? 2 : 1;
    }
    // go
    boolean headerGenerated = false;
    final int dataEndAtRow;
    if (config.rowLimit != null) {
        // limit number of lines
        dataEndAtRow = startRow + config.rowLimit;
    } else {
        // We increase by one, as we use less < dataEndAtRow,
        // not <= dataEndAtRow
        dataEndAtRow = sheet.getLastRowNum() + 1;
    }
    int skippedLinesCounter = 0;
    for (Integer rowNumPerFile = startRow; rowNumPerFile < dataEndAtRow; ++rowNumber, ++rowNumPerFile) {
        // skip till data
        if (rowNumPerFile < config.numberOfStartLinesToIgnore) {
            continue;
        }
        // get row
        final Row row = sheet.getRow(rowNumPerFile);
        if (row == null) {
            continue;
        }
        // We use zero as the first column must be column 1.
        final int columnStart = row.getFirstCellNum();
        final int columnEnd = row.getLastCellNum();
        // generate header
        if (!headerGenerated) {
            headerGenerated = true;
            // use row data to generate types
            final List<ColumnType> types = new ArrayList<>(columnEnd + namedCells.size());
            // to always start at the first column.
            for (int columnIndex = 0; columnIndex < columnEnd; columnIndex++) {
                final Cell cell = row.getCell(columnIndex);
                if (cell == null) {
                    types.add(null);
                    continue;
                }
                types.add(getCellType(cell));
            }
            // if header is presented.
            if (columnNames == null) {
                LOG.info("Generating column names from: {} to: {}", columnStart, columnEnd);
                columnNames = new ArrayList<>(columnEnd);
                // Generate column names, first column is col1. We start
                // from 0 as we always want start with left most column.
                // See comment before types generation for more info.
                int columnIndex = 0;
                for (int i = 0; i < columnEnd; i++) {
                    columnNames.add("col" + Integer.toString(++columnIndex));
                }
                tableHeaderSize = columnNames.size();
            } else {
                // expand types row. The header might be wider then the
                // first data row.
                fitToSize(types, tableHeaderSize);
            }
            // add user defined names
            for (NamedCell_V1 item : config.namedCells) {
                columnNames.add(item.getName());
                types.add(ColumnType.String);
            }
            // add global types and names
            columnNames.add(SHEET_COLUMN_NAME);
            types.add(ColumnType.String);
            // configure
            TableToRdfConfigurator.configure(tableToRdf, columnNames, (List) types, startRow);
        }
        // Prepare row.
        final List<String> parsedRow = new ArrayList<>(columnEnd + namedCells.size());
        // parse columns
        for (int columnIndex = 0; columnIndex < columnEnd; columnIndex++) {
            final Cell cell = row.getCell(columnIndex);
            if (cell == null) {
                parsedRow.add(null);
            } else {
                parsedRow.add(getCellValue(cell));
            }
        }
        // Check for row null values - this can happen for excel exported
        // from google docs, where the number oof declared data rows
        // is bigger then it should be together with fitToSize we would
        // generate non-existing columns. In order to prevent this
        // we scan an ignore lines with null values only.
        boolean isEmpty = true;
        for (Object value : parsedRow) {
            if (value != null) {
                isEmpty = false;
                break;
            }
        }
        if (isEmpty) {
            ++skippedLinesCounter;
            continue;
        }
        // expand row if needed
        fitToSize(parsedRow, tableHeaderSize);
        // add named columns first !!
        parsedRow.addAll(namedCells);
        // add global data
        parsedRow.add(wb.getSheetName(sheetIndex));
        // convert into table
        tableToRdf.paserRow((List) parsedRow, rowNumber);
        if ((rowNumPerFile % 1000) == 0) {
            LOG.debug("Row number {} processed.", rowNumPerFile);
        }
    }
    // 
    if (skippedLinesCounter != 0) {
        LOG.info("Some lines ({}) were skipped.", skippedLinesCounter);
    }
}
Also used : ColumnType(com.linkedpipes.plugin.transformer.tabularuv.TabularConfig_V2.ColumnType) NamedCell_V1(com.linkedpipes.plugin.transformer.tabularuv.TabularConfig_V2.NamedCell_V1)

Aggregations

ColumnType (com.linkedpipes.plugin.transformer.tabularuv.TabularConfig_V2.ColumnType)1 NamedCell_V1 (com.linkedpipes.plugin.transformer.tabularuv.TabularConfig_V2.NamedCell_V1)1