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

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

Introduction

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

Prototype

String getSheetName();

Source Link

Document

Returns the name of this sheet

Usage

From source file:org.drugepi.table.TableCreator.java

License:Mozilla Public License

private void createTableFromSheet(Sheet sheet) throws Exception {
    String tableId = sheet.getSheetName();
    String description = sheet.getSheetName();

    Row firstRow = sheet.getRow(0);/*from ww  w.  java 2  s  .  co  m*/

    if (firstRow == null) {
        System.out.println("Sheet is empty.");
        return;
    }

    this.addTable(tableId, description);
    System.out.printf("Table Creator added table: %s\n", tableId);

    LinkedHashMap<String, String> footnoteDefs = new LinkedHashMap<String, String>();
    LinkedHashMap<String, Cell> footnoteLinks = new LinkedHashMap<String, Cell>();

    for (Row row : sheet) {
        if (row != null) {
            boolean rowIsEmpty = true;

            for (Cell cell : row) {
                if (!ExcelUtils.cellIsEmpty(cell)) {
                    rowIsEmpty = false;

                    if (ExcelUtils.cellIsTableDescription(cell)) {
                        this.setTableDescription(tableId, cell.getStringCellValue());
                    }

                    if (ExcelUtils.cellIsRowHeader(cell)) {
                        this.setRowsTitle(tableId, cell.getStringCellValue());
                    }

                    if (ExcelUtils.cellIsColumnDefinition(cell)) {
                        Cell parentCell = ExcelUtils.getColumnParentCell(sheet, row, cell);
                        RowColTypes rcType = (ExcelUtils.cellIsBold(cell) ? RowColTypes.HEADER
                                : RowColTypes.NORMAL);

                        this.addColToTable(tableId, ExcelUtils.getCellId(parentCell),
                                ExcelUtils.getCellId(cell), ExcelUtils.getCellContents(cell), rcType);

                        //                     System.out.printf("Added %s column %s, ID = %s, parent = %s\n",
                        //                           (rcType == RowColTypes.HEADER ? "header" : "normal"),
                        //                           ExcelUtils.getCellContents(cell),
                        //                           ExcelUtils.getCellId(cell), 
                        //                           ExcelUtils.getCellId(ExcelUtils.getColumnParentCell(sheet, row, parentCell)));

                        String footnoteRef = ExcelUtils.getCellFootnoteReference(cell);
                        if (footnoteRef != null)
                            footnoteLinks.put(footnoteRef, cell);
                    }

                    if (ExcelUtils.cellIsRowDefinition(cell)) {
                        Cell parentCell = ExcelUtils.getRowParentCell(sheet, row, cell);

                        RowColTypes rcType = (ExcelUtils.cellIsBold(cell) ? RowColTypes.HEADER
                                : RowColTypes.NORMAL);

                        this.addRowToTable(tableId, ExcelUtils.getCellId(parentCell),
                                ExcelUtils.getCellId(cell), ExcelUtils.getCellContents(cell), rcType);

                        //                     System.out.printf("Added %s row %s, ID = %s, parent = %s\n",
                        //                           (rcType == RowColTypes.HEADER ? "header" : "normal"),
                        //                           ExcelUtils.getCellContents(cell),
                        //                           ExcelUtils.getCellId(cell), 
                        //                           ExcelUtils.getCellId(parentCell));

                        String footnoteRef = ExcelUtils.getCellFootnoteReference(cell);
                        if (footnoteRef != null)
                            footnoteLinks.put(footnoteRef, cell);
                    }

                    if (ExcelUtils.cellIsFootnoteDefinition(cell)) {
                        String footnoteRef = ExcelUtils.getCellFootnoteDefinitionReference(cell);
                        String footnoteText = ExcelUtils.getCellFootnoteDefinitionText(cell);

                        if ((footnoteRef != null) && (footnoteText != null)) {
                            footnoteDefs.put(footnoteRef, footnoteText);

                            System.out.printf("Noted footnote definition %s : %s\n", footnoteRef, footnoteText);
                        }
                    }

                }
            }

            if (rowIsEmpty) {
                this.addRowToTable(tableId, null, ExcelUtils.getRowId(row), "");
                //               System.out.println("Added blank row");
            }
        }
    }

    if (footnoteDefs.size() > 0) {
        for (String footnoteRef : footnoteDefs.keySet()) {
            Cell referredCell = footnoteLinks.get(footnoteRef);
            if (referredCell != null) {

                String rowId = null;
                String colId = null;
                String id = ExcelUtils.getCellId(referredCell);
                ;
                if (ExcelUtils.cellIsRowDefinition(referredCell))
                    rowId = id;
                else if (ExcelUtils.cellIsColumnDefinition(referredCell))
                    colId = id;
                else
                    break;

                this.addFootnoteToTable(tableId, rowId, colId, footnoteRef, footnoteDefs.get(footnoteRef));

                //               System.out.printf("Added footnote %s to R[%s], C[%s] -- %s\n", 
                //                     footnoteRef, rowId, colId, footnoteDefs.get(footnoteRef));
            }
        }
    }
}

