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:com.duroty.lucene.parser.MSExcelParser.java

License:Open Source License

/**
 * DOCUMENT ME!/*w  ww  . j av a  2 s. co  m*/
 *
 * @return DOCUMENT ME!
 *
 * @throws ParserException DOCUMENT ME!
 */
private String getContents() throws ParserException {
    String contents = "";

    try {
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook workbook = new HSSFWorkbook(fs);
        StringBuffer buffer = new StringBuffer();

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

            Iterator rows = sheet.rowIterator();

            while (rows.hasNext()) {
                HSSFRow row = (HSSFRow) rows.next();

                Iterator 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) {
                            buffer.append(num + " ");
                        }

                        break;

                    case HSSFCell.CELL_TYPE_STRING:

                        String text = cell.getStringCellValue().trim();

                        if (text.length() > 0) {
                            buffer.append(text + " ");
                        }

                        break;
                    }
                }

                buffer.append("\n");

                /*if (sleep > 0) {
                    try {
                        Thread.sleep(sleep);
                    } catch (Exception ex) {
                    }
                }*/
            }
        }

        contents = buffer.toString();
    } catch (Exception ex) {
        throw new ParserException(ex);
    }

    return contents;
}

From source file:com.eastsoft.ui.MainUI.java

License:Open Source License

