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.aludratest.app.excelwizard.JavaBeanExcelDocumentMapperTest.java

License:Apache License

private static void verifyExcelDocument(Collection<WorkbookTracker> files, String expectedFileName,
        String[] expectedMainHeaders, String[] expectedSubHeaders, String[] expectedData)
        throws IOException, InvalidFormatException {
    assertEquals(1, files.size());//  w w  w . ja  v  a  2  s  .  com
    File file = files.iterator().next().getFile();
    assertEquals(expectedFileName, file.getName());
    Workbook workbook = WorkbookFactory.create(file);
    Sheet sheet1 = workbook.getSheet("sheet1");
    assertNotNull(sheet1);
    Row headerRow = sheet1.getRow(0);
    assertNotNull(headerRow);
    for (String expectedMainHeader : expectedMainHeaders) {
        int index = ExcelUtil.findCellWithText(expectedMainHeader, headerRow);
        assertTrue(index >= 0);
    }
    for (String expectedSubHeader : expectedSubHeaders) {
        int index = ExcelUtil.findCellWithText(expectedSubHeader, headerRow);
        assertTrue(index >= expectedMainHeaders.length);
    }
    if (expectedData != null) {
        Row dataRow1 = sheet1.getRow(1);
        assertNotNull(dataRow1);
        for (int i = 0; i < expectedData.length; i++) {
            Cell dataCell = dataRow1.getCell(i);
            String expectedContent = expectedData[i];
            if (expectedContent != null) {
                assertNotNull(dataCell);
                assertEquals(expectedContent, dataCell.getStringCellValue());
            } else {
                assertNull(dataCell);
            }
        }
    }
}

From source file:org.aludratest.app.excelwizard.WorkbookTracker.java

License:Apache License

static WorkbookTracker importWorkbook(File file) throws InvalidFormatException, IOException {
    FileInputStream in = null;/* w  w  w  .j  a v  a 2s.  c  o  m*/
    try {
        in = new FileInputStream(file);
        Workbook woorkbook = WorkbookFactory.create(in);
        return new WorkbookTracker(file, woorkbook, STATUS_UNCHANGED);
    } finally {
        IOUtil.close(in);
    }
}

From source file:org.aludratest.testcase.data.impl.TestConfigInfoHelper.java

License:Apache License

/** Reads the test configuration information from the corresponding tab of the test data file.
 * @param method the method for which to determine the test infos
 * @param invocations the expected number of invocations
 * @return a List of the test infos for the method */
public List<TestDataLoadInfo> testInfos(Method method, int invocations) {
    // check if the Excel document is available
    String excelFilePath = testConfigurationFilePath(method);
    if (excelFilePath == null) {
        return defaultTestInfos(invocations, isIgnored(method));
    }/*  w  w w .j av  a2s  .  c om*/
    if (!IOUtil.isURIAvailable(excelFilePath)) {
        Exception e = new AutomationException("Data file not found: " + excelFilePath);
        return errorInfos(e, invocations);
    }

    // fetch the tab (sheet) with the config info
    try {
        Workbook workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(excelFilePath));
        Sheet sheet = workbook.getSheet(CONFIG_TAB_NAME);
        if (sheet == null) {
            if (aludraConfig.isConfigTabRequired()) {
                Exception e = new AutomationException(
                        "Sheet '" + CONFIG_TAB_NAME + "' not found in file " + excelFilePath);
                return errorInfos(e, invocations);
            } else {
                return defaultTestInfos(invocations, isIgnored(method));
            }
        }
        return parseTestInfos(sheet, invocations, method, excelFilePath);
    } catch (IOException e) {
        throw new AutomationException("Error reading Excel document " + excelFilePath, e);
    } catch (InvalidFormatException e) {
        throw new AutomationException("Error reading Excel document " + excelFilePath, e);
    }
}

From source file:org.apache.metamodel.excel.ExcelUtils.java

License:Apache License