From source file:org.drugepi.table.TableCreator.java

License:Mozilla Public License

/**
 * Replace the shell table in an Excel file with data from tables.
 * /*from w  ww .  ja v a  2 s  .  c  o  m*/
 * @param inWorkbookName  Name of the Excel workbook (.xls or .xlsx) with the defined tables.
 * @param outWorkbookName  Name of the Excel workbook (.xls or .xlsx) to use for output.  Any existing file will be replaced.
 * @throws Exception
 */
public void writeTablesToWorkbook(String inWorkbookName, String outWorkbookName) throws Exception {
    InputStream fileIn = new FileInputStream(inWorkbookName);

    Workbook workbook = WorkbookFactory.create(fileIn);
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        String tableId = TableElement.makeId(sheet.getSheetName());
        Table t = this.tables.get(tableId);
        if (t != null)
            this.fillTableInSheet(sheet, t);
    }

    FileOutputStream fileOut = new FileOutputStream(outWorkbookName);
    workbook.write(fileOut);
    fileOut.close();
}

From source file:org.eclipse.emfforms.internal.spreadsheet.core.transfer.EMFFormsSpreadsheetImporterImpl.java

License:Open Source License

private SpreadsheetImportResult readData(Workbook workbook, EClass eClass) {
    final SpreadsheetImportResult result = ErrorFactory.eINSTANCE.createSpreadsheetImportResult();
    final ResourceSet rs = new ResourceSetImpl();
    final MigrationInformation information = new MigrationInformation();
    final AdapterFactoryEditingDomain domain = new AdapterFactoryEditingDomain(
            new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE),
            new BasicCommandStack(), rs);
    rs.eAdapters().add(new AdapterFactoryEditingDomain.EditingDomainProvider(domain));
    final Resource resource = rs.createResource(URI.createURI("VIRTUAL_URI")); //$NON-NLS-1$

    final Map<String, Map<Integer, Integer>> mapIdToSheetIdWithRowId = parseIds(workbook, result);
    final Map<String, VDomainModelReference> sheetColumnToDMRMap = new LinkedHashMap<String, VDomainModelReference>();
    final Map<VDomainModelReference, EMFFormsSpreadsheetValueConverter> converter = new LinkedHashMap<VDomainModelReference, EMFFormsSpreadsheetValueConverter>();
    final List<EObject> importedEObjects = new ArrayList<EObject>(mapIdToSheetIdWithRowId.size());
    for (final String eObjectId : mapIdToSheetIdWithRowId.keySet()) {
        final Map<Integer, Integer> sheetIdToRowId = mapIdToSheetIdWithRowId.get(eObjectId);
        final EObject eObject = EcoreUtil.create(eClass);
        resource.getContents().add(eObject);
        for (final Integer sheetId : sheetIdToRowId.keySet()) {
            final Sheet sheet = workbook.getSheetAt(sheetId);
            final Row labelRow = sheet.getRow(0);
            final Row row = sheet.getRow(sheetIdToRowId.get(sheetId));
            extractRowInformation(labelRow, row, eObject, result, sheet.getSheetName(), sheetId,
                    sheetColumnToDMRMap, converter, information);
        }//from   w  w w  . j  av a 2 s. com
        importedEObjects.add(eObject);
    }
    result.getImportedEObjects().addAll(importedEObjects);
    return result;
}

