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:apm.common.utils.excel.ImportExcel.java

License:Open Source License

/**
 * /*from   w ww. ja v  a 2 s  .  com*/
 * @param path 
 * @param headerNum ???=?+1
 * @param sheetIndex ?
 * @throws InvalidFormatException 
 * @throws IOException 
 */
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
        throws InvalidFormatException, IOException {
    if (StringUtils.isBlank(fileName)) {
        throw new RuntimeException("?");
    } else if (fileName.toLowerCase().endsWith("xls")) {
        this.wb = new HSSFWorkbook(is);
    } else if (fileName.toLowerCase().endsWith("xlsx")) {
        this.wb = new XSSFWorkbook(is);
    } else {
        throw new RuntimeException("??!");
    }
    if (this.wb.getNumberOfSheets() < sheetIndex) {
        throw new RuntimeException("!");
    }
    this.sheet = this.wb.getSheetAt(sheetIndex);
    this.headerNum = headerNum;
    log.debug("Initialize success.");
}

From source file:at.peppol.commons.tools.MainCreateCodelistsFilesFromExcel.java

License:Mozilla Public License

public static void main(final String[] args) throws IOException, URISyntaxException {
    // Where is the Excel?
    final IReadableResource aXls = new FileSystemResource(EXCEL_FILE);
    if (!aXls.exists())
        throw new IllegalStateException("The Excel file could not be found!");

    // Interprete as Excel
    final Workbook aWB = new HSSFWorkbook(aXls.getInputStream());

    // Check whether all required sheets are present
    final Sheet aParticipantSheet = aWB.getSheet(SHEET_PARTICIPANT);
    if (aParticipantSheet == null)
        throw new IllegalStateException("The " + SHEET_PARTICIPANT + " sheet could not be found!");
    final Sheet aDocumentSheet = aWB.getSheet(SHEET_DOCUMENT);
    if (aDocumentSheet == null)
        throw new IllegalStateException("The " + SHEET_DOCUMENT + " sheet could not be found!");
    final Sheet aProcessSheet = aWB.getSheet(SHEET_PROCESS);
    if (aProcessSheet == null)
        throw new IllegalStateException("The " + SHEET_PROCESS + " sheet could not be found!");

    // Convert participants
    _emitIdentifierIssuingAgency(aParticipantSheet);

    // Convert document identifiers
    _emitDocumentIdentifiers(aDocumentSheet);

    // Convert processes identifiers
    _emitProcessIdentifier(aProcessSheet);

    // Write all Java source files
    final CodeWriter aWriter = new FileCodeWriter(new File("src/main/java"), CCharset.CHARSET_UTF_8);
    s_aCodeModel.build(aWriter);/*  w w  w .  j av  a 2s. c  om*/

    s_aLogger.info("Done creating code");
}

From source file:at.spardat.xma.mdl.grid.GridPOIAdapter.java

License:Open Source License

/**
 * Reads a spreadsheet from an execl file using POI and transfers the data into the <code>IGridWMServer</code>.
 * Only the first sheet in the file is copied.
 *
 * @param grid the XMA model where to copy the data
 * @param in an InputStream containing the excel file
 * @throws SysException if the file could not be read by poi
 * @return a list containing all SysExceptions describing problems with individual cell formulas or ranges
 * @throws SysException if the file could not be read and parsed by poi.
 */// w w w  .  j a  v  a2  s. co  m
public static List poi2xma(IGridWM grid, InputStream in) {
    try {
        POIFSFileSystem fs = new POIFSFileSystem(in);
        HSSFWorkbook book = new HSSFWorkbook(fs);
        List errors = poi2xma(grid, book, 0);
        calcAlignements(grid, book.getSheetAt(0));
        return errors;
    } catch (IOException exc) { // problem dedected by POI and reported in an IOException
        throw new SysException(exc, ((GridWM) grid).getMessage("poiReadError", exc.getMessage()))
                .setCode(GridWM.CODE_poiReadError);
    } catch (Exception exc) { // problem not dedected by POI -> need original exception type
        throw new SysException(exc, ((GridWM) grid).getMessage("poiReadError", exc.toString()))
                .setCode(GridWM.CODE_poiReadError);
    }
}

From source file:attandance.standalone.utils.ExcelUtils.java

public static List<AttandanceRecord> readDataFromExcel(String fileName) {
    List<AttandanceRecord> result = new ArrayList<>();
    try {//w  w w.j  a  va 2  s. co  m
        FileInputStream file = new FileInputStream(new File(fileName));
        //Get the workbook instance for XLS file 
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        //Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);
        //Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        int lineIndex = 1;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            //For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            int columnIndex = 1;
            AttandanceRecord lineBean = new AttandanceRecord();
            //skip header
            if (lineIndex == 1) {
                lineIndex += 1;
                continue;
            }
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                String cellValue = "";
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    cellValue = "" + cell.getBooleanCellValue();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    cellValue = "" + cell.getNumericCellValue();
                    break;
                case Cell.CELL_TYPE_STRING:
                    cellValue = cell.getStringCellValue();
                    break;
                default:
                    cellValue = cell.getStringCellValue();
                }
                lineBean.setAttribute(columnIndex, cellValue);
                columnIndex = columnIndex + 1;
            }
            result.add(lineBean);
        }
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:attendance.CheckIn.java

