Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt.

Prototype

@Override
public XSSFSheet getSheetAt(int index) 

Source Link

Document

Get the XSSFSheet object at the given index.

Usage

From source file:preprocessing.SkillTextGenerator.java

private static void createCSV(XSSFWorkbook book) {
    Sheet sheet = book.getSheetAt(0);
    Row row;//from   www  . j a  v a 2  s. c  o  m
    Cell cell;
    List<String> csv = new ArrayList<>();
    StringBuilder sb;
    for (int i = 0; i <= sheet.getLastRowNum(); i++) {
        sb = new StringBuilder();
        row = sheet.getRow(i);
        if (row == null) {
            continue;
        }
        for (int j = 0; j < 21; j++) {
            sb.append(getStringCellValue(getNotNullCell(row, j))).append(",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        csv.add(sb.toString());
    }
    try {
        File f = new File(".\\card_data.csv");
        if (f.exists()) {
            f.delete();
        }
        f.createNewFile();
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
        for (String str : csv) {
            br.write(str, 0, str.length());
            br.newLine();
        }
        br.flush();
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:preprocessing.Utils.java

public static int cumpleFormatoExcelRNV(String ruta) {
    InputStream ExcelFileToRead = null;
    try {//  w  ww. j a  va2s.  c om
        //regresa -1 si NO cumpel formato
        // de lo contrario regresa la cantidad de registros que tiene
        ExcelFileToRead = new FileInputStream(ruta);
        XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row;
        XSSFCell cell;
        Iterator rows = sheet.rowIterator();
        row = (XSSFRow) rows.next();
        Iterator cells = row.cellIterator();
        cell = (XSSFCell) cells.next();
        if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING)
            return -1;
        String dh = cell.getStringCellValue();
        dh = dh.toUpperCase();
        if (dh.compareTo("NOMBRE") != 0)
            return -1;
        cell = (XSSFCell) cells.next();
        if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING)
            return -1;
        dh = cell.getStringCellValue();
        dh = dh.toUpperCase();
        if (dh.compareTo("APELLIDOS") != 0)
            return -1;
        cell = (XSSFCell) cells.next();
        if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING)
            return -1;
        dh = cell.getStringCellValue();
        dh = dh.toUpperCase();
        if (dh.compareTo("DNI") != 0)
            return -1;
        cell = (XSSFCell) cells.next();
        if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING)
            return -1;
        dh = cell.getStringCellValue();
        dh = dh.toUpperCase();
        if (dh.compareTo("UBIGEO") != 0)
            return -1;
        cell = (XSSFCell) cells.next();
        if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING)
            return -1;
        dh = cell.getStringCellValue();
        dh = dh.toUpperCase();
        if (!dh.matches("HUELLA.*"))
            return -1;
        cell = (XSSFCell) cells.next();
        if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING)
            return -1;
        dh = cell.getStringCellValue();
        dh = dh.toUpperCase();
        if (!dh.matches("FIRMA.*"))
            return -1;
        int cant = 0;
        while (rows.hasNext()) {
            row = (XSSFRow) rows.next();
            cells = row.cellIterator();
            cell = (XSSFCell) cells.next();
            if (cell.getCellType() != XSSFCell.CELL_TYPE_STRING)
                break;
            cant++;
        }
        return cant;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            ExcelFileToRead.close();
        } catch (IOException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return -1;
}

From source file:pt.webdetails.cda.exporter.PivotXlsExporter.java

License:Open Source License