From source file:org.eclipse.emfforms.internal.spreadsheet.core.transfer.EMFFormsSpreadsheetImporterImpl.java

License:Open Source License

/**
 * Returns a Map from EObject-ID to Sheet-ID to Row-ID.
 *///from  ww w .  j a v a  2s  .  co  m
private Map<String, Map<Integer, Integer>> parseIds(Workbook workbook, SpreadsheetImportResult errorReports) {
    final Map<String, Map<Integer, Integer>> result = new LinkedHashMap<String, Map<Integer, Integer>>();

    for (int sheetId = 0; sheetId < workbook.getNumberOfSheets(); sheetId++) {
        final Sheet sheet = workbook.getSheetAt(sheetId);
        final Row labelRow = sheet.getRow(0);
        if (labelRow == null) {
            errorReports.reportError(Severity.ERROR,
                    MessageFormat.format(
                            LocalizationServiceHelper.getString(getClass(), "ImportError_SheetEmpty"), //$NON-NLS-1$
                            sheet.getSheetName()),
                    ErrorFactory.eINSTANCE.createSheetLocation(workbook.getSheetName(sheetId), 0, 0,
                            "NO CELL")); //$NON-NLS-1$
            continue;
        }
        final Cell idColumnLabelCell = labelRow.getCell(0, Row.CREATE_NULL_AS_BLANK);
        final Comment cellComment = idColumnLabelCell.getCellComment();
        if (cellComment != null && cellComment.getString() != null
                && IGNORE_SHEET.equals(cellComment.getString().getString())) {
            continue;
        }
        final String idColumnLabel = getStringCellValue(idColumnLabelCell);
        if (!EMFFormsIdProvider.ID_COLUMN.equals(idColumnLabel)) {
            /* ID Column is missing. We have to ignore this sheet */
            errorReports.reportError(Severity.ERROR,
                    MessageFormat.format(
                            LocalizationServiceHelper.getString(getClass(), "ImportError_FirstColumnWrong"), //$NON-NLS-1$
                            EMFFormsIdProvider.ID_COLUMN, idColumnLabel),
                    ErrorFactory.eINSTANCE.createSheetLocation(workbook.getSheetName(sheetId), 0, 0,
                            "NO CELL")); //$NON-NLS-1$
            continue;
        }
        for (int rowId = 3; rowId <= sheet.getLastRowNum(); rowId++) {
            final Row row = sheet.getRow(rowId);
            if (row == null) {
                errorReports.reportError(Severity.INFO,
                        LocalizationServiceHelper.getString(getClass(), "ImportError_EmptyRow"), //$NON-NLS-1$
                        ErrorFactory.eINSTANCE.createSheetLocation(workbook.getSheetName(sheetId), 0, rowId,
                                EMFFormsIdProvider.ID_COLUMN));
                continue;
            }
            final String eObjectId = getStringCellValue(row.getCell(0, Row.CREATE_NULL_AS_BLANK));
            if (eObjectId == null || eObjectId.isEmpty()) {
                /* EObject id deleted */
                errorReports.reportError(Severity.ERROR,
                        LocalizationServiceHelper.getString(getClass(), "ImportError_NoEObjectID"), //$NON-NLS-1$
                        ErrorFactory.eINSTANCE.createSheetLocation(workbook.getSheetName(sheetId), 0, rowId,
                                EMFFormsIdProvider.ID_COLUMN));
                continue;
            }
            if (!result.containsKey(eObjectId)) {
                result.put(eObjectId, new LinkedHashMap<Integer, Integer>());
            }
            // each sheetid should only be mapped once to each eobjectid
            if (result.get(eObjectId).containsKey(sheetId)) {
                /* duplicate EObject ID */
                errorReports.reportError(Severity.ERROR,
                        LocalizationServiceHelper.getString(getClass(), "ImportError_DuplicateEObjectID"), //$NON-NLS-1$
                        ErrorFactory.eINSTANCE.createSheetLocation(workbook.getSheetName(sheetId), 0, rowId,
                                EMFFormsIdProvider.ID_COLUMN));
                continue;
            }
            result.get(eObjectId).put(sheetId, rowId);
        }
    }
    return result;
}

