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.geotools.data.excel.ExcelDataStore.java

License:Open Source License

public ExcelDataStore(URL url, String sheet2, int headerRow, String latCol, String longCol,
        String projectionString) throws IOException {
    super();/*from  w  w  w  .  j  a va  2 s.c o m*/

    name = url.getFile();
    InputStream is = url.openStream();
    try {
        workbook = WorkbookFactory.create(is);

    } catch (InvalidFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    sheet = workbook.getSheet(sheet2);
    headerRowIndex = headerRow;
    latColumnIndex = lookupColumn(latCol);
    lonColumnIndex = lookupColumn(longCol);

    try {
        setProjection(CRS.decode(projectionString));
    } catch (NoSuchAuthorityCodeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FactoryException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.gephi.io.importer.plugin.file.spreadsheet.ImporterSpreadsheetExcel.java

License:Open Source License

public String[] getAvailableSheetNames() {
    try (Workbook workbook = WorkbookFactory.create(file)) {
        int length = workbook.getNumberOfSheets();

        String[] names = new String[length];
        for (int i = 0; i < length; i++) {
            names[i] = workbook.getSheetName(i);
        }/*from   w w  w .  j a v  a  2s  . c o m*/

        return names;
    } catch (Exception ex) {
        Logger.getLogger("").log(Level.SEVERE, ex.getMessage());
        return new String[] { "Error" };
    }
}

From source file:org.gitools.ui.app.fileimport.wizard.excel.ExcelReader.java

License:Open Source License

@Override
public void run(IProgressMonitor monitor) {
    // Open the workbook
    monitor.begin("Opening workbook [" + locator.getName() + "]", 0);
    InputStream fis = null;/*w  ww .j a v a  2 s  . c  o m*/
    try {
        fis = locator.openInputStream(monitor);
        Workbook workbook = WorkbookFactory.create(fis);
        this.sheet = workbook.getSheetAt(0);

    } catch (IOException | InvalidFormatException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(fis);
    }

    // Read the header
    Row header = sheet.getRow(0);
    Row firstRow = sheet.getRow(1);
    headers = rowToHeader(header, firstRow);

}

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

License:Apache License

/**
 * parse excel file data to java object//from  www .  j a  va  2  s  .co m
 * 
 * @param workbookInputStream
 * @param sheetProcessors
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void read(InputStream workbookInputStream, ExcelReadSheetProcessor<?>... sheetProcessors) {
    Assert.isTrue(workbookInputStream != null, "workbookInputStream can't be null");
    Assert.isTrue(sheetProcessors != null && sheetProcessors.length != 0, "sheetProcessor can't be null");
    try {
        Workbook workbook = WorkbookFactory.create(workbookInputStream);
        for (ExcelReadSheetProcessor<?> sheetProcessor : sheetProcessors) {
            ExcelReadContext context = new ExcelReadContext();
            try {
                Class clazz = sheetProcessor.getTargetClass();
                Integer sheetIndex = sheetProcessor.getSheetIndex();
                String sheetName = sheetProcessor.getSheetName();
                context.setCurSheetIndex(sheetIndex);
                context.setCurSheetName(sheetName);

                Sheet sheet = null;
                if (sheetName != null) {
                    try {
                        sheet = workbook.getSheet(sheetName);
                    } catch (IllegalArgumentException e) {
                        // ignore
                    }
                    if (sheet != null && sheetIndex != null
                            && !sheetIndex.equals(workbook.getSheetIndex(sheet))) {
                        throw new IllegalArgumentException(
                                "sheetName[" + sheetName + "] and sheetIndex[" + sheetIndex + "] not match.");
                    }
                } else if (sheetIndex != null) {
                    try {
                        sheet = workbook.getSheetAt(sheetIndex);
                    } catch (IllegalArgumentException e) {
                        // ignore
                    }
                } else {
                    throw new IllegalArgumentException("sheetName or sheetIndex can't be null");
                }
                if (sheet == null) {
                    ExcelReadException e = new ExcelReadException(
                            "Sheet Not Found Exception. for sheet name:" + sheetName);
                    e.setCode(ExcelReadException.CODE_OF_SHEET_NOT_EXSIT);
                    throw e;
                }

                if (sheetIndex == null) {
                    sheetIndex = workbook.getSheetIndex(sheet);
                }
                if (sheetName == null) {
                    sheetName = sheet.getSheetName();
                }
                // do check
                Map<Integer, Map<String, ExcelReadFieldMappingAttribute>> fieldMapping = new HashMap<Integer, Map<String, ExcelReadFieldMappingAttribute>>();
                Map<String, Map<String, ExcelReadFieldMappingAttribute>> src = null;
                if (sheetProcessor.getFieldMapping() != null) {
                    src = sheetProcessor.getFieldMapping().export();
                }
                convertFieldMapping(sheet, sheetProcessor, src, fieldMapping);
                if (sheetProcessor.getTargetClass() != null && sheetProcessor.getFieldMapping() != null
                        && !Map.class.isAssignableFrom(sheetProcessor.getTargetClass())) {
                    readConfigParamVerify(sheetProcessor, fieldMapping);
                }

                // proc sheet
                context.setCurSheet(sheet);
                context.setCurSheetIndex(sheetIndex);
                context.setCurSheetName(sheet.getSheetName());
                context.setCurRow(null);
                context.setCurRowData(null);
                context.setCurRowIndex(null);
                context.setCurColIndex(null);
                context.setCurColIndex(null);
                // beforeProcess
                sheetProcessor.beforeProcess(context);

                if (sheetProcessor.getPageSize() != null) {
                    context.setDataList(new ArrayList(sheetProcessor.getPageSize()));
                } else {
                    context.setDataList(new ArrayList());
                }

                Integer pageSize = sheetProcessor.getPageSize();
                int startRow = sheetProcessor.getStartRowIndex();
                Integer rowEndIndex = sheetProcessor.getEndRowIndex();
                int actLastRow = sheet.getLastRowNum();
                if (rowEndIndex != null) {
                    if (rowEndIndex > actLastRow) {
                        rowEndIndex = actLastRow;
                    }
                } else {
                    rowEndIndex = actLastRow;
                }

                ExcelProcessControllerImpl controller = new ExcelProcessControllerImpl();
                if (pageSize != null) {
                    int total = rowEndIndex - startRow + 1;
                    int pageCount = (total + pageSize - 1) / pageSize;
                    for (int i = 0; i < pageCount; i++) {
                        int start = startRow + pageSize * i;
                        int size = pageSize;
                        if (i == pageCount - 1) {
                            size = rowEndIndex - start + 1;
                        }
                        read(controller, context, sheet, start, size, fieldMapping, clazz,
                                sheetProcessor.getRowProcessor(), sheetProcessor.isTrimSpace());
                        sheetProcessor.process(context, context.getDataList());
                        context.getDataList().clear();
                        if (controller.isDoBreak()) {
                            controller.reset();
                            break;
                        }
                    }
                } else {
                    read(controller, context, sheet, startRow, rowEndIndex - startRow + 1, fieldMapping, clazz,
                            sheetProcessor.getRowProcessor(), sheetProcessor.isTrimSpace());
                    sheetProcessor.process(context, context.getDataList());
                    context.getDataList().clear();
                }
            } catch (RuntimeException e) {
                sheetProcessor.onException(context, e);
            } finally {
                sheetProcessor.afterProcess(context);
            }
        }
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}

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

License:Apache License

/**
 * parse java object to excel file//from   w w w . jav a 2s  .c  o  m
 * 
 * @param template
 * @param outputStream
 * @param sheetProcessors
 */
public static void write(InputStream template, OutputStream outputStream,
        ExcelWriteSheetProcessor<?>... sheetProcessors) {
    Assert.notNull(template);
    Assert.notNull(outputStream);
    Assert.isTrue(sheetProcessors != null && sheetProcessors.length > 0);
    Workbook workbook;
    try {
        workbook = WorkbookFactory.create(template);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    write(true, workbook, outputStream, sheetProcessors);
}

From source file:org.interpss.util.reader.ExcelFileReader.java

License:Open Source License

/**
 * Load the spreadsheet and process the row, one row at a time,
 * using the File processor //from  ww w.  j  a v a 2 s .c  o  m
 * 
 * @param procer
 * @return sheet name
 */
public String processFile(IExcelFileProcessor<Row> procer) throws InterpssException {
    final File file = new File(this.filepath);
    Workbook wb;
    try {
        final InputStream stream = new FileInputStream(file);
        wb = WorkbookFactory.create(stream);
    } catch (Exception e) {
        ipssLogger.severe(e.toString());
        throw new InterpssException(e.toString());
    }
    if (wb.getNumberOfSheets() <= this.indexSheet) // index starts from 0
        throw new InterpssException(this.sheetname + " does not exit in " + this.filepath);
    Sheet sheet = wb.getSheetAt(this.indexSheet);
    Iterator<Row> rowIter = sheet.rowIterator();
    while (rowIter.hasNext()) {
        procer.processRow(rowIter.next());
    }
    return sheet.getSheetName();
}

From source file:org.jberet.support.io.ExcelStreamingItemWriter.java

License:Open Source License

@Override
protected Workbook createWorkbook(final InputStream templateInputStream)
        throws IOException, InvalidFormatException {
    if (templateInputStream != null) {
        final Workbook template = WorkbookFactory.create(templateInputStream);
        if (template instanceof XSSFWorkbook) {
            workbook = compressTempFiles == Boolean.TRUE
                    ? new SXSSFWorkbook((XSSFWorkbook) template, -1, compressTempFiles)
                    : new SXSSFWorkbook((XSSFWorkbook) template, -1);
            return template;
        } else {/*from w w  w  .  j a v a  2  s .co  m*/
            throw SupportMessages.MESSAGES.incompatibleExcelFileFormat(templateResource);
        }
    } else if (resource.endsWith("xlsx")) {
        final SXSSFWorkbook workbook1 = new SXSSFWorkbook(-1);
        if (compressTempFiles == Boolean.TRUE) {
            workbook1.setCompressTempFiles(true);
        }
        workbook = workbook1;
    } else {
        throw SupportMessages.MESSAGES.incompatibleExcelFileFormat(resource);
    }
    return null;
}

From source file:org.jberet.support.io.ExcelUserModelItemReader.java

License:Open Source License

protected void initWorkbookAndSheet(int startRowNumber) throws Exception {
    workbook = WorkbookFactory.create(inputStream);
    if (sheetName != null) {
        sheet = workbook.getSheet(sheetName);
    }//w  w  w .ja v  a  2 s  .  co  m
    if (sheet == null) {
        sheet = workbook.getSheetAt(sheetIndex);
    }
    startRowNumber = Math.max(startRowNumber, sheet.getFirstRowNum());
    rowIterator = sheet.rowIterator();

    if (startRowNumber > 0) {
        while (rowIterator.hasNext()) {
            final Row row = rowIterator.next();
            currentRowNum = row.getRowNum();
            if (header == null && headerRow == currentRowNum) {
                header = getCellStringValues(row);
            }
            if (currentRowNum >= startRowNumber - 1) {
                break;
            }
        }
    }
}

From source file:org.jberet.support.io.ExcelUserModelItemWriter.java

License:Open Source License

/**
 * Creates the workbook for this writer.
 * @param templateInputStream    java.io.InputStream for the template excel file, if any
 * @return    the template workbook if a template is specified; otherwise null
 * @throws IOException//www .j a v a 2  s  . c  om
 * @throws InvalidFormatException
 */
protected Workbook createWorkbook(final InputStream templateInputStream)
        throws IOException, InvalidFormatException {
    if (templateInputStream != null) {
        return workbook = WorkbookFactory.create(templateInputStream);
    } else {
        workbook = resource.endsWith("xls") ? new HSSFWorkbook() : new XSSFWorkbook();
        return null;
    }
}

From source file:org.joeffice.spreadsheet.JoefficeWorkbookFactory.java

License:Apache License

public static Workbook create(File file) throws IOException, InvalidFormatException {
    String fileName = file.getName().toLowerCase();
    if (fileName.endsWith(".csv") || fileName.endsWith(".txt")) {
        SmartCsvReader csvReader = new SmartCsvReader();
        return csvReader.read(file);
    } else {/*from  www . j a v a2  s .c om*/
        return WorkbookFactory.create(file);
    }
}