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.diffkit.diff.sns.DKPoiSheet.java

License:Apache License

private Workbook getWorkbook() throws IOException {
    if (_workbook != null)
        return _workbook;
    try {/*from  w w w  .  j a  v  a 2  s  .  com*/
        _workbookInputStream = DKStreamUtil.ensureBuffered(FileUtils.openInputStream(this.getFile()));
        _workbook = WorkbookFactory.create(_workbookInputStream);
        return _workbook;
    } catch (InvalidFormatException e_) {
        _log.error(null, e_);
        throw new IOException(e_);
    }
}

From source file:org.drools.decisiontable.DecisionTableProviderImpl.java

License:Apache License

public List<String> loadWorkSheetsFromResource(Resource resource, DecisionTableConfiguration configuration) {
    List<String> drls = new ArrayList<String>(configuration.getRuleTemplateConfigurations().size());

    SpreadsheetCompiler compiler = new SpreadsheetCompiler();

    Workbook w;//from   w  w  w.j  av  a2s .  co  m
    String sheetName = "";
    try {
        w = WorkbookFactory.create(resource.getInputStream());
        for (int i = 0; i < w.getNumberOfSheets(); i++) {
            org.apache.poi.ss.usermodel.Sheet sheet = w.getSheetAt(i);
            sheetName = sheet.getSheetName();
            logger.info("Compiling sheet {} ", sheetName);
            String compiled = compiler.compile(resource, sheetName);
            drls.add(compiled);
        }
        /*for (Sheet sheet : w.getSheets()) {
           sheetName = sheet.getName();
           log.info("Compiling sheet {} from {}", sheetName, xls.getAbsolutePath());
           compileSheet(kbuilder, compiledFiles, xls, compiler, sheetName, in);
           IOUtils.closeQuietly(in);
        }*/
    } catch (Exception e) {
        logger.error("Cannot open ", e);
    }

    return drls;
}

From source file:org.drools.decisiontable.parser.xls.ExcelParser.java

License:Apache License

public void parseFile(InputStream inStream) {
    try {//from  w  ww  .j  av  a 2  s .  com
        Workbook workbook = WorkbookFactory.create(inStream);

        if (_useFirstSheet) {
            Sheet sheet = workbook.getSheetAt(0);
            processSheet(sheet, _listeners.get(DEFAULT_RULESHEET_NAME));
        } else {
            for (String sheetName : _listeners.keySet()) {
                Sheet sheet = workbook.getSheet(sheetName);
                if (sheet == null) {
                    throw new IllegalStateException(
                            "Could not find the sheetName (" + sheetName + ") in the workbook sheetNames.");
                }
                processSheet(sheet, _listeners.get(sheetName));

            }
        }
    } catch (InvalidFormatException e) {
        throw new DecisionTableParseException(
                "An error occurred opening the workbook. It is possible that the encoding of the document did not match the encoding of the reader.",
                e);

    } catch (IOException e) {
        throw new DecisionTableParseException(
                "Failed to open Excel stream, " + "please check that the content is xls97 format.", e);
    }

}

From source file:org.drools.workbench.screens.dtablexls.backend.server.DecisionTableXLSServiceImpl.java

License:Apache License

@Override
public Path create(final Path resource, final InputStream content, final String sessionId,
        final String comment) {
    log.info("USER:" + identity.getIdentifier() + " CREATING asset [" + resource.getFileName() + "]");

    try {/*from   www.j  av a2  s  .co m*/

        File tempFile = File.createTempFile("testxls", null);
        FileOutputStream tempFOS = new FileOutputStream(tempFile);
        IOUtils.copy(content, tempFOS);
        tempFOS.flush();
        tempFOS.close();

        //Validate the xls
        try {
            Workbook workbook = WorkbookFactory.create(new FileInputStream(tempFile));
        } catch (InvalidFormatException e) {
            throw new DecisionTableParseException(
                    "DecisionTableParseException: An error occurred opening the workbook. It is possible that the encoding of the document did not match the encoding of the reader.",
                    e);
        } catch (IOException e) {
            throw new DecisionTableParseException("DecisionTableParseException: Failed to open Excel stream, "
                    + "please check that the content is xls97 format.", e);
        } catch (Throwable e) {
            throw new DecisionTableParseException("DecisionTableParseException: " + e.getMessage(), e);
        }

        final org.uberfire.java.nio.file.Path nioPath = Paths.convert(resource);
        ioService.createFile(nioPath);
        final OutputStream outputStream = ioService.newOutputStream(nioPath,
                makeCommentedOption(sessionId, comment));
        IOUtils.copy(new FileInputStream(tempFile), outputStream);
        outputStream.flush();
        outputStream.close();

        //Read Path to ensure attributes have been set
        final Path newPath = Paths.convert(nioPath);

        return newPath;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        e.printStackTrace();
        throw ExceptionUtilities.handleException(e);

    } finally {
        try {
            content.close();
        } catch (IOException e) {
            throw ExceptionUtilities.handleException(e);
        }
    }
}

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

