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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes the underlying POIFSFileSystem from which the Workbook was read, if any.

Usage

From source file:it.cineca.pst.huborcid.service.AbstractFileService.java

License:Open Source License

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void uploadFileOrcid(MultipartFile file, Application application, String typeEntity) throws IOException {
    log.debug(String.format("Method uploadFileOrcid START, file.name=[%s]", file.getOriginalFilename()));

    Integer maxColumn = 0;//from  w w w .j a v a  2s.  c om
    ResultUploadOrcidEntity resultUploadOrcid = new ResultUploadOrcidEntity();
    try {
        resultUploadOrcid.setApplication(application);
        resultUploadOrcid.setFileNameUpload(file.getOriginalFilename());
        resultUploadOrcid.setStatus("PROGRESS");
        resultUploadOrcid.setEntityType(typeEntity);
        resultUploadOrcidEntityRepository.save(resultUploadOrcid);

        OrcidAccessToken orcidAccessToken = new OrcidAccessToken();

        InputStream fileInputStream = new BufferedInputStream(file.getInputStream());
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        HSSFSheet sheet = workbook.getSheetAt(0);

        boolean withErrors = false;
        Iterator<Row> rowIterator = sheet.iterator();
        OrcidOAuthClient clientOrcid = new OrcidOAuthClient(orcidApiType);
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (row.getRowNum() == 0) {
                maxColumn = row.getPhysicalNumberOfCells();
            } else {
                try {
                    String valueCellLocalId = "";
                    String valueCellOrcid = "";
                    Cell cell = row.getCell(0);
                    if (cell != null) {
                        valueCellLocalId = cell.getStringCellValue();
                    }
                    cell = row.getCell(1);
                    if (cell != null) {
                        valueCellOrcid = cell.getStringCellValue();
                    }

                    List<RelPersonApplication> listPersApp = relPersonApplicationRepository
                            .findAllByApplicationIsAndLastIsTrueAndOrcidIsOrLocalIdIs(application,
                                    valueCellOrcid, valueCellLocalId);
                    if (listPersApp.size() == 1) {
                        RelPersonApplication persApp = listPersApp.get(0);
                        orcidAccessToken.setAccess_token(persApp.getOauthAccessToken());
                        orcidAccessToken.setOrcid(persApp.getPerson().getOrcid());

                        createAppendEntity(clientOrcid, orcidAccessToken, sheet, row);

                        writeResultRow(row, maxColumn, "", true);
                    } else if (listPersApp.size() == 0) {
                        writeResultRow(row, maxColumn, "Utente non trovato", false);
                        withErrors = true;
                    } else if (listPersApp.size() > 1) {
                        writeResultRow(row, maxColumn, "Errore di sistema: anagrafiche duplicate", false);
                        withErrors = true;
                    }
                } catch (Exception e) {
                    writeResultRow(row, maxColumn, e.getMessage(), false);
                    withErrors = true;
                }
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        workbook.close();
        byte[] fileResult = baos.toByteArray();
        resultUploadOrcid.setStatus("COMPLETED");
        resultUploadOrcid.setWithErrors(withErrors);
        resultUploadOrcid.setFileResult(fileResult);
        resultUploadOrcidEntityRepository.save(resultUploadOrcid);
    } catch (Exception e) {
        log.debug(String.format("Method uploadFileOrcid, exception=[%s]", e.getMessage()));
        resultUploadOrcid.setStatus("ERROR");
        resultUploadOrcidEntityRepository.save(resultUploadOrcid);
    }

    log.debug("Method uploadFileOrcid END");
}

From source file:it.cineca.pst.huborcid.web.rest.ReportOrcidBioFileResource.java

License:Open Source License

@RequestMapping(value = "/reportOrcidBio/downloadExcel", method = RequestMethod.GET)
@Timed/*from   www.  j a  va  2s  . com*/
public void getExcelOrcidBio(HttpServletResponse response) throws URISyntaxException {
    String currentLogin = SecurityUtils.getCurrentLogin();
    Application application = applicationRepository.findOneByApplicationID(currentLogin);

    Sort sort = new Sort(Sort.Direction.ASC, Arrays.asList("person.firstName", "person.lastName"));
    List<PersonBio> listPersonBio = personBioRepository.findAllPersonByApplicationIsAndLastIsTrue(application,
            sort);

    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Report");

    Object[] headerExcel = new Object[] { "FIRST NAME", "LAST NAME", "LOCAL ID", "ORCID", "BIOGRAPHY",
            "RESEARCHER URLS", "EXTERNAL IDENTIFIERS" };
    Row rowHeader = sheet.createRow(0);
    int cellnumHeader = 0;
    for (Object obj : headerExcel) {
        Cell cell = rowHeader.createCell(cellnumHeader++);
        if (obj instanceof Date)
            cell.setCellValue((Date) obj);
        else if (obj instanceof Boolean)
            cell.setCellValue((Boolean) obj);
        else if (obj instanceof String)
            cell.setCellValue((String) obj);
        else if (obj instanceof Double)
            cell.setCellValue((Double) obj);
    }

    int rownum = 1;
    for (int i = 0; i < listPersonBio.size(); i++) {
        PersonBio personBio = listPersonBio.get(i);
        Row rowData = sheet.createRow(rownum++);
        int cellnumData = 0;

        Cell cell = rowData.createCell(cellnumData++);
        cell.setCellValue(personBio.getPerson().getFirstName());

        cell = rowData.createCell(cellnumData++);
        cell.setCellValue(personBio.getPerson().getLastName());

        cell = rowData.createCell(cellnumData++);
        cell.setCellValue(personBio.getPerson().getLocalID());

        cell = rowData.createCell(cellnumData++);
        cell.setCellValue(personBio.getPerson().getOrcid());

        cell = rowData.createCell(cellnumData++);
        cell.setCellValue(personBio.getBiography());

        cell = rowData.createCell(cellnumData++);
        cell.setCellValue(personBio.getResearcher_urls());

        cell = rowData.createCell(cellnumData++);
        cell.setCellValue(personBio.getExternal_identifiers());
    }

    for (int i = 0; i < headerExcel.length; i++) {
        sheet.autoSizeColumn(i);
    }

    try {
        workbook.write(response.getOutputStream());
        workbook.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.ofbiz.product.spreadsheetimport.ImportProductServices.java

License:Apache License

/**
 * This method is responsible to import spreadsheet data into "Product" and
 * "InventoryItem" entities into database. The method uses the
 * ImportProductHelper class to perform its operation. The method uses "Apache
 * POI" api for importing spreadsheet (xls files) data.
 *
 * Note : Create the spreadsheet directory in the ofbiz home folder and keep
 * your xls files in this folder only./*from  w w w.  java2 s .  com*/
 *
 * @param dctx the dispatch context
 * @param context the context
 * @return the result of the service execution
 * @throws IOException 
 */
public static Map<String, Object> productImportFromSpreadsheet(DispatchContext dctx,
        Map<String, ? extends Object> context) throws IOException {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    // System.getProperty("user.dir") returns the path upto ofbiz home
    // directory
    String path = System.getProperty("user.dir") + "/spreadsheet";
    List<File> fileItems = new LinkedList<File>();

    if (UtilValidate.isNotEmpty(path)) {
        File importDir = new File(path);
        if (importDir.isDirectory() && importDir.canRead()) {
            File[] files = importDir.listFiles();
            // loop for all the containing xls file in the spreadsheet
            // directory
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().toUpperCase().endsWith("XLS")) {
                    fileItems.add(files[i]);
                }
            }
        } else {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "ProductProductImportDirectoryNotFound", locale));
        }
    } else {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource, "ProductProductImportPathNotSpecified", locale));
    }

    if (fileItems.size() < 1) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource, "ProductProductImportPathNoSpreadsheetExists", locale)
                        + path);
    }

    for (File item : fileItems) {
        // read all xls file and create workbook one by one.
        List<Map<String, Object>> products = new LinkedList<Map<String, Object>>();
        List<Map<String, Object>> inventoryItems = new LinkedList<Map<String, Object>>();
        POIFSFileSystem fs = null;
        HSSFWorkbook wb = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(item));
            wb = new HSSFWorkbook(fs);
        } catch (IOException e) {
            Debug.logError("Unable to read or create workbook from file", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                    "ProductProductImportCannotCreateWorkbookFromFile", locale));
        }

        // get first sheet
        HSSFSheet sheet = wb.getSheetAt(0);
        wb.close();
        int sheetLastRowNumber = sheet.getLastRowNum();
        for (int j = 1; j <= sheetLastRowNumber; j++) {
            HSSFRow row = sheet.getRow(j);
            if (row != null) {
                // read productId from first column "sheet column index
                // starts from 0"
                HSSFCell cell2 = row.getCell(2);
                cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
                String productId = cell2.getRichStringCellValue().toString();
                // read QOH from ninth column
                HSSFCell cell5 = row.getCell(5);
                BigDecimal quantityOnHand = BigDecimal.ZERO;
                if (cell5 != null && cell5.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
                    quantityOnHand = new BigDecimal(cell5.getNumericCellValue());

                // check productId if null then skip creating inventory item
                // too.
                boolean productExists = ImportProductHelper.checkProductExists(productId, delegator);

                if (productId != null && !productId.trim().equalsIgnoreCase("") && !productExists) {
                    products.add(ImportProductHelper.prepareProduct(productId));
                    if (quantityOnHand.compareTo(BigDecimal.ZERO) >= 0)
                        inventoryItems.add(ImportProductHelper.prepareInventoryItem(productId, quantityOnHand,
                                delegator.getNextSeqId("InventoryItem")));
                    else
                        inventoryItems.add(ImportProductHelper.prepareInventoryItem(productId, BigDecimal.ZERO,
                                delegator.getNextSeqId("InventoryItem")));
                }
                int rowNum = row.getRowNum() + 1;
                if (row.toString() != null && !row.toString().trim().equalsIgnoreCase("") && productExists) {
                    Debug.logWarning("Row number " + rowNum + " not imported from " + item.getName(), module);
                }
            }
        }
        // create and store values in "Product" and "InventoryItem" entity
        // in database
        for (int j = 0; j < products.size(); j++) {
            GenericValue productGV = delegator.makeValue("Product", products.get(j));
            GenericValue inventoryItemGV = delegator.makeValue("InventoryItem", inventoryItems.get(j));
            if (!ImportProductHelper.checkProductExists(productGV.getString("productId"), delegator)) {
                try {
                    delegator.create(productGV);
                    delegator.create(inventoryItemGV);
                } catch (GenericEntityException e) {
                    Debug.logError("Cannot store product", module);
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                            "ProductProductImportCannotStoreProduct", locale));
                }
            }
        }
        int uploadedProducts = products.size() + 1;
        if (products.size() > 0)
            Debug.logInfo("Uploaded " + uploadedProducts + " products from file " + item.getName(), module);
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.cidte.sii.negocio.XLSWriter.java