public void export(final OutputStream out, final TableModel tableModel) throws ExporterException {

    XSSFWorkbook wb;
    InputStream inputStream = null;
    MetadataTableModel table = (MetadataTableModel) tableModel;
    XSSFSheet sheet;//www  . jav a2s . c om

    String pivotAfterColumnName = null;
    String pivotRowGroupColumn = null;
    String[] pivotColumnGroupColumns = null;
    String pivotColumnGroupTitleColumn = null;

    try {
        inputStream = new FileInputStream(templatesDir + templateSettings.get("filename"));
        wb = new XSSFWorkbook(inputStream);
        sheet = wb.getSheetAt(0);
        if (templateSettings.containsKey("PivotAfterColumnName")) {
            pivotAfterColumnName = templateSettings.get("PivotAfterColumnName");
        }
        if (templateSettings.containsKey("PivotCsGroupColumns")) {
            try {
                pivotColumnGroupColumns = templateSettings.get("PivotCsGroupColumns").split(",");
            } catch (Exception ex) {
                throw new ExporterException("PivotCsGroupColumns - illegal value", ex);
            }
        }
        if (templateSettings.containsKey("PivotRowGroupColumn")) {
            pivotRowGroupColumn = templateSettings.get("PivotRowGroupColumn");
        }
        if (templateSettings.containsKey("PivotGroupTitleColumn")) {
            pivotColumnGroupTitleColumn = templateSettings.get("PivotGroupTitleColumn");
        }

        if (pivotAfterColumnName == null || pivotColumnGroupColumns == null || pivotRowGroupColumn == null
                || pivotColumnGroupTitleColumn == null) {
            throw new Exception(
                    "required template settings missing (PivotAfterColumnName,PivotCsGroupColumns,PivotRowGroupColumn,PivotGroupTitleColumn");
        }
    } catch (Exception e) {
        throw new ExporterException("Error at loading TemplateFile", e);
    }

    PivotTableData pivotTableData = retrievePivotTableData(table, pivotRowGroupColumn, pivotAfterColumnName,
            pivotColumnGroupTitleColumn, pivotColumnGroupColumns);
    writePivotColumns(table, sheet, pivotTableData, pivotColumnGroupColumns);
    writePivotRows(sheet, pivotTableData, pivotColumnGroupColumns);

    try {
        wb.write(out);
    } catch (IOException e) {
        throw new ExporterException("IO Exception converting to utf-8", e);
    } finally {
        if (templateSettings.keySet().size() > 0) {
            try {
                inputStream.close();
            } catch (Exception e) {
                throw new ExporterException("Error at closing TemplateFile", e);
            }
        }
    }
}

From source file:punchcardrecords.ui.PunchCardRecordsMainFrame.java

License:Open Source License

/**
 * ?excel(2007+)//from  w ww.  j  av a 2  s .c  om
 * @param excelFile ??Excel
 * @param single ??
 */