License:Mozilla Public License

/**
 * Generate table formats by reading an Excel file.  Each sheet in the Excel file will 
 * serve as a table template.//from w w  w. jav a2 s  .co m
 * 
 * @param workbookName  Name of the Excel workbook (.xls or .xlsx) with the defined tables.
 * @throws Exception
 */
public void createTablesFromWorkbook(String workbookName) throws Exception {
    InputStream s = new FileInputStream(workbookName);

    Workbook workbook = WorkbookFactory.create(s);
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        this.createTableFromSheet(sheet);
    }
}

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

License:Mozilla Public License

/**
 * Replace the shell table in an Excel file with data from tables.
 * //w  w w  . 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.lyo.samples.excel.adapter.dao.internal.ExcelDaoImpl.java

License:Open Source License

public Model parseFile(String fileName) {
    if (relationshipUri == null) {
        return null;
    }/*  w  w w .  j  a va2  s. co m*/

    FileInputStream in = null;
    Workbook wb = null;

    try {
        in = new FileInputStream(fileName);
        wb = WorkbookFactory.create(in);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Model model = ModelFactory.createDefaultModel();
    model.setNsPrefixes(ConfigSingleton.getInstance().getNsPrefixes());

    HashMap<Sheet, Object[]> sheetResourceMap = new HashMap<Sheet, Object[]>();

    // Loop for Resources defined in Mapper file
    for (String en : mapperTable.getNameList()) {
        MapperEntry e = mapperTable.getEntry(en);
        String type = e.getType();
        String line = e.getLine();
        String uri = e.getUri();

        // parse line definition in Mapper file
        String[] ls = line.split(",");
        if (ls.length < 3) {
            System.err.println("line must has at least sheet, start row, and end row information");
            continue;
        }
        String ssheet = ls[0].trim();
        String sstart = ls[1].trim();
        String send = ls[2].trim();
        Sheet sheet = null;
        try {
            sheet = wb.getSheetAt(Integer.parseInt(ssheet));
        } catch (NumberFormatException ex) {
            sheet = wb.getSheet(ssheet);
        }
        if (sheet == null) {
            System.err.println("target sheet is not found");
            continue;
        }

        int start = Integer.parseInt(sstart);
        int end = sheet.getLastRowNum();
        if (!send.equals("*")) {
            end = Integer.parseInt(send);
        }
        String cond_cellstring = null;
        boolean exist = true;
        if (ls.length > 3) {
            String scond = ls[3].trim();
            if (scond.startsWith("exist")) {
                cond_cellstring = scond.substring(6, scond.length() - 1).trim();
            } else if (scond.startsWith("notexist")) {
                exist = false;
                cond_cellstring = scond.substring(9, scond.length() - 1).trim();
            }
        }

        // map to find referenced resource later
        Object[] resourceMap = sheetResourceMap.get(sheet);
        if (resourceMap == null) {
            resourceMap = new Object[sheet.getLastRowNum() + 1];
            Arrays.fill(resourceMap, null);
            sheetResourceMap.put(sheet, resourceMap);
        }

        // Loop of excel table rows to find the resource 
        for (int j = start; j <= end; j++) {
            if (sheet.getRow(j) == null) {
                continue;
            }
            if (cond_cellstring != null) {
                Cell cell = getCell(sheet, cond_cellstring, j);
                String value = getCellValue(cell);
                if (value == null && exist || value != null && !exist) {
                    continue;
                }
            }
            // generate URI for this resource
            String[] uris = uri.split(",");
            String format = uris[0].trim();
            String uriString = format;
            if (uris.length == 3) {
                Cell cell = getCell(sheet, uris[1].trim(), j);
                String value1 = getCellValue(cell);
                cell = getCell(sheet, uris[2].trim(), j);
                String value2 = getCellValue(cell);
                uriString = String.format(format, value1, value2);
            } else if (uris.length == 2) {
                Cell cell = getCell(sheet, uris[1].trim(), j);
                String value = getCellValue(cell);
                uriString = String.format(format, value);
            }

            // create a Resource in RDF model with URI and resource type defined in Mapper file
            Resource resource = null;
            try {
                resource = model.createResource(relationshipUri + URLEncoder.encode(uriString, "UTF-8"));

                type = getNameUri(type.trim(), model);
                resource.addProperty(RDF.type, model.createResource(type));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            if (resource == null) {
                continue;
            }

            // Keep resource map for current row which will be used to generate reference URI later
            Map<String, Resource> curResMap = (Map<String, Resource>) resourceMap[j];
            if (curResMap == null) {
                curResMap = new HashMap<String, Resource>();
                resourceMap[j] = curResMap;
            }
            curResMap.put(en, resource);

            // Loop for Properties for this resource defined in Mapper file
            for (String propName : e.getPropertyNameList()) {
                MapperEntry.Property prop = e.getProperty(propName);
                if (prop == null) {
                    continue;
                }
                String propType = prop.getType();
                if (propType == null) {
                    continue;
                }
                if (propType.equalsIgnoreCase("resource")) {
                    // assume that prop contains "reference" information in Mapper file
                    String reference = prop.getReference();
                    if (reference != null) {
                        processReference(model, resource, propName, reference, resourceMap, j);
                    }
                } else {
                    // assume that prop contains "column" information in Mapper file
                    String[] tokens = prop.getColumn().trim().split(",");
                    String fmt = null;
                    String column = tokens[0];
                    if (tokens.length > 1) {
                        fmt = tokens[0];
                        column = tokens[1];
                    }
                    Cell cell = getCell(sheet, column, j);
                    if (cell != null) {
                        String value = getCellValue(cell);
                        if (value != null) {
                            if (fmt != null) {
                                value = String.format(fmt, value);
                            }
                            String qpname = propName.trim();
                            qpname = getNameUri(qpname, model);
                            Property property = model.createProperty(qpname);
                            Literal literal = model.createLiteral(value);
                            resource.addLiteral(property, literal);
                        }
                    }
                }
            }
        }
    }
    return model;
}

From source file:org.eclipse.lyo.samples.excel.adapter.dao.internal.ExcelDaoImpl.java

License:Open Source License

@Override
public int getNewId(String fileName) {
    HSSFWorkbook workBook = new HSSFWorkbook();
    try {//from w w w .  j  a v a 2 s  .  co  m
        FileInputStream in = new FileInputStream(fileName);
        workBook = (HSSFWorkbook) WorkbookFactory.create(in);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InvalidFormatException e) {
        e.printStackTrace();
    }

    HSSFSheet sheet = workBook.getSheet(DEFAULT_SHEET_NAME);

    return sheet.getLastRowNum() + 1;
}

From source file:org.eclipse.lyo.samples.excel.adapter.MapperTable.java

License:Open Source License

public void initialize(String fileName) {
    FileInputStream in = null;//from  w ww.ja  va  2  s  .c  o m
    Workbook wb = null;

    try {
        in = new FileInputStream(fileName);
        wb = WorkbookFactory.create(in);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    String lastName = null;
    Sheet sheet = wb.getSheetAt(0); //wb.getFirstVisibleTab() + 1);
    int start = 2; // skip row 0 and 1
    for (int j = start; j <= sheet.getLastRowNum(); j++) {
        Row row = sheet.getRow(j);
        if (row == null) {
            continue;
        }

        /* 0,    1,    2,    3   */
        /* name, type, line, uri */
        String name = getCellValue(row, 0);
        if (name != null) {
            MapperEntry entry = new MapperEntry(name);
            entry.setType(getCellValue(row, 1)); /* type */
            entry.setLine(getCellValue(row, 2)); /* line */
            entry.setUri(getCellValue(row, 3)); /* uri */
            entryMap.put(name, entry);
            nameList.add(name);
            lastName = name;
            System.out.println("entry " + j + " : name=" + entry.getName() + ", type=" + entry.getType()
                    + ", line=" + entry.getLine() + ", uri=" + entry.getUri());
            continue;
        }

        if (lastName != null) {
            /* 4,         5,         6,        7        */
            /* prop:name, prop:type, prop:col, prop:ref */
            String propName = getCellValue(row, 4);
            if (propName != null) {
                MapperEntry entry = entryMap.get(lastName);
                MapperEntry.Property prop = entry.addProperty(propName);
                prop.setType(getCellValue(row, 5)); /* prop:type */
                prop.setColumn(getCellValue(row, 6)); /* prop:col */
                prop.setReference(getCellValue(row, 7)); /* prop:ref */
                System.out.println("property : name=" + prop.getName() + ", type=" + prop.getType()
                        + ", column=" + prop.getColumn() + ", reference=" + prop.getReference());
            }
        }
    }
}

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

License:Open Source License

public static Workbook readBook(EclFile file) throws CoreException {
    Workbook book;//from   w  w w.j  a va2s .c  om
    try (FileInputStream stream = new FileInputStream(file.toFile())) {
        book = WorkbookFactory.create(stream);
        return book;
    } catch (FileNotFoundException e) {
        throw new CoreException(EclDataApachePOIImplPlugin.createErr(e, "File not found %s", file.toURI()));
    } catch (InvalidFormatException e) {
        throw new CoreException(
                EclDataApachePOIImplPlugin.createErr("Invalid format of file %s", file.toURI()));
    } catch (IOException e) {
        throw new CoreException(EclDataApachePOIImplPlugin.createErr(e, "Error reading file %s", file.toURI()));
    }
}