Example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

List of usage examples for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

Introduction

In this page you can find the example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem.

Prototype


public POIFSFileSystem(InputStream stream) throws IOException 

Source Link

Document

Create a POIFSFileSystem from an InputStream.

Usage

From source file:org.sakaiproject.assignment.tool.AssignmentAction.java

License:Educational Community License

/**
 * parse content inside uploaded zip file
 * @param state/*from  w w w  .jav  a2  s . co m*/
 * @param hasSubmissionText
 * @param hasSubmissionAttachment
 * @param hasGradeFile
 * @param hasFeedbackText
 * @param hasComment
 * @param hasFeedbackAttachment
 * @param submissionTable
 * @param assignment
 * @param fileContentStream
 * @return
 */
private HashMap uploadAll_parseZipFile(SessionState state, boolean hasSubmissionText,
        boolean hasSubmissionAttachment, boolean hasGradeFile, boolean hasFeedbackText, boolean hasComment,
        boolean hasFeedbackAttachment, HashMap submissionTable, Assignment assignment,
        InputStream fileContentStream, String gradeFileFormat, HashMap anonymousSubmissionAndEidTable) {
    // a flag value for checking whether the zip file is of proper format: 
    // should have a grades.csv file or grades.xls if there is no user folders
    boolean zipHasGradeFile = false;
    // and if have any folder structures, those folders should be named after at least one site user (zip file could contain user names who is no longer inside the site)
    boolean zipHasFolder = false;
    boolean zipHasFolderValidUserId = false;

    FileOutputStream tmpFileOut = null;
    File tempFile = null;

    // as stated from UI, we expected the zip file to have structure as follows
    //       assignment_name/user_eid/files
    // or assignment_name/grades.csv or assignment_name/grades.xls
    boolean validZipFormat = true;

    try {
        tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), "");

        tmpFileOut = new FileOutputStream(tempFile);
        writeToStream(fileContentStream, tmpFileOut);
        tmpFileOut.flush();
        tmpFileOut.close();

        ZipFile zipFile = new ZipFile(tempFile, "UTF-8");
        Enumeration<ZipEntry> zipEntries = zipFile.getEntries();
        ZipEntry entry;
        while (zipEntries.hasMoreElements() && validZipFormat) {
            entry = zipEntries.nextElement();
            String entryName = entry.getName();
            if (!entry.isDirectory() && entryName.indexOf("/.") == -1) {
                // SAK-17606
                String anonTitle = rb.getString("grading.anonymous.title");

                if (entryName.endsWith("grades.csv") || entryName.endsWith("grades.xls")) {
                    if (hasGradeFile && entryName.endsWith("grades.csv") && "csv".equals(gradeFileFormat)) {
                        // at least the zip file has a grade.csv
                        zipHasGradeFile = true;

                        // read grades.cvs from zip
                        CSVReader reader = new CSVReader(new InputStreamReader(zipFile.getInputStream(entry)));

                        List<String[]> lines = reader.readAll();

                        if (lines != null) {
                            for (int i = 3; i < lines.size(); i++) {
                                String[] items = lines.get(i);
                                if ((assignment.isGroup() && items.length > 3) || items.length > 4) {
                                    // has grade information
                                    try {
                                        String _the_eid = items[1];
                                        if (!assignment.isGroup()) {

                                            // SAK-17606
                                            User u = null;
                                            // check for anonymous grading
                                            if (!AssignmentService.getInstance()
                                                    .assignmentUsesAnonymousGrading(assignment)) {
                                                u = UserDirectoryService
                                                        .getUserByEid(items[IDX_GRADES_CSV_EID]);
                                            } else { // anonymous so pull the real eid out of our hash table
                                                String anonId = items[IDX_GRADES_CSV_EID];
                                                String id = (String) anonymousSubmissionAndEidTable.get(anonId);
                                                u = UserDirectoryService.getUser(id);
                                            }

                                            if (u == null)
                                                throw new Exception("User not found!");
                                            _the_eid = u.getId();
                                        }

                                        UploadGradeWrapper w = (UploadGradeWrapper) submissionTable
                                                .get(_the_eid);
                                        if (w != null) {
                                            String itemString = assignment.isGroup() ? items[3] : items[4];
                                            int gradeType = assignment.getContent().getTypeOfGrade();
                                            if (gradeType == Assignment.SCORE_GRADE_TYPE) {
                                                validPointGrade(state, itemString);
                                            } // SAK-24199 - Applied patch provided with a few additional modifications.
                                            else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) {
                                                itemString = validatePassFailGradeValue(state, itemString);
                                            } else {
                                                validLetterGrade(state, itemString);
                                            }
                                            if (state.getAttribute(STATE_MESSAGE) == null) {
                                                w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE
                                                        ? scalePointGrade(state, itemString)
                                                        : itemString);
                                                submissionTable.put(_the_eid, w);
                                            }

                                        }

                                    } catch (Exception e) {
                                        M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage());
                                    }
                                }
                            }
                        }
                    } //end of csv grades import

                    //Excel file import
                    if (hasGradeFile && entryName.endsWith("grades.xls") && "excel".equals(gradeFileFormat)) {
                        // at least the zip file has a grade.csv
                        zipHasGradeFile = true;

                        // read grades.xls from zip
                        POIFSFileSystem fsFileSystem = new POIFSFileSystem(zipFile.getInputStream(entry));
                        HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
                        HSSFSheet hssfSheet = workBook.getSheetAt(0);
                        //Iterate the rows
                        Iterator rowIterator = hssfSheet.rowIterator();
                        int count = 0;
                        while (rowIterator.hasNext()) {
                            HSSFRow hssfRow = (HSSFRow) rowIterator.next();
                            //We skip first row (= header row)
                            if (count > 0) {
                                double gradeXls = -1;
                                String itemString = null;
                                // has grade information
                                try {
                                    String _the_eid = hssfRow.getCell(1).getStringCellValue();
                                    if (!assignment.isGroup()) {
                                        if (!AssignmentService.getInstance()
                                                .assignmentUsesAnonymousGrading(assignment)) {
                                            User u = UserDirectoryService.getUserByEid(
                                                    hssfRow.getCell(1).getStringCellValue()/*user eid*/);
                                            if (u == null)
                                                throw new Exception("User not found!");
                                            _the_eid = u.getId();
                                        } else {
                                            _the_eid = (String) anonymousSubmissionAndEidTable.get(_the_eid);
                                        }
                                    }
                                    UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(_the_eid);
                                    if (w != null) {
                                        itemString = assignment.isGroup() ? hssfRow.getCell(3).toString()
                                                : hssfRow.getCell(4).toString();
                                        int gradeType = assignment.getContent().getTypeOfGrade();
                                        if (gradeType == Assignment.SCORE_GRADE_TYPE) {
                                            //Parse the string to double using the locale format
                                            try {
                                                itemString = assignment.isGroup()
                                                        ? hssfRow.getCell(3).getStringCellValue()
                                                        : hssfRow.getCell(4).getStringCellValue();
                                                if ((itemString != null) && (itemString.trim().length() > 0)) {
                                                    NumberFormat nbFormat = FormattedText.getNumberFormat();
                                                    gradeXls = nbFormat.parse(itemString).doubleValue();
                                                }
                                            } catch (Exception e) {
                                                try {
                                                    gradeXls = assignment.isGroup()
                                                            ? hssfRow.getCell(3).getNumericCellValue()
                                                            : hssfRow.getCell(4).getNumericCellValue();
                                                } catch (Exception e2) {
                                                    gradeXls = -1;
                                                }
                                            }
                                            if (gradeXls != -1) {
                                                // get localized number format
                                                NumberFormat nbFormat = FormattedText.getNumberFormat();
                                                itemString = nbFormat.format(gradeXls);
                                            } else {
                                                itemString = "";
                                            }

                                            validPointGrade(state, itemString);
                                        } else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) {
                                            itemString = validatePassFailGradeValue(state, itemString);
                                        } else {
                                            validLetterGrade(state, itemString);
                                        }
                                        if (state.getAttribute(STATE_MESSAGE) == null) {
                                            w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE
                                                    ? scalePointGrade(state, itemString)
                                                    : itemString);
                                            submissionTable.put(_the_eid, w);
                                        }
                                    }
                                } catch (Exception e) {
                                    M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage());
                                }
                            }
                            count++;
                        }
                    } //end of Excel grades import

                } else {
                    String[] pathParts = entryName.split("/");
                    if (pathParts.length <= 2) {
                        validZipFormat = false;
                    } else {
                        // get user eid part
                        String userEid = "";
                        if (entryName.indexOf("/") != -1) {
                            // there is folder structure inside zip
                            if (!zipHasFolder)
                                zipHasFolder = true;

                            // remove the part of zip name
                            userEid = entryName.substring(entryName.indexOf("/") + 1);
                            // get out the user name part
                            if (userEid.indexOf("/") != -1) {
                                userEid = userEid.substring(0, userEid.indexOf("/"));
                            }
                            // SAK-17606 - get the eid part
                            if ((userEid.indexOf("(") != -1) && !userEid.contains(anonTitle)) {
                                userEid = userEid.substring(userEid.indexOf("(") + 1, userEid.indexOf(")"));
                            }
                            if (userEid.contains(anonTitle)) { // anonymous grading so we have to figure out the eid
                                //get eid out of this slick table we made earlier
                                userEid = (String) anonymousSubmissionAndEidTable.get(userEid);
                            }

                            userEid = StringUtils.trimToNull(userEid);
                            if (!assignment.isGroup()) {
                                try {
                                    User u = UserDirectoryService.getUserByEid(userEid/*user eid*/);
                                    if (u != null)
                                        userEid = u.getId();
                                } catch (Throwable _t) {
                                }
                            }
                        }

                        if (submissionTable.containsKey(userEid)) {

                            if (!zipHasFolderValidUserId)
                                zipHasFolderValidUserId = true;
                            if (hasComment && entryName.indexOf("comments") != -1) {
                                // read the comments file
                                String comment = getBodyTextFromZipHtml(zipFile.getInputStream(entry), true);
                                if (comment != null) {
                                    UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
                                    r.setComment(comment);
                                    submissionTable.put(userEid, r);
                                }
                            }
                            if (hasFeedbackText && entryName.indexOf("feedbackText") != -1) {
                                // upload the feedback text
                                String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry), false);
                                if (text != null) {
                                    UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
                                    r.setFeedbackText(text);
                                    submissionTable.put(userEid, r);
                                }
                            }
                            if (hasSubmissionText && entryName.indexOf("_submissionText") != -1) {
                                // upload the student submission text
                                String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry), false);
                                if (text != null) {
                                    UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
                                    r.setText(text);
                                    submissionTable.put(userEid, r);
                                }
                            }
                            if (hasSubmissionAttachment) {
                                // upload the submission attachment
                                String submissionFolder = "/" + rb.getString("stuviewsubm.submissatt") + "/";
                                if (entryName.indexOf(submissionFolder) != -1) {
                                    // clear the submission attachment first
                                    UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
                                    submissionTable.put(userEid, r);
                                    submissionTable = uploadZipAttachments(state, submissionTable,
                                            zipFile.getInputStream(entry), entry, entryName, userEid,
                                            "submission");
                                }
                            }
                            if (hasFeedbackAttachment) {
                                // upload the feedback attachment
                                String submissionFolder = "/" + rb.getString("download.feedback.attachment")
                                        + "/";
                                if (entryName.indexOf(submissionFolder) != -1) {
                                    // clear the feedback attachment first
                                    UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
                                    submissionTable.put(userEid, r);
                                    submissionTable = uploadZipAttachments(state, submissionTable,
                                            zipFile.getInputStream(entry), entry, entryName, userEid,
                                            "feedback");
                                }
                            }

                            // if this is a timestamp file
                            if (entryName.indexOf("timestamp") != -1) {
                                byte[] timeStamp = readIntoBytes(zipFile.getInputStream(entry), entryName,
                                        entry.getSize());
                                UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid);
                                r.setSubmissionTimestamp(new String(timeStamp));
                                submissionTable.put(userEid, r);
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        // uploaded file is not a valid archive
        addAlert(state, rb.getString("uploadall.alert.zipFile"));
        M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage());
    } finally {
        if (tmpFileOut != null) {
            try {
                tmpFileOut.close();
            } catch (IOException e) {
                M_log.warn(this + ":uploadAll_parseZipFile: Error closing temp file output stream: "
                        + e.toString());
            }
        }

        if (fileContentStream != null) {
            try {
                fileContentStream.close();
            } catch (IOException e) {
                M_log.warn(this + ":uploadAll_parseZipFile: Error closing file upload stream: " + e.toString());
            }
        }

        //clean up the zip file
        if (tempFile != null && tempFile.exists()) {
            if (!tempFile.delete()) {
                M_log.warn("Failed to clean up temp file");
            }
        }

    }

    //This is used so that the "Zip Error" message is only printed once

    boolean zipError = false;

    // generate error when there is no grade file and no folder structure
    if (!zipHasGradeFile && !zipHasFolder) {
        addAlert(state, rb.getString("uploadall.alert.incorrectFormat"));
        addAlert(state, rb.getString("uploadall.alert.noGradeFile"));
        zipError = true;
    }
    // generate error when there is folder structure but not matching one user id
    if (zipHasFolder && !zipHasFolderValidUserId) {
        if (zipError == false)
            addAlert(state, rb.getString("uploadall.alert.incorrectFormat"));
        addAlert(state, rb.getString("uploadall.alert.invalidUserId"));
        zipError = true;
    }
    // should have right structure of zip file
    if (!validZipFormat) {
        if (zipError == false)
            addAlert(state, rb.getString("uploadall.alert.incorrectFormat"));

        // alert if the zip is of wrong format
        addAlert(state, rb.getString("uploadall.alert.wrongZipFormat"));
        zipError = true;

    }
    return submissionTable;
}

