Example usage for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

List of usage examples for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

Introduction

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

Prototype

int getNumberOfSheets();

Source Link

Document

Get the number of spreadsheets in the workbook

Usage

From source file:org.eclipse.emfforms.internal.spreadsheet.core.renderer.categorization.EMFFormsCategoryRenderer.java

License:Open Source License

private String getSheetName(Workbook workbook, VCategory vElement) {
    for (final VAttachment vAttachment : vElement.getAttachments()) {
        if (VAnnotation.class.isInstance(vAttachment)
                && SHEET_NAME_KEY.equals(VAnnotation.class.cast(vAttachment).getKey())) {
            return VAnnotation.class.cast(vAttachment).getValue();
        }/*from w  w  w. j a v a 2s  .  c  om*/
    }
    final VAnnotation annotation = VAnnotationFactory.eINSTANCE.createAnnotation();
    annotation.setKey(SHEET_NAME_KEY);
    final String sheetName = WorkbookUtil
            .createSafeSheetName(workbook.getNumberOfSheets() + 1 + " " + vElement.getLabel()); //$NON-NLS-1$
    annotation.setValue(sheetName);
    vElement.getAttachments().add(annotation);
    return annotation.getValue();
}

From source file:org.eclipse.emfforms.internal.spreadsheet.core.renderer.categorization.SpreadsheetCategorization_Test.java

License:Open Source License

@Test
public void testEMFFormsCategoryRenderer() throws EMFFormsNoRendererException {
    final Workbook workbook = new HSSFWorkbook();
    final EMFFormsSpreadsheetRendererFactory rendererFactory = Mockito
            .mock(EMFFormsSpreadsheetRendererFactory.class);
    final ReportService reportService = Mockito.mock(ReportService.class);
    final EMFFormsCategoryRenderer renderer = new EMFFormsCategoryRenderer(rendererFactory, reportService);
    final ViewModelContext viewModelContext = new EMFFormsSpreadsheetViewModelContext(
            VViewFactory.eINSTANCE.createView(), null);
    final EMFFormsSpreadsheetRenderTarget renderTarget = new EMFFormsSpreadsheetRenderTarget("root", 0, 0); //$NON-NLS-1$
    final VCategory category = VCategorizationFactory.eINSTANCE.createCategory();
    final VControl vElement = VViewFactory.eINSTANCE.createControl();
    category.setComposite(vElement);/*from   w  ww . j a  v a2s.co  m*/

    final EMFFormsAbstractSpreadsheetRenderer<VElement> categoryRenderer = Mockito
            .mock(EMFFormsAbstractSpreadsheetRenderer.class);
    Mockito.when(rendererFactory.getRendererInstance(vElement, viewModelContext)).thenReturn(categoryRenderer);

    renderer.render(workbook, category, viewModelContext, renderTarget);

    Mockito.verify(rendererFactory).getRendererInstance(vElement, viewModelContext);
    Mockito.verify(categoryRenderer).render(Matchers.same(workbook), Matchers.same(vElement),
            Matchers.same(viewModelContext),
            Matchers.argThat(new BaseMatcher<EMFFormsSpreadsheetRenderTarget>() {

                @Override
                public boolean matches(Object item) {
                    if (!EMFFormsSpreadsheetRenderTarget.class.isInstance(item)) {
                        return false;
                    }
                    final EMFFormsSpreadsheetRenderTarget target = EMFFormsSpreadsheetRenderTarget.class
                            .cast(item);
                    if (0 != target.getColumn()) {
                        return false;
                    }
                    if (0 != target.getRow()) {
                        return false;
                    }

                    final String expected = WorkbookUtil
                            .createSafeSheetName(workbook.getNumberOfSheets() + 1 + " " + vElement.getLabel()); //$NON-NLS-1$
                    if (!expected.equals(target.getSheetName())) {
                        return false;
                    }
                    return true;
                }

                @Override
                public void describeTo(Description description) {
                }
            }));
}

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.
 */// w  w w  .  j a  v  a2s  .  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

public IStatus service(Command command, IProcess context) throws InterruptedException, CoreException {
    ReadExcelFile ref = (ReadExcelFile) command;
    EList<String> sheetNames = ref.getSheets();
    String uri = ref.getUri();//from   w  ww  .  j a  v a2 s.  co  m
    EclFile file = FileResolver.resolve(uri);
    Workbook book = ExcelFileService.readBook(file);

    if (sheetNames != null && !sheetNames.isEmpty()) {
        // try to read sheets
        for (String sheetName : sheetNames) {
            if (book.getSheet(sheetName) == null) {
                return EclDataApachePOIImplPlugin.createErr("Sheet %s does not persist in file %s", sheetName,
                        file.toURI());
            }
            Table table = readTable(book, book.getSheetIndex(sheetName));
            context.getOutput().write(table);
        }
    } else {
        // read all the sheets
        int sheetnum = 0;
        while (sheetnum < book.getNumberOfSheets()) {
            Table table = readTable(book, sheetnum);
            context.getOutput().write(table);
            sheetnum++;
        }
    }

    return Status.OK_STATUS;
}