public void writeXLS(ArrayList<Writable> list, String directorio, String nombre) {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet(nombre);

    for (int i = 0; i < list.size(); i++) {

        Row row = sheet.createRow(i);/*w  w  w.ja v  a  2 s. c  o m*/
        Writable writ = list.get(i);
        Object[] objArr;
        if (i == 0) {
            // el primero entonces los nombres de las columnas
            objArr = writ.getNames();
        } else {
            objArr = writ.getAsArray();
        }
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            // cell.setCellStyle(CellStyle.ALIGN_FILL);
            if (obj instanceof Date) {
                cell.setCellValue((Date) obj);
            } else if (obj instanceof Boolean) {
                cell.setCellValue((Boolean) obj);
            } else if (obj instanceof String) {
                cell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                cell.setCellValue((Double) obj);
            } else if (obj instanceof Integer) {
                cell.setCellValue((Integer) obj);
            }
        }
    }

    try {
        FileOutputStream out = new FileOutputStream(new File(directorio + nombre + ".xls"));
        workbook.write(out);
        out.close();
        workbook.close();
        System.out.println("Excel written successfully..");

    } catch (FileNotFoundException e) {
        System.out.println("Error " + e);
    } catch (IOException e) {
        System.out.println("Error " + e);
    }
}

From source file:org.neo4art.colour.write.WriteFileCsv.java