From source file:org.sakaiproject.contentreview.impl.compilatio.CompilatioContentValidator.java

License:Educational Community License

private int wordDocLength(ContentResource resource) {
    if (!serverConfigurationService.getBoolean("tii.checkWordLength", false))
        return 100;

    try {//  ww w . ja  va 2s.c om
        POIFSFileSystem pfs = new POIFSFileSystem(resource.streamContent());
        HWPFDocument doc = new HWPFDocument(pfs);
        SummaryInformation dsi = doc.getSummaryInformation();
        int count = dsi.getWordCount();
        log.debug("got a count of " + count);
        //if this == 0 then its likely that something went wrong -poi couldn't read it
        if (count == 0)
            return 100;
        return count;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ServerOverloadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //in case we can't read this lets err on the side of caution
    return 100;
}

From source file:org.sakaiproject.search.component.adapter.contenthosting.XLContentDigester.java

License:Educational Community License

public void loadContent(Writer writer, ContentResource contentResource) {
    if (contentResource != null && contentResource.getContentLength() > maxDigestSize) {
        throw new RuntimeException(
                "Attempt to get too much content as a string on " + contentResource.getReference());
    }//from w ww .  j a  va 2 s  .  c om
    if (contentResource == null) {
        throw new RuntimeException("Null contentResource passed the loadContent");
    }

    InputStream contentStream = null;
    try {
        contentStream = contentResource.streamContent();

        POIFSFileSystem fs = new POIFSFileSystem(contentStream);
        HSSFWorkbook workbook = new HSSFWorkbook(fs);

        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            HSSFSheet sheet = workbook.getSheetAt(i);

            Iterator<Row> rows = sheet.rowIterator();
            while (rows.hasNext()) {
                HSSFRow row = (HSSFRow) rows.next();

                Iterator<Cell> cells = row.cellIterator();
                while (cells.hasNext()) {
                    HSSFCell cell = (HSSFCell) cells.next();
                    switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        String num = Double.toString(cell.getNumericCellValue()).trim();
                        if (num.length() > 0) {
                            writer.write(num + " ");
                        }
                        break;
                    case HSSFCell.CELL_TYPE_STRING:
                        String text = cell.getStringCellValue().trim();
                        if (text.length() > 0) {
                            writer.write(text + " ");
                        }
                        break;
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new RuntimeException("Failed to read content for indexing ", e);
    } finally {
        if (contentStream != null) {
            try {
                contentStream.close();
            } catch (IOException e) {
                log.debug(e);
            }
        }
    }

}

From source file:org.seasar.fisshplate.template.FPTemplate.java

License:Apache License

/**
 * @param templateName/*from   w  ww.  j  av a  2  s . c  o m*/
 *            ??
 * @param data
 *            ??
 * @return ?????{@link HSSFWorkbook}
 * @throws FPParseException ?????????
 * @throws FPMergeException ??????????
 * @throws IOException
 *             IO????????
 */
public HSSFWorkbook process(String templateName, Map<String, Object> data)
        throws FPParseException, FPMergeException, IOException {
    InputStream is = InputStreamUtil.getResourceAsStream(templateName);
    HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(is));
    InputStreamUtil.close(is);
    return process(workbook, data);
}

From source file:org.seasar.fisshplate.template.FPTemplate.java

License:Apache License

/**
 * @param is//from  w  w w.j  av a 2 s.co m
 *            ?{@link InputStream}
 * @param data
 *            ??
 * @return ?????{@link HSSFWorkbook}
 * @throws FPParseException ?????????
 * @throws FPMergeException ??????????
 * @throws IOException
 *             IO????????
 */
public HSSFWorkbook process(InputStream is, Map<String, Object> data)
        throws FPParseException, FPMergeException, IOException {
    return process(new HSSFWorkbook(new POIFSFileSystem(is)), data);
}

From source file:org.silverpeas.core.index.indexing.parser.excelParser.ExcelParser.java

License:Open Source License

/**
 * Read the text content of a pdf file and store it in out to be ready to be indexed.
 * @param out/*from  w  ww.j  a v  a2 s .  co m*/
 * @param path
 * @param encoding
 * @throws IOException
 */
@Override
public void outPutContent(Writer out, String path, String encoding) throws IOException {
    FileInputStream file = new FileInputStream(path);
    try {
        POIFSFileSystem fs = new POIFSFileSystem(file);
        HSSFWorkbook workbook = new HSSFWorkbook(fs);

        HSSFSheet sheet;
        for (int nbSheet = 0; nbSheet < workbook.getNumberOfSheets(); nbSheet++) {
            // extract sheet's name
            out.write(workbook.getSheetName(nbSheet));
            sheet = workbook.getSheetAt(nbSheet);
            Iterator<Row> rows = sheet.rowIterator();
            while (rows.hasNext()) {
                Row row = rows.next();
                Iterator<Cell> cells = row.cellIterator();
                while (cells.hasNext()) {
                    Cell cell = cells.next();
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        out.write(cell.getStringCellValue());
                        out.write(' ');
                    }
                }
            }
        }
    } catch (IOException ioe) {
        SilverTrace.error("indexing", "ExcelParser.outPutContent()", "indexing.MSG_IO_ERROR_WHILE_READING",
                path, ioe);
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:org.silverpeas.search.indexEngine.parser.excelParser.ExcelParser.java

License:Open Source License

/**
 *Read the text content of a pdf file and store it in out to be ready to be indexed.
 * @param out/*from   w w  w . j a v a  2 s.  com*/
 * @param path
 * @param encoding
 * @throws IOException
 */
@Override
public void outPutContent(Writer out, String path, String encoding) throws IOException {
    FileInputStream file = new FileInputStream(path);
    try {
        POIFSFileSystem fs = new POIFSFileSystem(file);
        HSSFWorkbook workbook = new HSSFWorkbook(fs);

        HSSFSheet sheet = null;
        for (int nbSheet = 0; nbSheet < workbook.getNumberOfSheets(); nbSheet++) {
            // extract sheet's name
            out.write(workbook.getSheetName(nbSheet));
            SilverTrace.debug("indexEngine", "ExcelParser.outputContent", "root.MSG_GEN_PARAM_VALUE",
                    "sheetName = " + workbook.getSheetName(nbSheet));
            sheet = workbook.getSheetAt(nbSheet);
            Iterator<Row> rows = sheet.rowIterator();
            while (rows.hasNext()) {
                Row row = rows.next();
                Iterator<Cell> cells = row.cellIterator();
                while (cells.hasNext()) {
                    Cell cell = cells.next();
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        out.write(cell.getStringCellValue());
                        out.write(' ');
                        SilverTrace.debug("indexEngine", "ExcelParser.outputContent",
                                "root.MSG_GEN_PARAM_VALUE", "cellValue = " + cell.getStringCellValue());
                    }
                }
            }
        }
    } catch (IOException ioe) {
        SilverTrace.error("indexEngine", "ExcelParser.outPutContent()",
                "indexEngine.MSG_IO_ERROR_WHILE_READING", path, ioe);
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:org.sns.tool.data.DataGeneratorSources.java

License:Open Source License

public DataGeneratorSources(final InputStream workbookStream) throws IOException {
    assert workbookStream != null;

    final POIFSFileSystem fileSystem = new POIFSFileSystem(workbookStream);
    final HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);

    assert fileSystem != null;
    assert workbook != null;

    readNamesAndCounts(workbook.getSheet("Common Male Names"), maleNamesAndCounts);
    readNamesAndCounts(workbook.getSheet("Common Female Names"), femaleNamesAndCounts);
    readNamesAndCounts(workbook.getSheet("Common Surnames"), surnamesAndCounts);
    readCitiesAndPopulations(workbook.getSheet("Largest US Cities"));
    readSingleColumn(workbook.getSheet("Popular Street Names"), popularStreetNames);
    readSingleColumn(workbook.getSheet("Common Street Suffixes"), commonStreetSuffixes);
    readSingleColumn(workbook.getSheet("USPS Street Suffixes"), uspsStreetSuffixes);

    final HSSFSheet censusData = workbook.getSheet("Census Data");
    totalNationalPopulation = (int) censusData.getRow(1).getCell((short) 1).getNumericCellValue();
    malePopulationPercentage = censusData.getRow(4).getCell((short) 2).getNumericCellValue() / 100.0;
    femalePopulationPercentage = censusData.getRow(5).getCell((short) 2).getNumericCellValue() / 100.0;

    workbookStream.close();/* w w  w  .jav a2  s .c o m*/
}

From source file:org.specrunner.source.excel.SourceFactoryExcel.java

License:Open Source License

/**
 * Load a document from a target./*from w  w  w .  j av  a  2  s  .c om*/
 * 
 * @param uri
 *            The target corresponding uri (if any).
 * @param target
 *            The target.
 * @param encoding
 *            The encoding.
 * @return The document, if exists, null, otherwise.
 * @throws SourceException
 *             On load error.
 */
@Override
protected Document fromTarget(URI uri, String target, String encoding) throws SourceException {
    Element html = new Element("html");
    Document result = new Document(html);
    OPCPackage pkg = null;
    InputStream in = null;
    POIFSFileSystem fsys = null;
    try {
        Workbook wb = null;
        if (isFile(uri, target)) {
            if (UtilLog.LOG.isDebugEnabled()) {
                UtilLog.LOG.debug("Source from file:" + target);
            }
            in = new FileInputStream(new File(target));
        } else {
            if (UtilLog.LOG.isDebugEnabled()) {
                UtilLog.LOG.debug("Source from URI:" + uri);
            }
            in = uri.toURL().openStream();
        }
        if (target.trim().toLowerCase().endsWith(XLSX)) {
            pkg = OPCPackage.open(in);
            wb = new XSSFWorkbook(pkg);
        } else {
            fsys = new POIFSFileSystem(in);
            wb = new HSSFWorkbook(fsys);
        }
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            Sheet sheet = wb.getSheetAt(i);
            Map<String, Dimension> spanMap = new HashMap<String, Dimension>();
            Set<String> ignoreMap = new HashSet<String>();
            for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                CellRangeAddress region = sheet.getMergedRegion(j);
                for (int x = region.getFirstRow(); x <= region.getLastRow(); x++) {
                    for (int y = region.getFirstColumn(); y <= region.getLastColumn(); y++) {
                        if (x == region.getFirstRow() && y == region.getFirstColumn()) {
                            spanMap.put(x + "," + y,
                                    new Dimension(region.getLastRow() - x + 1, region.getLastColumn() - y + 1));
                        } else {
                            ignoreMap.add(x + "," + y);
                        }
                    }
                }
            }
            Element table = new Element("table");
            table.addAttribute(new Attribute("border", "1"));
            html.appendChild(table);
            Element caption = readCaption(table, sheet);
            Iterator<Row> ite = sheet.iterator();
            readBody(table, caption, spanMap, ignoreMap, ite, headers(table, caption, spanMap, ignoreMap, ite));
        }
    } catch (Exception e) {
        if (UtilLog.LOG.isDebugEnabled()) {
            UtilLog.LOG.debug(e.getMessage(), e);
        }
        throw new SourceException(e);
    } finally {
        if (pkg != null) {
            try {
                pkg.close();
            } catch (IOException e) {
                if (UtilLog.LOG.isDebugEnabled()) {
                    UtilLog.LOG.debug(e.getMessage(), e);
                }
                throw new SourceException(e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                if (UtilLog.LOG.isDebugEnabled()) {
                    UtilLog.LOG.debug(e.getMessage(), e);
                }
                throw new SourceException(e);
            }
        }
    }
    return result;
}

From source file:org.springframework.batch.spreadsheet.ExcelTemplate.java

License:Apache License

/**
 * This is the work horse for row-level worksheet processing.
 * <p>//from  w w w .ja  va  2  s. c o  m
 * 1) Read data from file.<br/>
 * 3) Create an empty List.<br/>
 * 4) Iterate over the specific worksheet, building up the list.<br/>
 * 5) Return the list.
 * 
 * @param <T> - type of the object to be returned
 * @param worksheetName - name of the worksheet to process
 * @param excelCallback - callback defining how to process a row of data
 * @param skipFirstRow
 * @param errorHandler
 * @return list of T objects
 */
public <T> List<T> onEachRow(String worksheetName, ExcelRowCallback<T> excelCallback, boolean skipFirstRow,
        ExcelTemplateErrorHandler<T> errorHandler) {
    try {
        InputStream inp = new FileInputStream(file);
        HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));

        List<T> results = new ArrayList<T>();

        if (skipFirstRow) {
            boolean firstRow = true;
            for (Row row : wb.getSheet(worksheetName)) {
                if (firstRow) {
                    firstRow = false;
                    continue;
                }

                processRow(excelCallback, errorHandler, results, row);
            }
        } else {
            for (Row row : wb.getSheet(worksheetName)) {
                processRow(excelCallback, errorHandler, results, row);
            }
        }

        return results;
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}