void savePrintInfoToExcel(recordInfo recordinfor, int printFormat) {
    if (printFormat != 0) {
        HSSFWorkbook wb = null;//from   w  w  w.ja  v  a 2 s. c o  m
        File printRecord = new File("?.xls");
        if (!printRecord.exists()) {

            wb = new HSSFWorkbook();
            HSSFSheet sheet1 = wb.createSheet("sheet1");
            HSSFRow row = sheet1.createRow(0);
            row.createCell((short) 0).setCellValue("?           ");
            row.createCell((short) 1).setCellValue("           ");
            row.createCell((short) 2).setCellValue("??           ");
            row.createCell((short) 3).setCellValue("??           ");
            row.createCell((short) 4).setCellValue("Aid     ");
            row.createCell((short) 5).setCellValue("?            ");

            HSSFRow row1 = sheet1.createRow(sheet1.getLastRowNum() + 1);
            row1.createCell((short) 0).setCellValue(recordinfor.getDate());
            row1.createCell((short) 1).setCellValue(recordinfor.getProductSerialNO());
            row1.createCell((short) 2).setCellValue(recordinfor.getDevice());
            row1.createCell((short) 3).setCellValue(recordinfor.getProduct());
            row1.createCell((short) 4).setCellValue(recordinfor.getAid());
            row1.createCell((short) 5).setCellValue(recordinfor.getPasswd());

        } else {
            FileInputStream fs = null;
            try {
                fs = new FileInputStream(printRecord);
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            POIFSFileSystem ps = null;
            try {
                ps = new POIFSFileSystem(fs);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                wb = new HSSFWorkbook(ps);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            HSSFSheet sheet = wb.getSheetAt(0);
            // ?cell,Rows 0(Create a row and put some cells
            // in
            // it. Rows are 0 based.)
            HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
            row.createCell((short) 0).setCellValue(recordinfor.getDate());
            row.createCell((short) 1).setCellValue(recordinfor.getProductSerialNO());
            row.createCell((short) 2).setCellValue(recordinfor.getDevice());
            row.createCell((short) 3).setCellValue(recordinfor.getProduct());
            row.createCell((short) 4).setCellValue(recordinfor.getAid());
            row.createCell((short) 5).setCellValue(recordinfor.getPasswd());

        }

        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(printRecord);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            appendTextareaText(jTextArea_status,
                    "\n?.xls ??");
            JOptionPane.showMessageDialog(getParent(),
                    "?.xls ??",
                    "?.xls", JOptionPane.WARNING_MESSAGE);
            e.printStackTrace();
        }
        try {
            wb.write(fileOut);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            fileOut.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.eryansky.core.excelTools.JsGridReportBase.java

License:Apache License

/**
 * ??//from w w w .  j  av  a 2  s . co  m
 * 
 * @param
 * @return HashMap<String,HSSFCellStyle>
 */
private HashMap<String, HSSFCellStyle> initStyles(HSSFWorkbook wb) {
    HashMap<String, HSSFCellStyle> ret = new HashMap<String, HSSFCellStyle>();
    try {
        POIFSFileSystem fs = new POIFSFileSystem(getClass().getClassLoader().getResourceAsStream(MODULE_PATH));

        HSSFWorkbook src = new HSSFWorkbook(fs);
        HSSFSheet sheet = src.getSheetAt(0);

        buildStyle(wb, src, sheet, 0, ret, "TITLE");
        buildStyle(wb, src, sheet, 1, ret, "SUB_TITLE");
        buildStyle(wb, src, sheet, 2, ret, "SUB_TITLE2");

        buildStyle(wb, src, sheet, 4, ret, "TABLE_HEADER");
        buildStyle(wb, src, sheet, 5, ret, "STRING");
        buildStyle(wb, src, sheet, 6, ret, "INT");
        buildStyle(wb, src, sheet, 7, ret, "D2");
        buildStyle(wb, src, sheet, 8, ret, "D3");

        buildStyle(wb, src, sheet, 10, ret, "STRING_C");
        buildStyle(wb, src, sheet, 11, ret, "INT_C");
        buildStyle(wb, src, sheet, 12, ret, "D2_C");
        buildStyle(wb, src, sheet, 13, ret, "D3_C");

        buildStyle(wb, src, sheet, 15, ret, "RED_BG");
        buildStyle(wb, src, sheet, 16, ret, "YELLOW_BG");
        buildStyle(wb, src, sheet, 17, ret, "GREEN_BG");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:com.essa.main.ReadExcel.java

public static void main(String[] args) {
    try {// w  w w . j  ava2s  . c o  m

        InputStream input = new BufferedInputStream(new FileInputStream("sample.xls"));
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Iterator rows = sheet.rowIterator();
        while (rows.hasNext()) {
            HSSFRow row = (HSSFRow) rows.next();
            System.out.println("\n");
            Iterator cells = row.cellIterator();
            while (cells.hasNext()) {

                HSSFCell cell = (HSSFCell) cells.next();
                if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType())
                    System.out.print(cell.getNumericCellValue() + "     ");
                else if (HSSFCell.CELL_TYPE_STRING == cell.getCellType())
                    System.out.print(cell.getStringCellValue() + "     ");
                else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType())
                    System.out.print(cell.getBooleanCellValue() + "     ");
                else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType())
                    System.out.print("BLANK     ");
                else
                    System.out.print("Unknown cell type");

            }

        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.etest.view.tq.itemanalysis.FileUploadWindow.java

void readContentFromExcelFile(File excelFile) {
    try {/*from   w w  w. j  a v  a 2s .  co m*/
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(excelFile));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(wb.getActiveSheetIndex());
        HSSFRow row;
        HSSFCell cell;

        boolean stop = false;
        boolean nonBlankRowFound;
        int s;
        HSSFRow lastRow = null;

        while (stop == false) {
            nonBlankRowFound = false;
            lastRow = sheet.getRow(sheet.getLastRowNum());
            for (s = lastRow.getFirstCellNum(); s <= lastRow.getLastCellNum(); s++) {
                cell = lastRow.getCell(s);
                if (cell != null && lastRow.getCell(s).getCellType() != HSSFCell.CELL_TYPE_BLANK) {
                    nonBlankRowFound = true;
                }
            }
            if (nonBlankRowFound == true) {
                stop = true;
            } else {
                sheet.removeRow(lastRow);
            }
        }

        int rows; // No of rows
        rows = sheet.getPhysicalNumberOfRows();

        int cols = 0; // No of columns
        int tmp = 0;

        // This trick ensures that we get the data properly even if it doesn't start from first few rows
        for (int i = 0; i < 10 || i < rows; i++) {
            row = sheet.getRow(i);
            if (row != null) {
                tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                if (tmp > cols)
                    cols = tmp;
            }
        }

        List<ItemAnalysis> itemAnalysisList = new ArrayList<>();
        List<Character> answer;
        ItemAnalysis itemAnalysis = null;

        for (int c = 0; c < cols; c++) {
            itemAnalysis = new ItemAnalysis();
            answer = new ArrayList<>();
            for (int r = 0; r < rows; r++) {
                row = sheet.getRow(r);
                if (row == null || row.toString().isEmpty()) {
                    ShowErrorNotification.error("Remove all blank/empty rows after the last Item!");
                    return;
                } else {
                    //                   if(row != null){
                    cell = row.getCell(c);
                    if (cell == null || cell.toString().isEmpty()) {
                        ShowErrorNotification.error("Remove all blank/empty columns after the last student!");
                        return;
                    } else {
                        //                       if(cell != null){                           
                        if (c != 0) {
                            if (r == 0) {
                                itemAnalysis.setStudentNumber(cell.toString().trim());
                            } else {
                                answer.add(cell.toString().trim().charAt(0));
                            }
                        } else {
                            if (r != 0) {
                                totalItems++;
                            }
                        }
                    }
                }
            }
            if (c != 0) {
                itemAnalysis.setAnswer(answer);
                itemAnalysisList.add(itemAnalysis);
            }
        }

        if (tq.getCellItemIdByTQCoverageId(getTqCoverageId()).size() != totalItems) {
            ShowErrorNotification.error("Total Items do not MATCH!");
            totalItems = 0;
            return;
        }

        studentNoAndTotalScore = new HashMap<>();
        studentNoAndAnswer = new HashMap<>();
        totalItems = 1;
        new Thread() {

            @Override
            public void run() {
                totalData = itemAnalysisList.size();
                for (ItemAnalysis i : itemAnalysisList) {
                    try {
                        Thread.sleep(50);
                        studentNoAndTotalScore.put(i.getStudentNumber(), ItemAnalysisInterpretation
                                .getTotalScoresOfAllStudent(tqCoverageId, i.getAnswer()));
                        studentNoAndAnswer.put(i.getStudentNumber(), i.getAnswer());

                        getUI().access(new Runnable() {

                            @Override
                            public void run() {
                                if (totalItems < itemAnalysisList.size()) {
                                    analyze.setValue("Analyzing data.. "
                                            + CommonUtilities.roundOffToTwoDecimal((current / totalData) * 100)
                                            + "%");
                                    current++;
                                } else {
                                    analyze.setValue("Data analyzed... 100%");
                                    getLowerAndUpperGroupStudent(studentNoAndTotalScore);

                                    HorizontalLayout h = new HorizontalLayout();
                                    h.setWidth("100%");

                                    h.addComponent(viewTableProportion());
                                    h.addComponent(viewStudentsTotalScore());
                                    h.addComponent(approveItemAnalysis());
                                    v.addComponent(h);

                                    v.addComponent(itemAnalysisGridPanel());
                                }
                            }

                        });

                        totalItems++;
                    } catch (InterruptedException ex) {
                        Logger.getLogger(FileUploadWindow.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

        }.start();
        UI.getCurrent().setPollInterval(500);
    } catch (IOException ex) {
        Logger.getLogger(TQItemAnalysisUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.example.minireader.WordViewActivity.java

License:Apache License

private void getRange() {
    FileInputStream in = null;/*from   www  . j a va2s .  com*/
    POIFSFileSystem pfs = null;
    try {
        in = new FileInputStream(nameStr);
        pfs = new POIFSFileSystem(in);
        hwpf = new HWPFDocument(pfs);
    } catch (Exception e) {

    }
    range = hwpf.getRange();
    //
    pictures = hwpf.getPicturesTable().getAllPictures();

    tableIterator = new TableIterator(range);

}

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

License:Apache License

/**
 * Import students form excel//from   ww  w  .j a  v  a  2s  . c  om
 * @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.frameworkset.platform.sanylog.util.POIExcelUtil.java

License:Open Source License

/**
 * ?Excel?MapList?Excel??Java./* w ww . j ava2  s  .  com*/
 * 
 * @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 a va  2  s.co  m
 * 
 * @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;
}

From source file:com.github.camellabs.iot.cloudlet.geofencing.service.DefaultRouteServiceTest.java

License:Apache License

@Test
public void shouldGenerateRoutesReport() throws URISyntaxException, IOException, InterruptedException {
    // Given/*from www.  java2 s  . c o  m*/
    documentDriver.save(collectionName(point1.getClass()), pojoToMap(point1));
    routeService.analyzeRoutes(client);
    String routeId = routeService.routes(client).get(0).getId();
    RouteComment routeComment = new RouteComment(null, routeId, new Date(), "text");
    documentDriver.save(collectionName(routeComment.getClass()), pojoToMap(routeComment));
    URI clientsRequestUri = new URI(restApi + "routes/export/" + client + "/xls");

    // When
    byte[] xls = IOUtils.toByteArray(clientsRequestUri);

    // Then
    HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(new ByteArrayInputStream(xls)));
    String comment = wb.getSheetAt(0).getRow(0).getCell(2).getStringCellValue();
    assertEquals(routeComment.getText(), comment);

}