public static Workbook readWorkbook(Resource resource) {
    if (!resource.isExists()) {
        // resource does not exist- create a blank workbook
        if (isXlsxFile(resource)) {
            return new SXSSFWorkbook(1000);
        } else {// w w  w  .j  av a2 s  . c o m
            return new HSSFWorkbook();
        }
    }

    if (resource instanceof FileResource) {
        final File file = ((FileResource) resource).getFile();
        try {
            return WorkbookFactory.create(file);
        } catch (Exception e) {
            logger.error("Could not open workbook", e);
            throw new IllegalStateException("Could not open workbook", e);
        }
    }

    return resource.read(new Func<InputStream, Workbook>() {
        @Override
        public Workbook eval(InputStream inputStream) {
            try {
                return WorkbookFactory.create(inputStream);
            } catch (Exception e) {
                logger.error("Could not open workbook", e);
                throw new IllegalStateException("Could not open workbook", e);
            }
        }
    });
}

From source file:org.apache.metamodel.excel.ZeroBasedRowIteratorTest.java

License:Apache License

public void testHasNext() throws Exception {
    Workbook workbook = WorkbookFactory
            .create(new FileInputStream("src/test/resources/xls_single_cell_sheet.xls"));
    Sheet sheet = workbook.getSheetAt(0);

    // POI's row numbers are 0-based also - the last cell in the sheet is
    // actually A6.
    assertEquals(5, sheet.getLastRowNum());

    ZeroBasedRowIterator it = new ZeroBasedRowIterator(sheet);

    assertTrue(it.hasNext());//from w  w  w  .  java 2  s .c  o m
    assertNull(it.next());

    assertTrue(it.hasNext());
    assertNull(it.next());

    assertTrue(it.hasNext());
    assertNull(it.next());

    assertTrue(it.hasNext());
    assertNull(it.next());

    assertTrue(it.hasNext());
    assertNull(it.next());

    assertTrue(it.hasNext());
    assertNotNull(it.next());

    assertFalse(it.hasNext());
}

From source file:org.bbreak.excella.reports.processor.ReportProcessor.java

License:Open Source License

/**
 * ???//from   w w  w .  j  a va  2 s  . co m
 *
 * @param filepath 
 * @return 
 * @throws IOException ???????
 */