License:Apache License

public void savePixel(Color[] c) {
    try {/*from w  ww  .j ava  2  s  .  co m*/
        int i = 0;
        FileInputStream inp = new FileInputStream(csv);
        HSSFWorkbook workbook = new HSSFWorkbook(inp);
        HSSFSheet worksheet = workbook.getSheet("Pixel image");
        while (i < c.length) {
            HSSFRow row = worksheet.createRow(worksheet.getLastRowNum() + 1);
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

            HSSFCell cell1 = row.createCell(0);
            cell1.setCellStyle(cellStyle);
            HSSFCell cell2 = row.createCell(1);
            cell2.setCellStyle(cellStyle);
            HSSFCell cell3 = row.createCell(2);
            cell3.setCellStyle(cellStyle);

            cell1.setCellValue(c[i].getRed());
            cell2.setCellValue(c[i].getGreen());
            cell3.setCellValue(c[i].getBlue());
            FileOutputStream fileOut = new FileOutputStream(csv);
            workbook.write(fileOut);
            i++;
        }
        workbook.close();
    } catch (Exception e) {

    }
}

From source file:org.neo4art.colour.write.WriteFileCsv.java

License:Apache License

public void saveReport(ColourAnalysis image) {
    try {//from w w  w  .  j  a  v  a2 s.c  o m
        Color[] temp = new Color[3];
        FileInputStream inp = new FileInputStream(csv);
        HSSFWorkbook workbook = new HSSFWorkbook(inp);

        HSSFSheet worksheet = workbook.getSheet("Report");
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        HSSFRow row = worksheet.createRow((short) 7);
        HSSFRow row1 = worksheet.createRow((short) 9);
        HSSFRow row3 = worksheet.createRow((short) 11);
        HSSFRow row4 = worksheet.createRow((short) 13);

        HSSFCell cell1 = row.createCell(0);
        cell1.setCellStyle(cellStyle);
        HSSFCell cell3 = row1.createCell(0);
        cell3.setCellStyle(cellStyle);
        HSSFCell cell4 = row3.createCell(0);
        cell4.setCellStyle(cellStyle);
        HSSFCell cell5 = row4.createCell(0);
        cell5.setCellStyle(cellStyle);

        cell1.setCellValue(image.getAverageClosestColour().getName());
        cell3.setCellValue(image.getMaximumClosestColour().getName());
        cell4.setCellValue(image.getMinimumClosestColour().getName());
        cell5.setCellValue(image.getIncrement());

        temp[0] = image.getAverageColour();
        temp[1] = image.getMinimumColour();
        temp[2] = image.getMaximumColour();
        int j = 1;
        for (int i = 0; i < 3; i++) {
            Color c = temp[i];

            HSSFRow row2 = worksheet.createRow((short) j);

            HSSFCell cell1a = row2.createCell(0);
            cell1a.setCellStyle(cellStyle);
            HSSFCell cell2a = row2.createCell(1);
            cell2a.setCellStyle(cellStyle);
            HSSFCell cell3a = row2.createCell(2);
            cell3a.setCellStyle(cellStyle);

            cell1a.setCellValue(c.getRed());
            cell2a.setCellValue(c.getGreen());
            cell3a.setCellValue(c.getBlue());

            FileOutputStream fileOut = new FileOutputStream(csv);
            workbook.write(fileOut);
            workbook.close();
            j = j + 2;
        }

    } catch (Exception e) {

    }
}

