Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFWorkbook HSSFWorkbook.

Prototype

public HSSFWorkbook(InputStream s) throws IOException 

Source Link

Document

Companion to HSSFWorkbook(POIFSFileSystem), this constructs the POI filesystem around your InputStream , including all nodes.

Usage

From source file:com.Excel.Excel.java

private boolean abrirArchivo() {
    FileInputStream file;//  w w w.j a  v  a  2 s  . com
    try {
        file = new FileInputStream(new File(pathArchivo + "\\" + nombreArchivo));
        workbook = new HSSFWorkbook(file);
        return true;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Excel2007.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Excel2007.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:com.femsa.kof.csi.util.XlsAnalizer.java

public List<Xtmpinddl> analizeXlsIndi(UploadedFile file, final DcsUsuario usuario, List<DcsCatPais> paises,
        List<DcsCatIndicadores> indicadores) throws DCSException {
    Workbook excelXLS = null;//from  www .j a  v a 2 s  .  c o  m
    List<Xtmpinddl> listaCarga = null;
    try {
        String extension = getExtension(file.getFileName());
        Iterator<Row> rowIterator;
        if (extension.equalsIgnoreCase("xlsx")) {
            excelXLS = new XSSFWorkbook(file.getInputstream());
        } else if (extension.equalsIgnoreCase("xls")) {
            excelXLS = new HSSFWorkbook(file.getInputstream());
        }
        int numberOfSheets = excelXLS != null ? excelXLS.getNumberOfSheets() : 0;
        for (int i = 0; i < numberOfSheets; i++) {
            Sheet sheet = excelXLS != null ? excelXLS.getSheetAt(i) : null;
            rowIterator = sheet != null ? sheet.iterator() : null;
            if (sheet != null && i == 0) {
                listaCarga = this.analizeSheetIndi(rowIterator, usuario, sheet.getSheetName(), paises,
                        indicadores);
                if (!listaCarga.isEmpty()) {
                    loadedSheets.add(sheet.getSheetName().trim().toUpperCase());
                } else {
                    omittedSheets.add(sheet.getSheetName().trim().toUpperCase() + ", Empty");
                }
            } else {
                String mensaje = sheet != null ? sheet.getSheetName().trim().toUpperCase() + ", not valid."
                        : "Not valid.";
                omittedSheets.add(mensaje);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error IO", ex);
        throw new DCSException("An error ocurred while analizing the file: " + ex.getMessage());
    } finally {
        try {
            file.getInputstream().close();
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error IO", ex);
            throw new DCSException("An error ocurred while analizing the file: " + ex.getMessage());
        }
    }
    return listaCarga;
}

From source file:com.femsa.kof.csi.util.XlsAnalizer.java

public List<XtmpinddlFlota> analizeXlsFlota(UploadedFile file, final DcsUsuario usuario,
        List<DcsCatPais> paises) throws DCSException {
    Workbook excelXLS = null;/*from  w  w  w  .j  a va2s. c  om*/
    List<XtmpinddlFlota> listaCarga = null;
    try {
        String extension = getExtension(file.getFileName());
        Iterator<Row> rowIterator;
        if (extension.equalsIgnoreCase("xlsx")) {
            excelXLS = new XSSFWorkbook(file.getInputstream());
        } else if (extension.equalsIgnoreCase("xls")) {
            excelXLS = new HSSFWorkbook(file.getInputstream());
        }
        int numberOfSheets = excelXLS != null ? excelXLS.getNumberOfSheets() : 0;
        for (int i = 0; i < numberOfSheets; i++) {
            Sheet sheet = excelXLS != null ? excelXLS.getSheetAt(i) : null;
            rowIterator = sheet != null ? sheet.iterator() : null;
            if (sheet != null && i == 0) {
                listaCarga = this.analizeSheetFlota(rowIterator, usuario, sheet.getSheetName(), paises);
                if (!listaCarga.isEmpty()) {
                    loadedSheets.add(sheet.getSheetName().trim().toUpperCase());
                } else {
                    omittedSheets.add(sheet.getSheetName().trim().toUpperCase() + ", Empty");
                }
            } else {
                String mensaje = sheet != null ? sheet.getSheetName().trim().toUpperCase() + ", not valid."
                        : "Not valid.";
                omittedSheets.add(mensaje);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error IO", ex);
        throw new DCSException("An error ocurred while analizing the file: " + ex.getMessage());
    } finally {
        try {
            file.getInputstream().close();
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error IO", ex);
            throw new DCSException("An error ocurred while analizing the file: " + ex.getMessage());
        }
    }
    return listaCarga;
}

From source file:com.ferid.app.classroom.edit.EditStudentActivity.java

License:Apache License

/**
 * Import students form excel/*from   w  ww.ja  va  2 s  .  co  m*/
 * @param fileName Excel file name
 */
private void readXlsFile(String fileName) {
    ArrayList<String> studentsList = new ArrayList<>();
    progressDialog = ProgressDialog.show(this, getString(R.string.wait), getString(R.string.ongoing), true,
            false);

    try {
        // Creating Input Stream
        File file = new File(fileName);
        FileInputStream fileInputStream = new FileInputStream(file);

        // Create a POIFSFileSystem object
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(fileInputStream);

        // Create a workbook using the File System
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(poifsFileSystem);

        // Get the first sheet from workbook
        HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);

        // Iterate through the cells
        Iterator rowIter = hssfSheet.rowIterator();

        StringBuilder studentName; //full name

        while (rowIter.hasNext()) {
            studentName = new StringBuilder("");

            HSSFRow hssfRow = (HSSFRow) rowIter.next();
            Iterator cellIter = hssfRow.cellIterator();
            while (cellIter.hasNext()) {
                HSSFCell currentCell = (HSSFCell) cellIter.next();
                if (!currentCell.toString().trim().equals("")) {
                    //put space in between name, surname, etc.
                    if (studentName.toString().length() > 0) {
                        studentName.append(" ");
                    }
                    studentName.append(currentCell.toString());
                }
            }

            //add to list
            if (!studentName.toString().equals("")) {
                studentsList.add(studentName.toString());
            }
        }
    } catch (Exception e) {
        progressDialog.dismiss();

        excelFileError();
    }

    if (!studentsList.isEmpty()) {
        new InsertMultipleStudents().execute(studentsList);
    } else {
        progressDialog.dismiss();
    }
}

From source file:com.flexive.extractor.ExcelExtractor.java

License:Open Source License

/**
 * Extracts the text informations from the excel file.
 *
 * @param in the input stream to read from
 * @return the extraxted informations, or null if no text extraction was possible
 *///from www . ja  va 2s .c  o m
public ExtractedData extract(final InputStream in) {

    BufferedInputStream bis = null;
    try {

        writer = new ByteArrayOutputStream();

        // We need to read the stream 2 times, so we use a buffered input stream and mark the
        // beginning
        bis = new BufferedInputStream(in);
        bis.mark(Integer.MAX_VALUE);

        // Retrieve summary information
        POIFSReader r = new POIFSReader();
        r.registerListener(this, "\005SummaryInformation");
        r.read(bis);
        bis.reset();

        // Retrieve text by processing all sheets
        HSSFWorkbook wb = new HSSFWorkbook(bis);
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            HSSFSheet sheet = wb.getSheetAt(i);
            processSheet(sheet);
        }

        // Append summary info to text
        if (fxsi != null) {
            writer.write(FxSharedUtils.getBytes(fxsi.getFTIndexInformations()));
        }
        writer.flush();

        return new ExtractedData(fxsi, writer.toString());
    } catch (Exception exc) {
        exc.printStackTrace();
        return null;
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (Exception exc) {
            /*ignore*/}
        try {
            if (bis != null)
                bis.close();
        } catch (Exception exc) {
            /*ignore*/}
    }
}

From source file:com.framework.common.ExcelSpreadsheet.java

public ExcelSpreadsheet(ExcelFile excelConnectionDetails) throws FileNotFoundException, IOException {

    String current = System.getProperty("user.dir");
    this.filePathAndName = current + "/" + excelConnectionDetails.getFilename();

    FileInputStream fileInputStream = new FileInputStream(excelConnectionDetails.getFilename());
    HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
    HSSFSheet worksheet = workbook.getSheet(excelConnectionDetails.getSheetname());

    this.requiredWorksheet = worksheet;

}

From source file:com.frameworkset.platform.cms.searchmanager.extractors.CmsExtractorMsExcel.java

License:Open Source License

/** 
 * ?excel2003 // w  w  w .j a v  a 2 s  . c om
 * @param path 
 * @return 
 * @throws IOException 
 */
public String readExcel(InputStream in) throws IOException {

    String content = null;
    try {

        HSSFWorkbook wb = new HSSFWorkbook(in);
        ExcelExtractor extractor = new ExcelExtractor(wb);
        extractor.setFormulasNotResults(true);
        extractor.setIncludeSheetNames(false);
        content = extractor.getText();
        this.m_documentSummary = extractor.getDocSummaryInformation();
        this.m_summary = extractor.getSummaryInformation();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return content;
}

From source file:com.frameworkset.platform.cms.searchmanager.extractors.CmsExtractorMsExcel.java

License:Open Source License

/**
 * Extracts the text from the Excel table content.<p>
 * //from w w w.j  av a 2  s . c  om
 * @param in the document input stream
 * @return the extracted text
 * @throws IOException if something goes wring
 */
protected String extractTableContent(InputStream in) throws IOException {

    HSSFWorkbook excelWb = new HSSFWorkbook(in);
    StringBuffer result = new StringBuffer(4096);

    int numberOfSheets = excelWb.getNumberOfSheets();

    for (int i = 0; i < numberOfSheets; i++) {
        HSSFSheet sheet = excelWb.getSheetAt(i);
        int numberOfRows = sheet.getPhysicalNumberOfRows();
        if (numberOfRows > 0) {

            if (CmsStringUtil.isNotEmpty(excelWb.getSheetName(i))) {
                // append sheet name to content
                if (i > 0) {
                    result.append("\n\n");
                }
                result.append(excelWb.getSheetName(i).trim());
                result.append(":\n\n");
            }

            Iterator rowIt = sheet.rowIterator();
            while (rowIt.hasNext()) {
                HSSFRow row = (HSSFRow) rowIt.next();
                if (row != null) {
                    boolean hasContent = false;
                    Iterator it = row.cellIterator();
                    while (it.hasNext()) {
                        HSSFCell cell = (HSSFCell) it.next();
                        String text = null;
                        try {
                            switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_BLANK:
                            case HSSFCell.CELL_TYPE_ERROR:
                                // ignore all blank or error cells
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                text = Double.toString(cell.getNumericCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                text = Boolean.toString(cell.getBooleanCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                            default:
                                text = cell.getStringCellValue();
                                break;
                            }
                        } catch (Exception e) {
                            // ignore this cell
                        }
                        if (CmsStringUtil.isNotEmpty(text)) {
                            result.append(text.trim());
                            result.append(' ');
                            hasContent = true;
                        }
                    }
                    if (hasContent) {
                        // append a newline at the end of each row that has content                            
                        result.append('\n');
                    }
                }
            }
        }
    }

    return result.toString();
}

From source file:com.frameworkset.platform.sanylog.util.POIExcelUtil.java

License:Open Source License

/**
 * ?Excel?MapList?Excel??Java./*from   w w w  .  j a v a  2 s .c om*/
 * 
 * @param file
 * @return
 * @throws IOException
 */
public static List<Map<String, Object>> parseHSSFMapList(MultipartFile file) throws IOException {//
    POIFSFileSystem poiFs = new POIFSFileSystem(file.getInputStream());
    HSSFWorkbook wb = new HSSFWorkbook(poiFs);

    HSSFSheet sheet = wb.getSheetAt(0);

    int rowNum = sheet.getLastRowNum();
    HSSFRow titleRow = sheet.getRow(0);

    int colNum = titleRow.getLastCellNum();

    //?17
    List<String> titleList = new ArrayList<String>();
    for (int i = 0; i < colNum; i++) {
        String title = titleRow.getCell(i).getStringCellValue();
        titleList.add(trimTitle(title));
    }

    List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
    for (int i = 1; i <= rowNum; i++) {
        HSSFRow row = sheet.getRow(i);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        for (int j = 0; j < colNum; j++) {
            HSSFCell cell = row.getCell(j);
            if (cell != null) {
                switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC:
                    double d = cell.getNumericCellValue();
                    CellStyle style = cell.getCellStyle();
                    //?
                    if (HSSFDateUtil.isCellDateFormatted(cell) || (style != null
                            && (style.getDataFormat() == 57 || style.getDataFormat() == 58))) {
                        map.put(titleList.get(j), HSSFDateUtil.getJavaDate(d));
                    } else {
                        map.put(titleList.get(j), d);
                    }
                    break;

                default:
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    map.put(titleList.get(j), row.getCell(j).getStringCellValue());
                    break;
                }
            } else {
                map.put(titleList.get(j), null);
            }
        }
        mapList.add(map);
    }

    return mapList;
}

From source file:com.frameworkset.platform.util.POIExcelUtil.java

License:Open Source License

/**
 * ?// ww  w .  j av  a2  s  .  com
 * 
 * @param uploadFileName
 * @return
 *         2015112
 */
public static List<String> getTitlesList(InputStream inputStream) throws Exception {
    // ?excel2003
    POIFSFileSystem poiFs = new POIFSFileSystem(inputStream);
    HSSFWorkbook wb = new HSSFWorkbook(poiFs);

    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow titleRow = sheet.getRow(0);
    int colNum = titleRow.getLastCellNum();

    // ?
    List<String> titleList = new ArrayList<String>();
    for (int i = 0; i < colNum; i++) {
        String title = titleRow.getCell(i).getStringCellValue();
        titleList.add(trimTitle(title));
    }

    return titleList;
}