private Map<String, double[]> parseExcel42007(File excelFile, boolean single) {
    Map<String, double[]> result = new HashMap<String, double[]>();
    try {
        // ?,?,
        File copyExcelFile = null;
        XSSFWorkbook copyWorkBook = null;
        if (single) {// ??
            addMessage("");
            copyExcelFile = new File(
                    excelFile.getAbsolutePath().substring(0, excelFile.getAbsolutePath().lastIndexOf("\\"))
                            + "/.xlsx");
            FileUtils.copyFile(excelFile, copyExcelFile);
            // 
            copyWorkBook = new XSSFWorkbook(new FileInputStream(copyExcelFile));
        }

        // ?
        XSSFWorkbook workBook = new XSSFWorkbook(new FileInputStream(excelFile));
        XSSFSheet sheet = workBook.getSheetAt(0);
        int rows = sheet.getLastRowNum();
        if (rows >= 6) { // 6,???
            int month = -1; // ?
            int year = -1;// ?
            if (single) {// ??
                // ?3,?
                String dateStr = sheet.getRow(2).getCell(2).getStringCellValue();
                if (StringUtils.isNotBlank(dateStr)) {
                    addMessage("??:" + dateStr);
                    String[] dates = dateStr.split("~");
                    month = Integer.parseInt(dates[0].split("\\/")[1]);// ??
                    year = Integer.parseInt(dates[0].split("\\/")[0]);// ??
                } else {
                    addMessage(
                            "??,??,?");
                }
                // ?,??
                // ,??
                int maxValue = (rows - 6) / 2;
                progressBar.setMaximum(maxValue);
            }
            int days = sheet.getRow(3).getLastCellNum();

            // ?
            SimpleDateFormat punchFormat = new SimpleDateFormat("HH:mm");

            if (single) {// ??
                // ?,,,?
                String[] title = { "", "", "?" };
                if (null != copyWorkBook) {
                    for (int i = 0; i < title.length; i++) {
                        copyWorkBook.getSheetAt(0).getRow(4).createCell(days + i).setCellValue(title[i]);
                        XSSFCellStyle cellStyle = (XSSFCellStyle) copyWorkBook.getSheetAt(0).getRow(4)
                                .getCell(0).getCellStyle().clone();
                        cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                        cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                        copyWorkBook.getSheetAt(0).getRow(4).getCell(days + i).setCellStyle(cellStyle);
                        copyWorkBook.getSheetAt(0).autoSizeColumn((short) (days + i));
                    }
                }
            }

            for (int i = 4; i < rows; i = i + 2) { // 
                //,?,?+2
                String userName = sheet.getRow(i).getCell(10).getStringCellValue();// ??
                String userNum = sheet.getRow(i).getCell(2).getStringCellValue();// ?
                if (single) {// ??
                    addMessage("?:" + userName + "<?:" + userNum + ">");
                    // ??
                    addBar(1);
                }

                // ??,i+1
                XSSFRow recordRow = sheet.getRow(i + 1);

                // 
                double punchDays = 0;
                // (?),?
                double punchHours = 0, avgHours = 0;
                // ???
                for (int j = 0; j < days; j++) {// ???

                    if (single) {// ??
                        // ?,
                        // ?,??,??
                        if (month != -1 && year != -1) {
                            // ???
                            if (isWeekEnd(year, month, j + 1)) {
                                // ,
                                if (null != copyWorkBook) {
                                    XSSFCellStyle weekend = (XSSFCellStyle) copyWorkBook.getSheetAt(0)
                                            .getRow(i + 1).getCell(j).getCellStyle().clone();
                                    weekend.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                                    weekend.setFillForegroundColor(
                                            new XSSFColor(new java.awt.Color(21, 225, 216)));
                                    //weekend.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
                                    copyWorkBook.getSheetAt(0).getRow(i + 1).getCell(j).setCellStyle(weekend);
                                }
                            }
                        }
                    }

                    // ???
                    String record = recordRow.getCell(j).getStringCellValue();// ?
                    if (StringUtils.isNotBlank(record)) {// ??,??
                        String[] records = record.split("\n");
                        // ???,,?
                        if (records.length >= 2) {
                            try {
                                // ?start,?end,?ls,??le
                                Date end = punchFormat.parse(records[records.length - 1]),
                                        start = punchFormat.parse(records[0]);
                                Date ls = punchFormat.parse("11:40"), le = punchFormat.parse("13:00");

                                if (start.after(ls) && end.before(le)) {
                                    // ??,??
                                    if (single) {// ??
                                        // ?,??,??
                                        if (null != copyWorkBook) {
                                            XSSFCellStyle excepitonStyle = (XSSFCellStyle) copyWorkBook
                                                    .getSheetAt(0).getRow(i + 1).getCell(j).getCellStyle()
                                                    .clone();
                                            excepitonStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                                            if (month != -1 && year != -1) {
                                                // ???
                                                if (isWeekEnd(year, month, j + 1)) {
                                                    // ,
                                                    excepitonStyle.setFillForegroundColor(
                                                            IndexedColors.PINK.getIndex());
                                                } else {
                                                    excepitonStyle.setFillForegroundColor(
                                                            IndexedColors.RED.getIndex());
                                                }
                                            }
                                            copyWorkBook.getSheetAt(0).getRow(i + 1).getCell(j)
                                                    .setCellStyle(excepitonStyle);
                                        }
                                    }
                                } else {//???
                                    punchDays = punchDays + 1;
                                    // ?
                                    long ms = end.getTime() - start.getTime();//????

                                    // ??,???,?
                                    long mins = 75 * 60 * 1000;//?75

                                    // ??,???
                                    if (start.before(ls) && end.before(le)) {
                                        // ????
                                        mins = end.getTime() - ls.getTime();
                                    }

                                    // ??,???
                                    if (start.after(ls) && end.after(le)) {
                                        // ???,?:??-?
                                        if (start.before(le)) {
                                            mins = le.getTime() - start.getTime();
                                        } else if (start.after(ls)) { // ???,?0
                                            mins = 0;
                                        }
                                    }

                                    ms = ms - mins;// ??

                                    punchHours = punchHours + (double) ms / (3600 * 1000); // (?)
                                }
                            } catch (ParseException ex) {
                                Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE,
                                        null, ex);
                            }
                        } else {// ?,
                            if (single) {// ??
                                // ?,??,??
                                if (null != copyWorkBook) {
                                    XSSFCellStyle excepitonStyle = (XSSFCellStyle) copyWorkBook.getSheetAt(0)
                                            .getRow(i + 1).getCell(j).getCellStyle().clone();
                                    excepitonStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                                    if (month != -1 && year != -1) {
                                        // ???
                                        if (isWeekEnd(year, month, j + 1)) {
                                            // ,
                                            excepitonStyle
                                                    .setFillForegroundColor(IndexedColors.PINK.getIndex());
                                        } else {
                                            excepitonStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
                                        }
                                    }
                                    copyWorkBook.getSheetAt(0).getRow(i + 1).getCell(j)
                                            .setCellStyle(excepitonStyle);
                                }
                            }
                        }
                    }
                }
                // ?
                if (punchDays > 0) {
                    // ????
                    punchHours = new BigDecimal(punchHours).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    avgHours = new BigDecimal(punchHours / punchDays).setScale(1, BigDecimal.ROUND_HALF_UP)
                            .doubleValue();
                }

                double[] values = { punchDays, punchHours, avgHours };
                result.put(userNum + ":" + userName, values);

                if (single) {// ??
                    addMessage(":" + userName + "<?:" + userNum + ">??,:"
                            + "D:" + punchDays + ",H:" + punchHours + ",AH:" + avgHours);
                    if (null != copyWorkBook) {
                        for (int v = 0; v < values.length; v++) {
                            copyWorkBook.getSheetAt(0).getRow(i + 1).createCell(days + v)
                                    .setCellValue(values[v]);
                            XSSFCellStyle cellStyle = (XSSFCellStyle) copyWorkBook.getSheetAt(0).getRow(i + 1)
                                    .getCell(0).getCellStyle().clone();
                            cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                            cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                            copyWorkBook.getSheetAt(0).getRow(i + 1).getCell(days + v).setCellStyle(cellStyle);
                        }
                    }
                }
            }

            if (single) {// ??
                // ??
                // ,?
                addMessage("?,??");
                if (null != copyWorkBook) {
                    FileOutputStream out = new FileOutputStream(copyExcelFile);
                    copyWorkBook.write(out);
                    out.close();
                }

                // ???,??
                JFileChooser fileSaveChooser = new JFileChooser();

                fileSaveChooser.setDialogTitle("?");
                fileSaveChooser.setSelectedFile(new File(
                        excelFile.getAbsolutePath().substring(0, excelFile.getAbsolutePath().lastIndexOf("."))
                                + "-.xlsx"));
                String[] saveType = { "xlsx" };
                fileSaveChooser.setAcceptAllFileFilterUsed(false);
                fileSaveChooser.setFileFilter(new FileNameExtensionFilter("*.xlsx", saveType));
                int saveResult = fileSaveChooser.showSaveDialog(this);
                if (saveResult == JFileChooser.APPROVE_OPTION) {
                    File saveFile = fileSaveChooser.getSelectedFile();

                    // ???
                    String saveFilePath = saveFile.getAbsolutePath();
                    addMessage("?,??->" + saveFilePath);
                    FileUtils.copyFile(copyExcelFile, saveFile);

                    Object[] options = { "", "",
                            ",?" };
                    int response = JOptionPane.showOptionDialog(this,
                            "??,???", "?",
                            JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (0 == response) {// 
                        // ??
                        addMessage(",??");
                        Desktop.getDesktop().open(saveFile);
                    } else if (1 == response) {// 
                        addMessage(",??");
                        String[] cmd = new String[5];
                        cmd[0] = "cmd";
                        cmd[1] = "/c";
                        cmd[2] = "start";
                        cmd[3] = " ";
                        cmd[4] = saveFile.getAbsolutePath().substring(0,
                                saveFile.getAbsolutePath().lastIndexOf("\\"));
                        Runtime.getRuntime().exec(cmd);
                    } else {
                        alert("??,?()");
                    }
                } else {
                    // ??,?
                    clearMessage();
                    fileName.setText("");
                    // ???
                    addMessage("??");
                }

                // ???
                if (null != copyExcelFile) {
                    copyExcelFile.delete();
                }
            }

        } else {
            // excel???,???????
            alert("????!");
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        alert(",??");
    } catch (IOException | OfficeXmlFileException ex) {
        Logger.getLogger(PunchCardRecordsMainFrame.class.getName()).log(Level.SEVERE, null, ex);
        alert(":" + ex.getMessage());
    }
    return result;
}

From source file:py.gov.datos.XlsToCsvConverter.java

License:GNU General Public License

/**
 * Convierte un nico archivo XLSX a uno o ms archivos CSV.
 *
 * @param file el archivo a convertir./*from  w w  w .j  a v  a2  s  .  c o  m*/
 * @param path la ruta del directorio de salida.
 * @return los archivos generados.
 */
private List<File> convert(File file, String path) {
    List<File> result = new ArrayList<File>();
    try {
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
        File csvDir = new File(path + "csv/");
        csvDir.mkdir();
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            XSSFSheet sheet = workbook.getSheetAt(i);
            File outputFile = new File(path + "csv/" + sheet.getSheetName() + ".csv");
            if (outputFile.createNewFile()) {
                FileOutputStream out = new FileOutputStream(outputFile);
                StringBuffer content = this.convertSheet(sheet);
                //System.out.println(content);
                out.write(content.toString().getBytes());
                result.add(outputFile);
                out.flush();
                out.close();
            } else {
                LOG.error("Can not create output file");
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:rapture.dp.invocable.workflow.ProcessFile.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from w ww  .ja va 2 s  . co m
public String invoke(CallingContext ctx) {
    final int BATCH_LOAD_SIZE = 50; // TODO: move to config
    OPCPackage pkg;
    XSSFWorkbook wb;
    List uris = new ArrayList<>();
    // stores all documents for insertion
    List<List<String>> allDocs = new ArrayList<List<String>>();

    String file = Kernel.getDecision().getContextValue(ctx, getWorkerURI(), "filetoupload");
    String blobUri = Kernel.getDecision().getContextValue(ctx, getWorkerURI(), "blobUri");
    String folderName = Kernel.getDecision().getContextValue(ctx, getWorkerURI(), "folderName");

    String repo = "document://data/" + folderName;
    String docUri = repo + "#id";

    try {
        InputStream is = new ByteArrayInputStream(Kernel.getBlob().getBlob(ctx, blobUri).getContent());
        pkg = OPCPackage.open(is);
        wb = new XSSFWorkbook(pkg);
        XSSFSheet sheet = wb.getSheetAt(0);

        log.info("Loading " + sheet.getPhysicalNumberOfRows() + " rows from " + file + ". Batch size is "
                + BATCH_LOAD_SIZE);

        int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
        int remainder = physicalNumberOfRows % BATCH_LOAD_SIZE;
        int div = physicalNumberOfRows / BATCH_LOAD_SIZE;

        // this only needs to be done once as the uris dont change
        for (int g = 1; g <= BATCH_LOAD_SIZE; g++) {
            uris.add(docUri);
        }
        log.info("created uris list " + uris.size());

        int j = 0;
        int count = 0;
        long startLoadTime = System.currentTimeMillis();
        for (int i = 1; i <= div; i++) {
            List docs = new ArrayList<>();
            // Create a list of documents with size of BATCH_LOAD_SIZE
            for (j = count; j < (BATCH_LOAD_SIZE * i); j++) {
                Row row = sheet.getRow(j);
                Map<String, Object> map = ImmutableMap.of("Row", row.getRowNum(), "DataPeriod",
                        row.getCell(0).toString(), "Industry", row.getCell(3).toString(), "Price",
                        row.getCell(7).toString());
                docs.add(JacksonUtil.jsonFromObject(map));
            }
            allDocs.add(docs);
            count = j;
        }
        long endLoadTime = System.currentTimeMillis();

        ExecutorService executorService = Executors.newCachedThreadPool();
        long startWriteTime = System.currentTimeMillis();
        for (List<String> docList : allDocs) {
            executorService.execute(new InsertData(ctx, docList, uris));
        }
        executorService.shutdown();

        try {
            // TODO: hardcoded timeout.ComparableFutures?
            // Helpful:
            // http://stackoverflow.com/questions/1250643/how-to-wait-for-all-threads-to-finish-using-executorservice
            executorService.awaitTermination(60000L, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            log.error(e.getStackTrace().toString(), e);
            return "error";
        }
        long endWriteTime = System.currentTimeMillis();
        log.info("Completed parallel load.");

        // handle the remaining rows
        if (remainder > 0) {
            long remStartTime = System.currentTimeMillis();
            for (int k = (count); k < (count + remainder); k++) {
                Row row = sheet.getRow(k);
                Map<String, Object> map = ImmutableMap.of("Row", row.getRowNum(), "DataPeriod",
                        row.getCell(0).toString(), "Industry", row.getCell(3).toString(), "Price",
                        row.getCell(7).toString());
                Kernel.getDoc().putDoc(ctx, docUri, JacksonUtil.jsonFromObject(map));
            }
            long remEndTime = System.currentTimeMillis();
            log.info("Remainders took " + (remEndTime - remStartTime) + "ms");
        }

        log.info("Populated uri " + repo + ". Took " + (endLoadTime - startLoadTime) + "ms. to load data. Took "
                + (endWriteTime - startWriteTime) + "ms. to write data.");
        pkg.close();

        Map<String, RaptureFolderInfo> listDocsByUriPrefix = Kernel.getDoc().listDocsByUriPrefix(ctx, repo, 1);
        log.info("Count from repo is " + listDocsByUriPrefix.size());

        if (listDocsByUriPrefix.size() == sheet.getPhysicalNumberOfRows()) {
            return "ok";
        } else {
            return "error"; // TODO: add error step
        }
    } catch (InvalidFormatException | IOException | RaptureException e) {
        log.error("ProcessFile error", e);
        return "error";
    }
}

From source file:ReadExcel.HSSFReadWrite.java

License:Apache License

private static void startReadXlsxFile(String fileName) {
    try {/*  w w w .j a va 2  s  .com*/
        XSSFWorkbook wb = HSSFReadWrite.readxlsxFile(fileName);
        System.out.println("Data dump:\n");
        for (int k = 0; k < wb.getNumberOfSheets(); k++) {
            XSSFSheet 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++) {
                XSSFRow 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++) {
                    XSSFCell 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:regression.data.GenerateData.java

/**
 * Read data from excel/*from   ww w  . jav a 2 s .  c  om*/
 *
 * @param file
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidFormatException
 */
public void readExcelDataSet(File file) throws FileNotFoundException, IOException, InvalidFormatException {
    FileInputStream excelFile = new FileInputStream(file);
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = firstSheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        Cell firstCell = row.getCell(row.getFirstCellNum());
        Cell secondCell = row.getCell(row.getFirstCellNum() + 1);

        if (firstCell.getCellType() == Cell.CELL_TYPE_NUMERIC
                && secondCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            try {
                this.points.add(new Point(firstCell.getNumericCellValue(), secondCell.getNumericCellValue()));
            } catch (Exception e) {
                System.err.println("Cannot convert data in row: " + row.getRowNum());
            }
        }

    }
    this.numberOfInstances = points.size();
}

From source file:regression.data.GenerateData.java

public void createWekaFile(File f) throws FileNotFoundException, IOException, InvalidFormatException {
    FileInputStream excelFile = new FileInputStream(f);
    File wekaFile = new File("weka.arff");
    XSSFWorkbook workbook = new XSSFWorkbook(f);
    XSSFSheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = firstSheet.iterator();
    PrintWriter writer = new PrintWriter(wekaFile);
    writer.println("@RELATION logistic");
    writer.println("@ATTRIBUTE x NUMERIC");
    writer.println("@ATTRIBUTE class {1,0}");
    writer.println("@DATA");
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();/*  w w w. j  a  v a  2  s.c  o  m*/
        Cell firstCell = row.getCell(row.getFirstCellNum());
        Cell secondCell = row.getCell(row.getFirstCellNum() + 1);

        if (firstCell.getCellType() == Cell.CELL_TYPE_NUMERIC
                && secondCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            try {
                writer.println(firstCell.getNumericCellValue() + "," + (int) secondCell.getNumericCellValue());
            } catch (Exception e) {
                System.err.println("Cannot convert data in row: " + row.getRowNum());
            }
        }

    }
    writer.close();
    this.numberOfInstances = points.size();

}

From source file:regression.data.GenerateLinearData.java

/**
 * Read data from excel//from ww  w  .  ja v  a 2  s .c o  m
 *
 * @param file
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidFormatException
 */
public void readExcelDataSet(File file) throws FileNotFoundException, IOException, InvalidFormatException {
    FileInputStream excelFile = new FileInputStream(file);
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = firstSheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        Cell firstCell = row.getCell(row.getFirstCellNum());
        Cell secondCell = row.getCell(row.getFirstCellNum() + 1);
        System.out.println(firstCell.getCellType() + " " + secondCell.getCellType());
        if (firstCell.getCellType() == Cell.CELL_TYPE_NUMERIC
                && secondCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            try {
                this.points.add(new Point(firstCell.getNumericCellValue(), secondCell.getNumericCellValue()));
            } catch (Exception e) {
                System.err.println("Cannot convert data in row: " + row.getRowNum());
            }
        }

    }

}