From source file:org.eclipse.rcptt.ecl.data.apache.poi.impl.internal.commands.ReadExcelFileService.java

License:Open Source License

private Table readTable(Workbook book, int sheetnum) {
    Table table = ObjectsFactory.eINSTANCE.createTable();
    Sheet sheet = book.getSheetAt(sheetnum);
    table.setPageName(sheet.getSheetName());
    readRows(table, sheet);//w  ww. j  a  v  a 2s  . c om
    return table;
}

From source file:org.formulacompiler.spreadsheet.internal.excel.xls.loader.ExcelXLSLoader.java

License:Open Source License

public Spreadsheet loadFrom(String _originalFileName, InputStream _stream)
        throws IOException, SpreadsheetException {
    final Workbook xlsWorkbook = new HSSFWorkbook(_stream);
    loadConfig(xlsWorkbook);//w w  w  . ja  v a 2 s.  c o  m
    final SpreadsheetBuilder spreadsheetBuilder = new SpreadsheetBuilder(ComputationMode.EXCEL);

    final int numberOfSheets = xlsWorkbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
        final Sheet xlsSheet = xlsWorkbook.getSheetAt(i);
        final SheetBuilder sheetBuilder = spreadsheetBuilder.beginSheet(xlsSheet.getSheetName());
        loadRows(xlsSheet, sheetBuilder);
        sheetBuilder.endSheet();
    }

    final BaseSpreadsheet spreadsheet = spreadsheetBuilder.getSpreadsheet();
    loadNames(xlsWorkbook, spreadsheet);
    return spreadsheet;
}

From source file:org.generationcp.breeding.manager.crossingmanager.util.CrossingManagerUploader.java

License:Open Source License

@Override
public void uploadSucceeded(SucceededEvent event) {
    System.out.println("DEBUG | " + tempFileName);
    System.out.println("DEBUG | Upload succeeded!");

    currentSheet = 0;/*from  ww w  . j  a v  a  2 s  .  c  o m*/
    currentRow = 0;
    currentColumn = 0;

    maleGermplasmList = null;
    maleListIdIsSpecified = false;
    femaleGermplasmList = null;
    femaleListIdIsSpecified = false;
    importedGermplasmCrosses = null;

    fileIsValid = true;

    try {
        inp = new FileInputStream(tempFileName);
        wb = new HSSFWorkbook(inp);

        try {
            Sheet sheet1 = wb.getSheetAt(0);

            if (sheet1 == null || sheet1.getSheetName() == null
                    || !(sheet1.getSheetName().equals("Description"))) {
                MessageNotifier.showError(source.getWindow(), "Error with reading file uploaded.",
                        "File doesn't have the first sheet - Description", Notification.POSITION_CENTERED);
                fileIsValid = false;
                return;
            }
        } catch (Exception ex) {
            MessageNotifier.showError(source.getWindow(), "Error with reading file uploaded.",
                    "File doesn't have the first sheet - Description", Notification.POSITION_CENTERED);
            fileIsValid = false;
            return;
        }

        try {
            Sheet sheet2 = wb.getSheetAt(1);

            if (sheet2 == null || sheet2.getSheetName() == null
                    || !(sheet2.getSheetName().equals("Observation"))) {
                MessageNotifier.showError(source.getWindow(), "Error with reading file uploaded.",
                        "File doesn't have the second sheet - Observation", Notification.POSITION_CENTERED);
                fileIsValid = false;
                return;
            }
        } catch (Exception ex) {
            MessageNotifier.showError(source.getWindow(), "Error with reading file uploaded.",
                    "File doesn't have the second sheet - Observation", Notification.POSITION_CENTERED);
            fileIsValid = false;
            return;
        }

        readExcelSheets();

        if (fileIsValid == false) {
            importedGermplasmCrosses = null;
        }

        // <macky>: moved "selectManuallyMakeCrosses() / selectAlreadyDefinedCrossesInNurseryTemplateFile()"
        // code block to CrossingManagerImportFileComponent.uploadComponents.FinishedListener

    } catch (FileNotFoundException e) {
        System.out.println("File not found");
    } catch (IOException e) {
        showInvalidFileTypeError();
    } catch (ReadOnlyException e) {
        showInvalidFileTypeError();
    } catch (ConversionException e) {
        showInvalidFileTypeError();
    } catch (OfficeXmlFileException e) {
        showInvalidFileTypeError();
    } catch (CrossingManagerUploaderException e) {
        MessageNotifier.showError(source.getWindow(), "Error with reading file uploaded.", e.getMessage(),
                Notification.POSITION_CENTERED);
        fileIsValid = false;
    }
}