From source file:org.eclipse.rmf.reqif10.excel.serialization.ExcelResourceImpl.java

License:Open Source License

@Override
protected void doLoad(InputStream inputStream, Map<?, ?> options) throws IOException {
    Workbook workbook = new HSSFWorkbook(inputStream);
    System.out.println("Number of Sheets: " + workbook.getNumberOfSheets());
}

From source file:org.efaps.esjp.common.file.FileUtil_Base.java

License:Apache License

/**
 * Combine xls./* ww w . j a  v  a2s.  c om*/
 *
 * @param _files the files
 * @param _fileName the file name
 * @param _combine the paginate
 * @return the file
 * @throws EFapsException on error
 */
public File combineXls(final List<File> _files, final String _fileName, final boolean _combine)
        throws EFapsException {
    File ret = null;
    if (_files.size() == 1) {
        ret = _files.get(0);
    } else {
        try (final Workbook newWB = new HSSFWorkbook()) {
            final List<Workbook> workBooks = new ArrayList<>();
            for (final File file : _files) {
                workBooks.add(new HSSFWorkbook(new FileInputStream(file)));
            }
            for (final Workbook wb : workBooks) {
                for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                    final Sheet sheet = wb.getSheetAt(i);
                    final Sheet newSheet = newWB.createSheet();
                    copySheets(newSheet, sheet, true);
                }
            }
            ret = getFile(_fileName, "xls");
            final OutputStream outputStream = new FileOutputStream(ret);
            newWB.write(outputStream);
        } catch (final IOException e) {
            LOG.error("Catched", e);
        }
    }
    return ret;
}

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);/*from   ww  w. ja  v  a  2s  . com*/
    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.formulacompiler.spreadsheet.internal.excel.xls.loader.ExcelXLSLoader.java

License:Open Source License

private void loadConfig(Workbook _xlsWorkbook) {
    final SpreadsheetBuilder spreadsheetBuilder = new SpreadsheetBuilder(ComputationMode.EXCEL);
    final int numberOfSheets = _xlsWorkbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
        spreadsheetBuilder.beginSheet(_xlsWorkbook.getSheetAt(i).getSheetName());
        spreadsheetBuilder.endSheet();/*from   w  w w.j a  v  a2  s. c  om*/
    }
    final BaseSpreadsheet spreadsheet = spreadsheetBuilder.getSpreadsheet();

    final Cell gtFormatCell = getCellByName("GlobalTimeFormat", _xlsWorkbook, spreadsheet);
    if (null != gtFormatCell) {
        this.globalTimeFormat = gtFormatCell.getCellStyle().getDataFormatString();
    }
    final Cell gtZoneNameCell = getCellByName("GlobalTimeZoneName", _xlsWorkbook, spreadsheet);
    if (null != gtZoneNameCell) {
        this.globalTimeZone = TimeZone.getTimeZone(gtZoneNameCell.getStringCellValue());
    }
}

From source file:org.formulacompiler.spreadsheet.internal.excel.xls.saver.ExcelXLSSaver.java

License:Open Source License

private void removeDataFrom(final Workbook _xwb) {
    for (int i = _xwb.getNumberOfSheets() - 1; i >= 0; i--) {
        _xwb.removeSheetAt(i);/*from w w  w.  j a  va2 s  .  co  m*/
    }
    for (int i = 0; i < _xwb.getNumberOfNames(); i++) {
        _xwb.removeName(i);
    }
}

From source file:org.forzaframework.util.ExcelUtils.java

License:Apache License

public static Sheet getSheet(Workbook wb, String sheetName, Boolean createNewSheet, Integer indexSheet) {
    Sheet sheet = null;//Revisamos si vamos a crear una hoja nueva o con una ya existente.
    if ((createNewSheet != null && createNewSheet) || wb.getNumberOfSheets() == 0) {
        //Creamos una hoja nueva
        if (sheetName != null) {
            sheet = wb.createSheet(sheetName);
        } else {//  ww w  .  ja  v a  2 s. c om
            sheet = wb.createSheet();
        }
    } else {
        //Revisamos si existe la hoja con el nombre especificado
        if (indexSheet == null && sheetName != null) {
            sheet = wb.getSheet(sheetName);
        }

        if (sheet == null) {
            //Trabajamos con una hoja ya existente
            if (indexSheet == null) {
                indexSheet = 0;
            }
            if (sheetName != null) {
                wb.setSheetName(indexSheet, sheetName);
            }
            sheet = wb.getSheetAt(indexSheet);
        }
    }
    return sheet;
}