private Workbook getTemplateWorkbook(ReportBook reportBook) throws Exception {
    Workbook wb = null;
    // URL???????URL
    if (reportBook.getTemplateFileURL() != null) {
        InputStream in = null;
        try {
            in = reportBook.getTemplateFileURL().openStream();
            wb = WorkbookFactory.create(in);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    } else {
        FileInputStream fileIn = null;
        try {
            fileIn = new FileInputStream(reportBook.getTemplateFileName());
            wb = WorkbookFactory.create(fileIn);
        } finally {
            if (fileIn != null) {
                fileIn.close();
            }
        }
    }

    return wb;
}

From source file:org.bdxjug.api.infrastructure.sheet.xlsx.XlsxSheet.java

License:Apache License

public XlsxSheet() {
    try (InputStream inputStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("database-site.xlsx");) {
        this.workbook = WorkbookFactory.create(inputStream);
    } catch (IOException | InvalidFormatException e) {
        throw new RuntimeException(e);
    }/*from   w  ww . j a  va 2 s  . co m*/

}

From source file:org.celllife.idart.gui.patientAdmin.PatientAdmin.java

License:Open Source License

private void importPatientViralLoad(String fileName) {
    ArrayList<PatientViralLoadDataImport> patients = new ArrayList<PatientViralLoadDataImport>();
    int rowErrors = 0;
    Session sess = HibernateUtil.getNewSession();
    try {//from  w  ww  . ja  v  a 2  s.co  m
        FileInputStream file = new FileInputStream(new File(fileName));

        //Create Workbook instance holding reference to .xlsx file
        Workbook workbook = WorkbookFactory.create(file);

        //Get first/desired sheet from the workbook
        Sheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        Integer patientId;
        Boolean highViralLoad;
        Date resultDate;
        Row row = rowIterator.next();

        while (rowIterator.hasNext()) {
            try {
                row = rowIterator.next();
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();

                Cell cell = cellIterator.next();

                patientId = new Integer((int) cell.getNumericCellValue());

                cell = cellIterator.next();
                cell = cellIterator.next();
                cell = cellIterator.next();
                cell = cellIterator.next();
                cell = cellIterator.next();

                highViralLoad = (new BooleanConverter()).convert(cell.getStringCellValue());
                //cell.getStringCellValue().equalsIgnoreCase("Sim") ? true : false; 

                cell = cellIterator.next();

                resultDate = cell.getDateCellValue();
                //(new DateConverter()).convert(cell.getNumericCellValue());
                //DateUtil.getJavaDate(cell.getNumericCellValue());
                patients.add(new PatientViralLoadDataImport(patientId, highViralLoad, resultDate));
            } catch (Exception e) {
                e.printStackTrace();
                rowErrors++;
            }
            System.out.println("");
        }
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    PatientViralLoad latestViralLoad, newViralLoad;
    for (PatientViralLoadDataImport patientDataImport : patients) {
        try {
            latestViralLoad = PatientManager.getLastPatientViralLoad(sess, patientDataImport.getId());
            newViralLoad = new PatientViralLoad();
            if (latestViralLoad == null) {
                newViralLoad = new PatientViralLoad();
                newViralLoad.setHighViralLoad(patientDataImport.getHighViralLoad());
                newViralLoad.setBelongsGaac(false);
                newViralLoad.setRecommendedToCounselor(false);
                newViralLoad.setResultDate(new java.sql.Date(patientDataImport.getResultDate().getTime()));
                newViralLoad.setCounselingDate(null);
                newViralLoad.setGaacNumber(Integer.parseInt("0"));
                newViralLoad.setPatient(PatientManager.getPatient(sess, patientDataImport.getId()));
            } else {
                newViralLoad = new PatientViralLoad();
                newViralLoad.setHighViralLoad(patientDataImport.getHighViralLoad());
                newViralLoad.setBelongsGaac(latestViralLoad.getBelongsGaac());
                newViralLoad.setRecommendedToCounselor(latestViralLoad.getRecommendedToCounselor());
                newViralLoad.setResultDate(new java.sql.Date(patientDataImport.getResultDate().getTime()));
                newViralLoad.setCounselingDate(latestViralLoad.getCounselingDate());
                newViralLoad.setGaacNumber(latestViralLoad.getGaacNumber());
                newViralLoad.setPatient(PatientManager.getPatient(sess, patientDataImport.getId()));
            }

            Transaction tx = null;

            try {

                tx = sess.beginTransaction();

                PatientManager.addPatientViralLoad(sess, newViralLoad);

                sess.flush();
                tx.commit();

            } catch (HibernateException he) {
                if (tx != null) {
                    tx.rollback();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    String message = Messages.getString("PatientAdmin.button.importPatient.error1") + " " + rowErrors + " "
            + Messages.getString("PatientAdmin.button.importPatient.error2") + patients.size()
            + Messages.getString("PatientAdmin.button.importPatient.success");
    JOptionPane.showMessageDialog(null, message);

}

From source file:org.cgiar.ccafs.marlo.action.center.capdev.CapacityDevelopmentDetailAction.java

License:Open Source License

public String previewExcelFile() throws Exception {

    this.previewList = new ArrayList<>();
    previewListHeader = new ArrayList<>();
    previewListContent = new ArrayList<>();
    Map<String, Object> previewMap = new HashMap<>();

    Workbook wb = WorkbookFactory.create(this.getRequest().getInputStream());
    boolean rightFile = reader.validarExcelFile(wb);
    if (rightFile) {
        previewListHeader = reader.getHeadersExcelFile(wb);
        previewListContent = reader.getDataExcelFile(wb);
        previewMap.put("headers", previewListHeader);
        previewMap.put("content", previewListContent);

        this.previewList.add(previewMap);

    }//ww w  .  ja v a 2  s.c  o m
    return SUCCESS;

}

From source file:org.cgiar.ccafs.marlo.action.center.capdev.ParticipantsAction.java

License:Open Source License

public String preLoadExcelFile() {
    request = ServletActionContext.getRequest();

    try {//from  w  w w .j a v  a  2 s .  c  o m
        InputStream input = request.getInputStream();

        wb = WorkbookFactory.create(input);

        Sheet sheet = wb.getSheetAt(0);
        Row firstRow = sheet.getRow(0);
        int totalRows = sheet.getLastRowNum();
        int totalColumns = firstRow.getLastCellNum();

        input.close();

    } catch (IOException | EncryptedDocumentException | InvalidFormatException e) {
        e.printStackTrace();
    }

    return SUCCESS;
}