private static void fileImport() throws IOException {
    //variable assignment
    fileChosen = true;/* ww  w.  j a v  a2  s .co m*/
    chooseError = "";

    //creates filechooser with desktop as default directory
    String userhome = System.getProperty("user.home");
    JFileChooser chooser = new JFileChooser(userhome + "\\Desktop");

    //opens filechooser, assigns choice to status
    int status = chooser.showOpenDialog(null);
    File file = chooser.getSelectedFile();
    filePath = file.getAbsolutePath();

    //if they don't click approve, assume no file chosen
    if (status != JFileChooser.APPROVE_OPTION) {
        //System.out.println("No File Chosen");
        fileChosen = false;
        chooseError = "No File Chosen";
        confirmChoice();
    }

    file1 = new FileInputStream(new File(filePath));

    if (filePath.endsWith(".xls"))
        workbook = new HSSFWorkbook(file1);
    else if (filePath.endsWith(".xlsx"))
        workbook = new XSSFWorkbook(file1);

    for (int i = 0; i < NUM_SHEETS; i++) {
        sheets.add(workbook.getSheetAt(i));
    }
}

From source file:au.gov.ansto.bragg.quokka.experiment.util.ExperimentModelUtils.java

License:Open Source License

public static void refineExperimentFromExcel(Experiment experiment, InputStream input) throws IOException {
    // Sample environment is not supported at this stage
    if (experiment.isControlledEnvironment()) {
        return;//  w w w.j  a  v  a 2 s.co m
    }
    // Clear existing acquisition entries
    experiment.getNormalAcquisition().getEntries().clear();
    // Read from a Excel file
    Workbook workbook = new HSSFWorkbook(input);
    Sheet sheet = workbook.getSheetAt(0);
    // Start from row 3
    for (int i = 2; i < sheet.getLastRowNum(); i++) {
        Row row = sheet.getRow(i);
        int samplePosition = Integer.parseInt(row.getCell(1).getStringCellValue());
        Sample sample = experiment.getSamples().get(samplePosition);
        AcquisitionEntry entry = new AcquisitionEntry(sample);
        experiment.getNormalAcquisition().getEntries().add(entry);
    }
}

From source file:axiom.util.TextExtractor.java

License:Open Source License

public static String msExcelExtractor(InputStream is) throws Exception {
    POIFSFileSystem fs = new POIFSFileSystem(is);
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    StringBuffer sb = new StringBuffer();

    final int numSheets = wb.getNumberOfSheets();
    for (int k = 0; k < numSheets; k++) {
        HSSFSheet sheet = wb.getSheetAt(k);
        Iterator rIt = sheet.rowIterator();
        while (rIt.hasNext()) {
            HSSFRow row = (HSSFRow) rIt.next();
            Iterator cIt = row.cellIterator();
            while (cIt.hasNext()) {
                HSSFCell cell = (HSSFCell) cIt.next();
                sb.append(cell.toString()).append(" ");
            }//from  ww w.jav  a  2  s. c  o  m
        }
    }

    return sb.toString();
}

From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileExcelParser.java

License:Open Source License

public DiveProfile read(File file) throws IOException {
    DiveProfile dp = new DiveProfile();
    Map<Double, Double> depthEntries = new HashMap<Double, Double>();
    Set<Double> ascentWarnings = new HashSet<Double>();
    Set<Double> decoWarnings = new HashSet<Double>();
    Set<Double> remainingBottomTimeWarnings = new HashSet<Double>();
    Set<Double> decoEntries = new HashSet<Double>();

    HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
    HSSFSheet sheet = wb.getSheetAt(0);/*  w  w w .  j av a2s .c  o  m*/

    int rowMax = sheet.getLastRowNum();
    for (int i = 1; i <= rowMax; i++) {
        HSSFRow row = sheet.getRow(i);
        double second = row.getCell(0).getNumericCellValue();
        depthEntries.put(second, row.getCell(1).getNumericCellValue());

        boolean b = row.getCell(2).getBooleanCellValue();
        if (b)
            ascentWarnings.add(second);

        b = row.getCell(3).getBooleanCellValue();
        if (b)
            remainingBottomTimeWarnings.add(second);

        b = row.getCell(4).getBooleanCellValue();
        if (b)
            decoWarnings.add(second);

        b = row.getCell(5).getBooleanCellValue();
        if (b)
            decoEntries.add(second);
    }

    dp.setDepthEntries(depthEntries);

    if (ascentWarnings.size() > 0)
        dp.setAscentWarnings(ascentWarnings);

    if (decoWarnings.size() > 0)
        dp.setDecoCeilingWarnings(decoWarnings);

    if (remainingBottomTimeWarnings.size() > 0)
        dp.setRemainingBottomTimeWarnings(remainingBottomTimeWarnings);

    if (decoEntries.size() > 0)
        dp.setDecoEntries(decoEntries);

    return dp;
}

From source file:biz.ganttproject.impex.csv.XlsReaderImpl.java

License:Open Source License

XlsReaderImpl(InputStream is, List<String> columnHeaders) throws IOException {
    myBook = new HSSFWorkbook(is);
    myHeaders = initializeHeader(columnHeaders);
}

From source file:blueprint.sdk.experimental.util.XlsReader.java

License:Open Source License

/**
 * Opens Migration Plan (*.xls) file//from  ww  w.jav  a2  s . c  om
 *
 * @throws IOException Failed to open or read *.xls file
 */
public void open() throws IOException {
    InputStream input = new FileInputStream(filePath);
    wbook = new HSSFWorkbook(new POIFSFileSystem(input));
    evaluator = new HSSFFormulaEvaluator(wbook);
}