From source file:org.neo4art.colour.write.WriteFileCsv.java

License:Apache License

public void createSheet() {
    try {/*w  ww. j  av a2  s .c o m*/
        FileOutputStream fileOut = new FileOutputStream(csv);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet worksheet = workbook.createSheet("Pixel image");
        HSSFRow row1 = worksheet.createRow((short) 0);

        HSSFCell cellA1 = row1.createCell(0);
        HSSFCell cellA2 = row1.createCell(1);
        HSSFCell cellA3 = row1.createCell(2);

        cellA1.setCellValue("RED");
        cellA2.setCellValue("GREEN");
        cellA3.setCellValue("BLUE");

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        HSSFSheet worksheetReport = workbook.createSheet("Report");
        HSSFRow rowReport = worksheetReport.createRow((short) 0);
        HSSFRow rowReport1 = worksheetReport.createRow((short) 2);
        HSSFRow rowReport2 = worksheetReport.createRow((short) 4);
        HSSFRow rowReport3 = worksheetReport.createRow((short) 6);
        HSSFRow rowReport4 = worksheetReport.createRow((short) 8);
        HSSFRow rowReport5 = worksheetReport.createRow((short) 10);
        HSSFRow rowReport6 = worksheetReport.createRow((short) 12);

        worksheetReport.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(2, 2, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(4, 4, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(6, 6, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(7, 7, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(8, 8, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(9, 9, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(10, 10, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(11, 11, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(12, 12, 0, 2));
        worksheetReport.addMergedRegion(new CellRangeAddress(13, 13, 0, 2));

        HSSFCell cellB1 = rowReport.createCell(0);
        cellB1.setCellStyle(cellStyle);
        HSSFCell cellB2 = rowReport1.createCell(0);
        cellB2.setCellStyle(cellStyle);
        HSSFCell cellB3 = rowReport2.createCell(0);
        cellB3.setCellStyle(cellStyle);
        HSSFCell cellB4 = rowReport3.createCell(0);
        cellB4.setCellStyle(cellStyle);
        HSSFCell cellB5 = rowReport4.createCell(0);
        cellB5.setCellStyle(cellStyle);
        HSSFCell cellB6 = rowReport5.createCell(0);
        cellB6.setCellStyle(cellStyle);
        HSSFCell cellB7 = rowReport6.createCell(0);
        cellB7.setCellStyle(cellStyle);

        cellB1.setCellValue("MAX RGB");
        cellB2.setCellValue("MIN RGB");
        cellB3.setCellValue("AVG RGB");
        cellB4.setCellValue("NAME RGB AVG");
        cellB5.setCellValue("NAME RGB MAX");
        cellB6.setCellValue("NAME RGB MIN");
        cellB7.setCellValue("INCREMENT");

        workbook.write(fileOut);
        workbook.close();
        fileOut.flush();
        fileOut.close();
    } catch (Exception e) {

    }
}

From source file:ReadExcel.HSSFReadWrite.java

License:Apache License

/**
 * given a filename this outputs a sample sheet with just a set of
 * rows/cells.//from  w w  w.  ja  v a2 s.c o m
 */
private static void testCreateSampleSheet(String outputFilename) throws IOException {
    int rownum;
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet s = wb.createSheet();
    HSSFCellStyle cs = wb.createCellStyle();
    HSSFCellStyle cs2 = wb.createCellStyle();
    HSSFCellStyle cs3 = wb.createCellStyle();
    HSSFFont f = wb.createFont();
    HSSFFont f2 = wb.createFont();

    f.setFontHeightInPoints((short) 12);
    f.setColor((short) 0xA);
    f.setBold(true);
    f2.setFontHeightInPoints((short) 10);
    f2.setColor((short) 0xf);
    f2.setBold(true);
    cs.setFont(f);
    cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
    cs2.setBorderBottom(BorderStyle.THIN);
    cs2.setFillPattern((short) 1); // fill w fg
    cs2.setFillForegroundColor((short) 0xA);
    cs2.setFont(f2);
    wb.setSheetName(0, "HSSF Test");
    for (rownum = 0; rownum < 300; rownum++) {
        HSSFRow r = s.createRow(rownum);
        if ((rownum % 2) == 0) {
            r.setHeight((short) 0x249);
        }
        for (int cellnum = 0; cellnum < 50; cellnum += 2) {
            HSSFCell c = r.createCell(cellnum);
            c.setCellValue(rownum * 10000 + cellnum + (((double) rownum / 1000) + ((double) cellnum / 10000)));
            if ((rownum % 2) == 0) {
                c.setCellStyle(cs);
            }
            c = r.createCell(cellnum + 1);
            c.setCellValue(new HSSFRichTextString("TEST"));
            // 50 characters divided by 1/20th of a point
            s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05));
            if ((rownum % 2) == 0) {
                c.setCellStyle(cs2);
            }
        }
    }
    // draw a thick black border on the row at the bottom using BLANKS
    rownum++;
    rownum++;
    HSSFRow r = s.createRow(rownum);
    cs3.setBorderBottom(BorderStyle.THICK);
    for (int cellnum = 0; cellnum < 50; cellnum++) {
        HSSFCell c = r.createCell(cellnum);
        c.setCellStyle(cs3);
    }
    s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3));
    s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110));

    // end draw thick black border
    // create a sheet, set its title then delete it
    wb.createSheet();
    wb.setSheetName(1, "DeletedSheet");
    wb.removeSheetAt(1);
    // end deleted sheet
    FileOutputStream out = new FileOutputStream(outputFilename);
    try {
        wb.write(out);
    } finally {
        out.close();
    }
    wb.close();
}

From source file:ReadExcel.HSSFReadWrite.java

License:Apache License

private static void startReadXlsFile(String fileName) {
    try {//w ww .j a  v a 2s  .c  o m
        HSSFWorkbook wb = HSSFReadWrite.readxlsFile(fileName);
        System.out.println("Data dump:\n");
        for (int k = 0; k < wb.getNumberOfSheets(); k++) {
            HSSFSheet sheet = wb.getSheetAt(k);
            int rows = sheet.getPhysicalNumberOfRows();
            System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + " row(s).");
            for (int r = 0; r < rows; r++) {
                HSSFRow row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                int cells = row.getPhysicalNumberOfCells();
                System.out.println("\nROW " + row.getRowNum() + " has " + cells + " cell(s).");
                for (int c = 0; c < cells; c++) {
                    HSSFCell cell = row.getCell(c);
                    String value = null;
                    switch (cell.getCellTypeEnum()) {
                    case FORMULA:
                        value = "FORMULA value=" + cell.getCellFormula();
                        break;
                    case NUMERIC:
                        value = "NUMERIC value=" + cell.getNumericCellValue();
                        break;
                    case STRING:
                        value = "STRING value=" + cell.getStringCellValue();
                        break;
                    default:
                    }
                    System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
                }
            }
        }
        wb.close();

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

From source file:rzd.vivc.documentexamination.service.ReportGeneratorServicePOI.java

@Override
public String generateReportDoc(List<DocumentLine> documentLines, DateFilter dateFilter) {
    InputStream in = null;//from  w w  w  .  j a v a 2s  .  c  o m
    HSSFWorkbook wb = null;
    try {
        in = new FileInputStream("c://Documents/1/reportDoc.xls");
        wb = new HSSFWorkbook(in);
    } catch (IOException ex) {
        Logger.getLogger(ReportGeneratorServicePOI.class.getName()).log(Level.SEVERE, null, ex);
    }
    Sheet sheet = wb.getSheetAt(0);
    Row row = sheet.getRow(0);
    Cell cell = row.getCell(2);
    cell.setCellValue(dateFilter.getFromString());
    cell = row.getCell(4);
    cell.setCellValue(dateFilter.getToString());
    int i = 2;
    for (DocumentLine line : documentLines) {
        Row createRow = sheet.createRow(i++);
        Cell createCell = createRow.createCell(0);
        createCell.setCellValue(line.getName());
        createCell = createRow.createCell(1);
        createCell.setCellValue(line.getNum());
        createCell = createRow.createCell(2);
        createCell.setCellValue(line.getRegistrationDateString());
        createCell = createRow.createCell(3);
        createCell.setCellValue(line.getChecked());
        createCell = createRow.createCell(4);
        createCell.setCellValue(line.getUnchecked());
    }

    String tail = new Date().getTime() + ".xls";
    String addr = "c://Documents/1/reportDoc" + tail;
    File file = new File(addr);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(ReportGeneratorServicePOI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    try {
        wb.write(new FileOutputStream(file));
        wb.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReportGeneratorServicePOI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReportGeneratorServicePOI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "docs/1/reportDoc" + tail;
}