Example usage for org.apache.poi.ss.usermodel WorkbookFactory create

List of usage examples for org.apache.poi.ss.usermodel WorkbookFactory create

Introduction

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

Prototype

public static Workbook create(File file) throws IOException, EncryptedDocumentException 

Source Link

Document

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.

Usage

From source file:org.databene.formats.xls.XLSLineIterator.java

License:Open Source License

private static Sheet sheet(String uri, String sheetName) throws IOException, ParseException {
    try {/*from   w ww.j  av a2s.  c o  m*/
        Workbook workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(uri));
        Sheet sheet = sheetName != null ? workbook.getSheet(sheetName) : workbook.getSheetAt(0);
        if (sheet == null)
            throw new IllegalArgumentException("Sheet '" + sheetName + "' not found in file " + uri);
        return sheet;
    } catch (InvalidFormatException e) {
        throw new ParseException("Error parsing sheet '" + sheetName + "' of " + uri, null);
    }
}

From source file:org.databene.formats.xls.XLSLineIterator.java

License:Open Source License

private static Sheet sheet(String uri, int sheetIndex) throws IOException {
    Workbook workbook;/*  w  w w.  j a v  a 2 s  .  co m*/
    try {
        workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(uri));
        return workbook.getSheetAt(sheetIndex);
    } catch (InvalidFormatException e) {
        throw new ParseException("Error parsing sheet " + sheetIndex + " of " + uri, e, null, -1, -1);
    }
}

From source file:org.databene.platform.xls.AllSheetsXLSEntityIterator.java

License:Open Source License

public AllSheetsXLSEntityIterator(String uri, Converter<String, ?> preprocessor,
        ComplexTypeDescriptor entityDescriptor, boolean formatted) throws IOException, InvalidFormatException {
    this.uri = uri;
    this.preprocessor = preprocessor;
    this.entityDescriptor = entityDescriptor;
    this.rowBased = (entityDescriptor != null && entityDescriptor.isRowBased() != null
            ? entityDescriptor.isRowBased()
            : true);/*from www .  j a  va  2s . com*/
    this.emptyMarker = (entityDescriptor != null && entityDescriptor.getEmptyMarker() != null
            ? entityDescriptor.getEmptyMarker()
            : null);
    this.workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(uri));
    this.sheetNo = -1;
    this.formatted = formatted;
}

From source file:org.databene.platform.xls.SingleSheetXLSEntityIterator.java

License:Open Source License

private static Sheet loadSheet(String uri, String sheetName) throws InvalidFormatException, IOException {
    Workbook workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(uri));
    Sheet sheet = workbook.getSheet(sheetName);
    if (sheet == null)
        throw new ConfigurationError("Sheet '" + sheetName + "' not found in file " + uri);
    return sheet;
}

From source file:org.dbunit.dataset.excel.MyXlsDataSet.java

License:Open Source License

/**
 * Creates a new XlsDataSet object that loads the specified Excel document.
 *///  w w  w.ja v a  2s .  com
public MyXlsDataSet(InputStream in) throws IOException, DataSetException {
    _tables = super.createTableNameMap();

    Workbook workbook;
    try {
        workbook = WorkbookFactory.create(in);
    } catch (InvalidFormatException e) {
        throw new IOException(e);
    }

    int sheetCount = workbook.getNumberOfSheets();
    for (int i = 0; i < sheetCount; i++) {
        ITable table = new MyXlsTable(workbook.getSheetName(i), workbook.getSheetAt(i));
        _tables.add(table.getTableMetaData().getTableName(), table);
    }
}

From source file:org.dbunit.dataset.excel.XlsDataSet.java

License:Open Source License

/**
 * Creates a new XlsDataSet object that loads the specified Excel document.
 *///from  www  .  j av  a2s. c  o m
public XlsDataSet(InputStream in) throws IOException, DataSetException {
    _tables = super.createTableNameMap();

    Workbook workbook;
    try {
        workbook = WorkbookFactory.create(in);
    } catch (InvalidFormatException e) {
        throw new IOException(e);
    }

    int sheetCount = workbook.getNumberOfSheets();
    for (int i = 0; i < sheetCount; i++) {
        ITable table = new XlsTable(workbook.getSheetName(i), workbook.getSheetAt(i));
        _tables.add(table.getTableMetaData().getTableName(), table);
    }
}

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

License:Open Source License

/**
 * Reads in the available sheets from file
 *
 * This reads in the available sheets from the file chosen at
 * {@link #comboLocation} and adds them as items to {@link #comboSheet}.
 *//*from  ww w.  j a v a  2s .c  o  m*/
private void readSheets() throws IOException {

    /* Remove previous items */
    comboSheet.removeAll();

    /* Get workbook */
    try {
        try {
            if (stream != null)
                stream.close();
        } catch (Exception e) {
            /* Die silently*/
        }

        stream = new FileInputStream(comboLocation.getText());
        workbook = WorkbookFactory.create(stream);
    } catch (InvalidFormatException e) {
        throw new IOException("File format invalid");
    }

    /* Add all sheets to combo */
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        comboSheet.add(workbook.getSheetName(i));
    }
}

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

License:Apache License

@Benchmark
public long apachePoi() throws IOException {
    try (Workbook wb = WorkbookFactory.create(openResource(FILE))) {
        org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);
        long sum = StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(sheet.rowIterator(), Spliterator.ORDERED), false)
                .skip(1).mapToLong(r -> (long) r.getCell(0).getNumericCellValue()).sum();
        assertEquals(RESULT, sum);/*from   www  . j  a  v a 2  s. com*/
        return sum;
    }
}

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

License:Apache License

@Test
public void testDates() throws IOException, OpenXML4JException {
    ArrayList<RowDates> values = new ArrayList<>();

    try (InputStream inputStream = open(EXCEL_DATES);
            ReadableWorkbook fworkbook = new ReadableWorkbook(inputStream)) {
        try (Stream<Row> stream = fworkbook.getFirstSheet().openStream()) {
            stream.forEach(row -> {// w  ww.  ja  v a2s . c  o  m
                values.add(new RowDates(row.getRowNum(), row.getCell(0).asDate().toString(),
                        row.getCell(1).asDate().toString()));
            });
        }
    }

    ArrayList<RowDates> wvalues = new ArrayList<>();
    try (InputStream inputStream = open(EXCEL_DATES); Workbook workbook = WorkbookFactory.create(inputStream)) {
        for (org.apache.poi.ss.usermodel.Row row : workbook.getSheetAt(0)) {
            wvalues.add(new RowDates(row.getRowNum() + 1, toODT(row.getCell(0).getDateCellValue()),
                    toODT(row.getCell(1).getDateCellValue())));
        }
    }

    for (int i = 0; i < values.size(); i++) {
        if (!values.get(i).equals(wvalues.get(i))) {
            assertThat(values.get(i)).isEqualTo(wvalues.get(i));
        }
    }
}

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.jav  a2  s. co  m*/
                            }
                        }
                    }
                } catch (Throwable e) {
                    throw new RuntimeException("On sheet " + sheetDef.getId() + " " + sheetDef.getName(), e);
                }
            }

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