From source file:org.generationcp.middleware.operation.parser.WorkbookParser.java

License:Open Source License

protected boolean isDescriptionSheetExists(final Workbook wb) {
    final Sheet sheet1 = wb.getSheetAt(WorkbookParser.DESCRIPTION_SHEET);
    if (sheet1 == null || sheet1.getSheetName() == null
            || !WorkbookParser.DESCRIPTION_SHEET_NAME.equals(sheet1.getSheetName())) {
        return false;
    }/*  ww w  .  j  a v  a2 s. c  o  m*/
    return true;
}

From source file:org.generationcp.middleware.operation.parser.WorkbookParser.java

License:Open Source License

protected void validateExistenceOfSheets(final Workbook wb) throws WorkbookParserException {
    try {//from   www .j  a v a 2  s. c  o m
        final Sheet sheet1 = wb.getSheetAt(WorkbookParser.DESCRIPTION_SHEET);

        if (sheet1 == null || sheet1.getSheetName() == null
                || !WorkbookParser.DESCRIPTION_SHEET_NAME.equals(sheet1.getSheetName())) {
            this.errorMessages.add(new Message("error.missing.sheet.description"));
        }
    } catch (final IllegalArgumentException e) {
        WorkbookParser.LOG.debug(e.getMessage(), e);
        this.errorMessages.add(new Message("error.missing.sheet.description"));
    } catch (final Exception e) {
        throw new WorkbookParserException("Error encountered with parseFile(): " + e.getMessage(), e);
    }

    try {
        final Sheet sheet2 = wb.getSheetAt(WorkbookParser.OBSERVATION_SHEET);

        if (sheet2 == null || sheet2.getSheetName() == null
                || !WorkbookParser.OBSERVATION_SHEET_NAME.equals(sheet2.getSheetName())) {
            this.errorMessages.add(new Message("error.missing.sheet.observation"));
        }
    } catch (final IllegalArgumentException e) {
        WorkbookParser.LOG.debug(e.getMessage(), e);
        this.errorMessages.add(new Message("error.missing.sheet.observation"));
    } catch (final Exception e) {
        throw new WorkbookParserException("Error encountered with parseFile(): " + e.getMessage(), e);
    }
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

License:Apache License

private static void convertFieldMapping(Sheet sheet, ExcelReadSheetProcessor<?> sheetProcessor,
        Map<String, Map<String, ExcelReadFieldMappingAttribute>> src,
        Map<Integer, Map<String, ExcelReadFieldMappingAttribute>> tar) {
    if (src == null) {
        return;//from  w  ww.  j a  v a 2  s  .co m
    }
    Integer headRowIndex = sheetProcessor.getHeadRowIndex();
    Map<String, Integer> colCache = new HashMap<String, Integer>();
    if (headRowIndex != null) {
        Row row = sheet.getRow(headRowIndex);
        if (row != null) {
            int start = row.getFirstCellNum();
            int end = row.getLastCellNum();
            for (int i = start; i < end; i++) {
                Cell cell = row.getCell(i);
                Object cellValue = _readCell(cell);
                if (cellValue != null) {
                    String strVal = cellValue.toString().trim();
                    colCache.put(strVal, i);
                }
            }
        }
    }

    for (Map.Entry<String, Map<String, ExcelReadFieldMappingAttribute>> entry : src.entrySet()) {
        String colIndexOrColName = entry.getKey();
        Integer colIndex = null;
        if (headRowIndex == null) {
            colIndex = convertColCharIndexToIntIndex(colIndexOrColName);
        } else {
            colIndex = colCache.get(colIndexOrColName);
            if (colIndex == null) {
                throw new IllegalStateException("For sheet:" + sheet.getSheetName() + " headRowIndex:"
                        + headRowIndex + " can't find colum named:" + colIndexOrColName);
            }
        }
        tar.put(colIndex, entry.getValue());
    }
}