Example usage for org.apache.poi.ss.usermodel Row getCell

List of usage examples for org.apache.poi.ss.usermodel Row getCell

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Row getCell.

Prototype

Cell getCell(int cellnum);

Source Link

Document

Get the cell representing a given column (logical cell) 0-based.

Usage

From source file:TaskFetcher.java

static HashMap<String, String> fetchActiveTasks(String username, String excel_path) {
    HashMap<String, String> activetasks = new HashMap<String, String>();
    FileInputStream file = null;// w w w  . j a v a 2s  . c  o m
    try {
        file = new FileInputStream(new File(excel_path));
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Create Workbook instance holding reference to .xlsx file
    XSSFWorkbook workbook = null;
    try {
        workbook = new XSSFWorkbook(file);
    } catch (IOException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Get first/desired sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    if (rowIterator.hasNext())
        rowIterator.next(); //skipping the first row of heading
    while (rowIterator.hasNext()) //loop over all entries in the excel sheet
    {
        Row row = rowIterator.next();
        Cell cell = row.getCell(0);
        if (username.equalsIgnoreCase(cell.getStringCellValue())) {
            String task;
            String status;
            String totTimeString = null;
            String latestTimeStamp;
            double totTime;
            task = row.getCell(1).getStringCellValue();
            status = row.getCell(2).getStringCellValue();
            latestTimeStamp = row.getCell(3).getStringCellValue();
            if (status.equalsIgnoreCase("Paused") || status.equalsIgnoreCase("Deferred")) {
                if (row.getCell(4) != null)
                    totTimeString = row.getCell(4).getStringCellValue();
            } else if (status.equalsIgnoreCase("In-Progress")) {
                if (row.getCell(4) != null)
                    totTimeString = row.getCell(4).getStringCellValue();
                if (totTimeString != null) {
                    totTime = Double.parseDouble(totTimeString);
                } else {
                    totTime = 0;
                }
                DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
                Date currentTimestamp = new Date();
                Date latestTimeStampObj = null;
                df.format(currentTimestamp);
                try {
                    latestTimeStampObj = df.parse(latestTimeStamp);
                } catch (ParseException ex) {
                    Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
                }
                long timeDifference = currentTimestamp.getTime() - latestTimeStampObj.getTime();
                long divisor = 60 * 60 * 1000;
                double diffHours = ((double) timeDifference / (double) divisor);
                totTime += diffHours;
                totTimeString = String.valueOf(totTime);
            }
            if (status != null && !status.equalsIgnoreCase("completed") && task != null
                    && totTimeString != null) {
                activetasks.put(task, status + ":" + totTimeString);
            }
        }
    }
    try {
        workbook.close();
    } catch (IOException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    return activetasks;
}

From source file:TaskFetcher.java

static HashMap<String, String> fetchAllTasks(String username, String excel_path) {
    HashMap<String, String> alltasks = new HashMap<String, String>();
    FileInputStream file = null;//from   www. ja  va2  s  .c  om
    try {
        file = new FileInputStream(new File(excel_path));
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Create Workbook instance holding reference to .xlsx file
    XSSFWorkbook workbook = null;
    try {
        workbook = new XSSFWorkbook(file);
    } catch (IOException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Get first sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(1);
    Iterator<Row> rowIterator = sheet.iterator();
    if (rowIterator.hasNext())
        rowIterator.next(); //skipping the first row of heading
    while (rowIterator.hasNext()) //loop over all entries in the excel sheet
    {
        Row row = rowIterator.next();
        Cell cell = row.getCell(0);
        if (username.equalsIgnoreCase(cell.getStringCellValue())) {
            String task;
            String status;
            String timestamp;
            String comments;
            task = row.getCell(1).getStringCellValue();
            status = row.getCell(2).getStringCellValue();
            timestamp = row.getCell(3).getStringCellValue();
            comments = row.getCell(4).getStringCellValue();
            alltasks.put(timestamp, task + ":" + status + ":" + comments);
        }
    }
    try {
        workbook.close();
    } catch (IOException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    return alltasks;
}

From source file:accounts.ExcelUtils.java

License:Apache License

public Map<String, Map<TRId, TR>> processAllSheets(String filename, Map<String, BankAccount> baMap,
        String accountName) throws IOException, DBException {
    Map<String, Map<TRId, TR>> excelTrMap = new TreeMap<>();
    FileInputStream file = new FileInputStream(new File(filename));

    // Get the workbook instance for XLS file
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        XSSFSheet sheet = workbook.getSheetAt(i);
        String sheetName = workbook.getSheetName(i);
        if ("RentalSummary".equalsIgnoreCase(sheetName) || "CompanySummary".equalsIgnoreCase(sheetName)
                || "PersonalSummary".equalsIgnoreCase(sheetName)) {
            continue;
        }//  www  .  j a  v a2 s  .  c o  m
        if (accountName != null && !accountName.equalsIgnoreCase(sheetName)) {
            continue;
        }
        Map<TRId, TR> mapTr = new HashMap<>();
        excelTrMap.put(sheetName, mapTr);
        System.out.println("Processing sheet: " + sheetName);
        BankAccount ba = baMap.get(sheetName);
        if (ba == null) {
            throw new IOException("Unknown bank account name in excel=" + sheetName);
        }

        for (int rownum = 1; rownum <= sheet.getLastRowNum(); rownum++) {
            Row row = sheet.getRow(rownum);

            // Get iterator to all cells of current row

            TR tr = DBFactory.inst().createCorrespondingTRObj(ba);
            tr.setDate(row.getCell(0).getDateCellValue());
            tr.setDescription(row.getCell(1).getStringCellValue());
            tr.setDebit((float) row.getCell(2).getNumericCellValue());
            tr.setComment(row.getCell(3).getStringCellValue());
            tr.setTrType(row.getCell(4).getStringCellValue());
            tr.setTaxCategory(row.getCell(5).getStringCellValue());
            tr.setProperty(row.getCell(6).getStringCellValue());
            tr.setOtherEntity(row.getCell(7).getStringCellValue());
            String locked = row.getCell(8).getStringCellValue();
            tr.setLocked("YES".equalsIgnoreCase(locked));
            tr.setTrId();
            mapTr.put(tr.getTrId(), tr);

        }
    }
    return excelTrMap;

}

From source file:accounts.ExcelUtils.java

License:Apache License

public Map<String, Map<TRId, TR>> processAllSheets(String filename) throws IOException {
    Map<String, Map<TRId, TR>> excelTrMap = new TreeMap<>();
    FileInputStream file = new FileInputStream(new File(filename));

    // Get the workbook instance for XLS file
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        XSSFSheet sheet = workbook.getSheetAt(i);
        String sheetName = workbook.getSheetName(i);
        Map<TRId, TR> mapTr = new HashMap<>();
        excelTrMap.put(sheetName, mapTr);
        System.out.println("Processing sheet: " + sheetName);

        // Get iterator to all the rows in current sheet
        Iterator<Row> rowIterator = sheet.iterator();

        for (int rownum = 1; rownum <= sheet.getLastRowNum(); rownum++) {
            Row row = sheet.getRow(rownum);

            // Get iterator to all cells of current row

            TR tr = new TRNonDB();
            tr.setDate(row.getCell(0).getDateCellValue());
            tr.setDescription(row.getCell(1).getStringCellValue());
            tr.setDebit((float) row.getCell(2).getNumericCellValue());
            tr.setComment(row.getCell(3).getStringCellValue());
            tr.setTrType(row.getCell(4).getStringCellValue());
            tr.setTaxCategory(row.getCell(5).getStringCellValue());
            tr.setProperty(row.getCell(6).getStringCellValue());
            tr.setOtherEntity(row.getCell(7).getStringCellValue());
            String lockedStr = row.getCell(7).getStringCellValue();
            if ("YES".equalsIgnoreCase(lockedStr) || "TRUE".equalsIgnoreCase(lockedStr)) {
                tr.setLocked(true);//from   ww  w  .  j a va 2s .c  o m
            }
            tr.setTrId();
            mapTr.put(tr.getTrId(), tr);

        }
    }
    return excelTrMap;

}

From source file:aco.Utilities.java

License:Open Source License

static void writeInputDataPoints() {
    //the file already exists
    if (new File(filePath3).canRead()) {
        //System.out.println("File already exists..");
        try {//from  www .j  ava2s . c  o m
            FileInputStream file = new FileInputStream(new File(filePath3));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook1 = new XSSFWorkbook(file);

            //Get first/desired sheet from the workbook
            XSSFSheet sheet1 = workbook1.getSheetAt(11);

            //define a cell style for bold font
            CellStyle style = workbook1.createCellStyle();
            Font font = workbook1.createFont();
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            style.setFont(font);

            Row r1 = sheet1.getRow(0);
            if (r1 == null) {
                // First cell in the row, create
                r1 = sheet1.createRow(0);
            }

            Cell c = r1.getCell(0);
            if (c == null) {
                c = r1.createCell(0);
            }
            c.setCellValue("VRPTW instance - " + VRPTW.instance.name
                    + "; data point coordinates corresponding to customers' requests");
            c.setCellStyle(style);

            Row r = sheet1.getRow(2);
            if (r == null) {
                // First cell in the row, create
                r = sheet1.createRow(2);
            }

            Cell c1 = r.getCell(0);
            if (c1 == null) {
                c1 = r.createCell(0);
            }
            c1.setCellValue("Point #");
            c1.setCellStyle(style);

            c1 = r.getCell(1);
            if (c1 == null) {
                c1 = r.createCell(1);
            }
            c1.setCellValue("X Coord");
            c1.setCellStyle(style);

            c1 = r.getCell(2);
            if (c1 == null) {
                c1 = r.createCell(2);
            }
            c1.setCellValue("Y Coord");
            c1.setCellStyle(style);

            int size = VRPTW.instance.nodes.length;
            int rowIndex = 3;
            double x, y;
            for (int i = 0; i < size; i++) {
                x = VRPTW.instance.nodes[i].x;
                y = VRPTW.instance.nodes[i].y;
                r = sheet1.getRow(rowIndex + i);
                if (r == null) {
                    // First cell in the row, create
                    //System.out.println("Empty row, create new one");
                    r = sheet1.createRow(rowIndex + i);
                }

                c1 = r.getCell(0);
                if (c1 == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c1 = r.createCell(0);
                }
                c1.setCellValue(i);

                c1 = r.getCell(1);
                if (c1 == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c1 = r.createCell(1);
                }
                c1.setCellValue(x);

                c1 = r.getCell(2);
                if (c1 == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c1 = r.createCell(2);
                }
                c1.setCellValue(y);

            }

            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File(filePath3));
            workbook1.write(out);
            out.close();

            //System.out.println("Written successfully on disk.");
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        System.out.println("File not exists..");
    }
}

From source file:aco.Utilities.java

License:Open Source License

static void writeResultsExcel(int trialNumber, boolean saveIterCosts) {
    Row r, r1;
    Cell c;//from  w  w w . j av  a  2s  .co m
    int index1 = 0, index2 = 0, index3 = 0, index4 = 0, index5 = 0;
    //int index6 = 0;

    //the file already exists; we should add a new row as the last one in the Excel file
    if (new File(filePath).canRead()) {
        //System.out.println("File already exists..");
        try {
            FileInputStream file = new FileInputStream(new File(filePath));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook1 = new XSSFWorkbook(file);

            int startIndex = 0, rowIndex = 0;
            /*switch (VRPTW.m) {
               case 2: 
             startIndex = 0;
             rowIndex = 4;
             break;
               case 3: 
             startIndex = 2;
             rowIndex = 5;
             break;
               case 5: 
             startIndex = 4;
             rowIndex = 7;
             break;
               case 7: 
             startIndex = 6;
             rowIndex = 9;
             break;
               default:
             System.out.println("Unknown value for m");
             break;         
            }*/

            //Get desired sheet from the workbook
            XSSFSheet sheet1 = workbook1.getSheetAt(startIndex); //for tours
            /*XSSFSheet sheet2 = workbook1.getSheetAt(startIndex + 1);  //for number of assigned cities
            XSSFSheet sheet3 = workbook1.getSheetAt(startIndex + 2);  //for cost of individual subtours
            XSSFSheet sheet4 = workbook1.getSheetAt(startIndex + 3);  //for total cost of subtours
            XSSFSheet sheet5 = workbook1.getSheetAt(startIndex + 4);  //for verbose output of total cost at each 5 iteration
            */
            XSSFSheet sheet2 = workbook1.getSheetAt(startIndex + 1); //for verbose output of longest cost at each 5 iteration

            //define a cell style for bold font
            CellStyle style = workbook1.createCellStyle();
            Font font = workbook1.createFont();
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            style.setFont(font);

            //define style with bold font and blue color for font
            CellStyle styleBoldBlue = workbook1.createCellStyle();
            font = workbook1.createFont();
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            font.setColor(IndexedColors.BLUE.index);
            styleBoldBlue.setFont(font);

            index1 = 133;
            if (!saveIterCosts) {
                //write only once the name of the algorithm that was run
                if (trialNumber == 0) {
                    r = sheet1.getRow(index1);
                    if (r == null) {
                        // First cell in the row, create
                        //System.out.println("Empty row, create new one");
                        r = sheet1.createRow(index1);
                    }

                    c = r.getCell(0);
                    if (c == null) {
                        // New cell
                        //System.out.println("Empty cell, create new one");
                        c = r.createCell(0);
                    }
                    c.setCellValue(
                            "Obtained solutions (values) after running new version (ACS MinMax global, voiajor si oras alesi simultan) with local search");
                    c.setCellStyle(styleBoldBlue);
                }

                //write only once the table header
                index1 = index1 + 3;
                r = sheet1.getRow(index1);
                if (r == null) {
                    // First cell in the row, create
                    //System.out.println("Empty row, create new one");
                    r = sheet1.createRow(index1);
                }

                c = r.getCell(0);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(0);
                }
                c.setCellValue("Run #");
                c.setCellStyle(style);

                c = r.getCell(1);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(1);
                }
                c.setCellValue("MinMax (cost of longest subtour)");
                c.setCellStyle(style);

                c = r.getCell(2);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(2);
                }
                c.setCellValue("Total Cost");
                c.setCellStyle(style);

                c = r.getCell(3);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(3);
                }
                c.setCellValue("Amplitude");
                c.setCellStyle(style);

                //write number of run
                index1 = 137 + trialNumber;
                r = sheet1.getRow(index1);
                if (r == null) {
                    // First cell in the row, create
                    //System.out.println("Empty row, create new one");
                    r = sheet1.createRow(index1);
                }

                c = r.getCell(0);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(0);
                }
                c.setCellValue(trialNumber + 1);

                //write MinMax (cost of longest subtour)
                double longestSubtour = getLongestSubtour();
                c = r.getCell(1);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(1);
                }
                c.setCellValue(longestSubtour);

                //write total cost
                double totalCost = getTotalCost();
                c = r.getCell(2);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(2);
                }
                c.setCellValue(totalCost);

                //write amplitude
                double amplitude = getAmplitude();
                c = r.getCell(3);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(3);
                }
                c.setCellValue(amplitude);
            }

            index5 = 859;
            if (saveIterCosts) {
                //write only once the name of the algorithm that was run
                if (trialNumber == 0) {
                    r = sheet2.getRow(index5);
                    if (r == null) {
                        // First cell in the row, create
                        //System.out.println("Empty row, create new one");
                        r = sheet2.createRow(index5);
                    }

                    c = r.getCell(0);
                    if (c == null) {
                        // New cell
                        //System.out.println("Empty cell, create new one");
                        c = r.createCell(0);
                    }
                    c.setCellValue(
                            "Longest cost of subtour at each 5 iteration after running new version (ACS MinMax global, voiajor si oras alesi simultan) with local search");
                    c.setCellStyle(styleBoldBlue);

                    int tempIndex = index5 + 3;
                    r = sheet2.getRow(tempIndex);
                    if (r == null) {
                        // First cell in the row, create
                        //System.out.println("Empty row, create new one");
                        r = sheet2.createRow(tempIndex);
                    }
                    ArrayList<Integer> iterNumber = getIterNumber();

                    c = r.getCell(0);
                    if (c == null) {
                        // New cell
                        //System.out.println("Empty cell, create new one");
                        c = r.createCell(0);
                    }
                    c.setCellValue("Nr Iter");
                    c.setCellStyle(style);

                    int indexTemp = 0;
                    for (int j = 0; j < iterNumber.size(); j++) {
                        indexTemp = tempIndex + 1 + j;
                        r1 = sheet2.getRow(indexTemp);
                        if (r1 == null) {
                            // First cell in the row, create
                            //System.out.println("Empty row, create new one");
                            r1 = sheet2.createRow(indexTemp);
                        }

                        c = r1.getCell(0);
                        if (c == null) {
                            // New cell
                            //System.out.println("Empty cell, create new one");
                            c = r1.createCell(0);
                        }
                        c.setCellValue(iterNumber.get(j));
                    }
                }

                index5 = index5 + 3;
                r = sheet2.getRow(index5);
                if (r == null) {
                    // First cell in the row, create
                    //System.out.println("Empty row, create new one");
                    r = sheet2.createRow(index5);
                }

                //for each trial run save at each 5 iteration the best longest cost of a subtour so far
                ArrayList<Double> iterLongestCost = getIterLongestCost();
                int index;

                //for each run write the table header cell
                c = r.getCell(trialNumber + 1);
                if (c == null) {
                    // New cell
                    //System.out.println("Empty cell, create new one");
                    c = r.createCell(trialNumber + 1);
                }
                c.setCellValue("Run " + (trialNumber + 1));
                c.setCellStyle(style);

                for (int j = 0; j < iterLongestCost.size(); j++) {
                    index = index5 + 1 + j;
                    r1 = sheet2.getRow(index);
                    if (r1 == null) {
                        // First cell in the row, create
                        //System.out.println("Empty row, create new one");
                        r1 = sheet2.createRow(index);
                    }

                    c = r1.getCell(trialNumber + 1);
                    if (c == null) {
                        // New cell
                        //System.out.println("Empty cell, create new one");
                        c = r1.createCell(trialNumber + 1);
                    }
                    c.setCellValue(iterLongestCost.get(j));
                }
            }

            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File(filePath));
            workbook1.write(out);
            out.close();

            int nrOfRun = trialNumber + 1;
            System.out.println("\nRun #" + nrOfRun + " written successfully on disk.\n");
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        //Blank workbook
        System.out.println("File " + filePath + " doesn't exists..");

    }
}

From source file:aco.Utilities.java

License:Open Source License

static void writeParetoSet(ArrayList<Ant> bestSoFarPareto, int trial) {
    Row r;
    Cell c;//from www.j  a  va2s  .com
    int lineNumber = 0;

    //filePath1 += InOut.max_iterations + " iter (ACO MinMax_vers noua).xlsx";
    //System.out.println("file path=" + filePath1);

    //the file already exists; we should add a new row as the last one in the Excel file
    if (new File(filePath1).canRead()) {
        //System.out.println("File already exists..");
        try {
            FileInputStream file = new FileInputStream(new File(filePath1));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook1 = new XSSFWorkbook(file);

            //Get first/desired sheet from the workbook
            XSSFSheet sheet1 = workbook1.getSheetAt(trial);

            //write table header cells
            r = sheet1.getRow(lineNumber);
            if (r == null) {
                // First cell in the row, create
                r = sheet1.createRow(lineNumber);
            }
            c = r.getCell(0);
            if (c == null) {
                // New cell
                c = r.createCell(0);
            }
            c.setCellValue("Point #");
            c = r.getCell(1);
            if (c == null) {
                // New cell
                c = r.createCell(1);
            }
            c.setCellValue("Total tours length");
            c = r.getCell(2);
            if (c == null) {
                // New cell
                c = r.createCell(2);
            }
            c.setCellValue("Amplitude of tours");
            c = r.getCell(3);
            if (c == null) {
                // New cell
                c = r.createCell(3);
            }
            c.setCellValue("List with cost of subtours");

            lineNumber++;
            for (int i = 0; i < bestSoFarPareto.size(); i++) {
                r = sheet1.getRow(i + lineNumber);
                if (r == null) {
                    // First cell in the row, create
                    r = sheet1.createRow(i + lineNumber);
                }
                //write point id
                c = r.getCell(0);
                if (c == null) {
                    // New cell
                    c = r.createCell(0, Cell.CELL_TYPE_NUMERIC);
                }
                c.setCellValue(i + 1);
                //write total cost and amplitude
                for (int indexObj = 0; indexObj < 2; indexObj++) {
                    c = r.getCell(indexObj + 1);
                    if (c == null) {
                        // New cell
                        c = r.createCell(indexObj + 1, Cell.CELL_TYPE_NUMERIC);
                    }
                    c.setCellValue(bestSoFarPareto.get(i).costObjectives[indexObj]);
                }
                //write cost of each individual subtour
                for (int j = 0; j < bestSoFarPareto.get(i).tour_lengths.size(); j++) {
                    c = r.getCell(j + 3);
                    if (c == null) {
                        // New cell
                        c = r.createCell(j + 3);
                    }
                    c.setCellValue(bestSoFarPareto.get(i).tour_lengths.get(j));
                }
            }

            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File(filePath1));
            workbook1.write(out);
            out.close();

            //System.out.println("\nWritten Pareto front points successfully on disk.\n");
            int nrOfRun = trial + 1;
            System.out.println("\nRun #" + nrOfRun + " written Pareto front points successfully on disk.\n");
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        System.out.println(" File " + filePath1 + " doesn't exists");
    }

}

From source file:aco.Utilities.java

License:Open Source License

static void writeExcelFinalSolution(int trial, double scalledValue) {
    Row r;
    Cell c;/*w w w  . ja v a  2 s .c  o m*/
    int index1 = 0;

    //the file already exists; we should add a new row as the last one in the Excel file
    if (new File(filePath5).canRead()) {
        //System.out.println("File already exists..");
        try {
            FileInputStream file = new FileInputStream(new File(filePath5));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook1 = new XSSFWorkbook(file);

            //Get desired sheet from the workbook
            XSSFSheet sheet1 = workbook1.getSheetAt(0);

            //define a cell style for bold font
            CellStyle style = workbook1.createCellStyle();
            Font font = workbook1.createFont();
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            style.setFont(font);

            //define style with bold font and blue color for font
            CellStyle styleBoldBlue = workbook1.createCellStyle();
            font = workbook1.createFont();
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            font.setColor(IndexedColors.BLUE.index);
            styleBoldBlue.setFont(font);

            index1 = 8; //8  //26

            index1 = index1 + trial;
            r = sheet1.getRow(index1);
            if (r == null) {
                // First cell in the row, create
                //System.out.println("Empty row, create new one");
                r = sheet1.createRow(index1);
            }

            int nrOfRun = trial + 1;
            //write trial number (Run #)
            c = r.getCell(15);
            if (c == null) {
                // New cell
                //System.out.println("Empty cell, create new one");
                c = r.createCell(15);
            }
            c.setCellValue(nrOfRun);

            //write number of used vehicles
            c = r.getCell(16);
            if (c == null) {
                // New cell
                //System.out.println("Empty cell, create new one");
                c = r.createCell(16);
            }
            c.setCellValue(Ants.best_so_far_ant.usedVehicles);

            //write total traveled distance
            c = r.getCell(17);
            if (c == null) {
                // New cell
                //System.out.println("Empty cell, create new one");
                c = r.createCell(17);
            }
            c.setCellValue(scalledValue);

            //write the total number of feasible solutions
            c = r.getCell(18);
            if (c == null) {
                // New cell
                //System.out.println("Empty cell, create new one");
                c = r.createCell(18);
            }
            c.setCellValue(InOut.noSolutions);

            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File(filePath5));
            workbook1.write(out);
            out.close();

            System.out.println("\nRun #" + nrOfRun + " written successfully on disk.\n");
        }

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

    } else {
        //Blank workbook
        System.out.println("File " + filePath5 + " doesn't exists..");

    }
}

From source file:Actionclasses.ReadExcel.java

public ReadExcel(String filePath) {
    filelocation = filePath;/*  w  w w.  j  a  va 2 s.  c om*/
    try {
        FileInputStream file = new FileInputStream(new File(filelocation));
        //new workbook is created
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        //new sheet is created
        XSSFSheet sheet = workbook.getSheetAt(0);
        /*rowIterator - Returns an iterator of the physical rows
           iterator - Alias for rowIterator() to allow foreach loops
        So basically they return the same values, but the second was added 
        to support Java's for-each loop. In other words, instead of getting the iterator
        and running while loop, you could directly run for-each loop, which makes code 
        shorter and more readable
                     */
        //Creating random table
        Insert();
        //loop for iterate in each row
        for (Row row : sheet) {
            //List list=new ArrayList();
            //loop for iterate in each cell in a particular row
            for (Cell cell : row) {
                cell.setCellType(CELL_TYPE_STRING);
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.println("boolean===>>>\"+cell.getBooleanCellValue() + \"\\t");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    break;
                case Cell.CELL_TYPE_STRING:
                    //list.add(cell.getStringCellValue());
                    System.out.println(cell.getStringCellValue());
                    break;
                }
            }
            String Name = row.getCell(0).getStringCellValue();
            String Emailid = row.getCell(1).getStringCellValue();
            System.out.println(Name + " " + Emailid);
            Insertindb(Name, Emailid);
        }
        //file.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReadExcel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReadExcel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:adams.data.io.input.ExcelSpreadSheetReader.java

License:Open Source License

/**
 * Reads the spreadsheet content from the specified file.
 *
 * @param in      the input stream to read from
 * @return      the spreadsheets or null in case of an error
 *///from www  .j a v a 2s  . c  o  m
@Override
protected List<SpreadSheet> doReadRange(InputStream in) {
    List<SpreadSheet> result;
    int[] indices;
    Workbook workbook;
    Sheet sheet;
    SpreadSheet spsheet;
    Row exRow;
    Cell exCell;
    adams.data.spreadsheet.Row spRow;
    int i;
    int n;
    int cellType;
    DateFormat dformat;
    boolean numeric;
    int dataRowStart;
    int firstRow;
    int lastRow;
    List<String> header;

    result = new ArrayList<>();

    workbook = null;
    dformat = DateUtils.getTimestampFormatter();
    try {
        workbook = WorkbookFactory.create(in);
        m_SheetRange.setMax(workbook.getNumberOfSheets());
        indices = m_SheetRange.getIntIndices();
        firstRow = m_FirstRow - 1;
        dataRowStart = getNoHeader() ? firstRow : firstRow + 1;
        for (int index : indices) {
            if (m_Stopped)
                break;

            spsheet = m_SpreadSheetType.newInstance();
            spsheet.setDataRowClass(m_DataRowType.getClass());
            result.add(spsheet);

            if (isLoggingEnabled())
                getLogger().info("sheet: " + (index + 1));

            sheet = workbook.getSheetAt(index);
            if (sheet.getLastRowNum() == 0) {
                getLogger().severe("No rows in sheet #" + index);
                return null;
            }
            spsheet.setName(sheet.getSheetName());

            // header
            if (isLoggingEnabled())
                getLogger().info("header row");
            exRow = sheet.getRow(firstRow);
            if (exRow == null) {
                getLogger().warning("No data in sheet #" + (index + 1) + "?");
            } else if (exRow != null) {
                spRow = spsheet.getHeaderRow();
                m_TextColumns.setMax(exRow.getLastCellNum());
                if (getNoHeader()) {
                    header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                    for (i = 0; i < header.size(); i++)
                        spRow.addCell("" + (i + 1)).setContent(header.get(i));
                } else {
                    if (!m_CustomColumnHeaders.trim().isEmpty()) {
                        header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                        for (i = 0; i < header.size(); i++)
                            spRow.addCell("" + (i + 1)).setContent(header.get(i));
                    } else {
                        for (i = 0; i < exRow.getLastCellNum(); i++) {
                            if (m_Stopped)
                                break;
                            exCell = exRow.getCell(i);
                            if (exCell == null) {
                                spRow.addCell("" + (i + 1)).setMissing();
                                continue;
                            }
                            numeric = !m_TextColumns.isInRange(i);
                            switch (exCell.getCellType()) {
                            case Cell.CELL_TYPE_BLANK:
                            case Cell.CELL_TYPE_ERROR:
                                spRow.addCell("" + (i + 1)).setContent("column-" + (i + 1));
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(exCell))
                                    spRow.addCell("" + (i + 1)).setContent(new DateTime(
                                            HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                                else if (numeric)
                                    spRow.addCell("" + (i + 1)).setContent(exCell.getNumericCellValue());
                                else
                                    spRow.addCell("" + (i + 1)).setContentAsString(numericToString(exCell));
                                break;
                            default:
                                spRow.addCell("" + (i + 1)).setContentAsString(exCell.getStringCellValue());
                            }
                        }
                    }
                }
            }

            // data
            if (spsheet.getColumnCount() > 0) {
                if (m_NumRows < 1)
                    lastRow = sheet.getLastRowNum();
                else
                    lastRow = Math.min(firstRow + m_NumRows - 1, sheet.getLastRowNum());
                for (i = dataRowStart; i <= lastRow; i++) {
                    if (m_Stopped)
                        break;
                    if (isLoggingEnabled())
                        getLogger().info("data row: " + (i + 1));
                    spRow = spsheet.addRow("" + spsheet.getRowCount());
                    exRow = sheet.getRow(i);
                    if (exRow == null)
                        continue;
                    for (n = 0; n < exRow.getLastCellNum(); n++) {
                        // too few columns in header?
                        if ((n >= spsheet.getHeaderRow().getCellCount()) && m_AutoExtendHeader)
                            spsheet.insertColumn(spsheet.getColumnCount(), "");

                        m_TextColumns.setMax(spsheet.getHeaderRow().getCellCount());
                        exCell = exRow.getCell(n);
                        if (exCell == null) {
                            spRow.addCell(n).setMissing();
                            continue;
                        }
                        cellType = exCell.getCellType();
                        if (cellType == Cell.CELL_TYPE_FORMULA)
                            cellType = exCell.getCachedFormulaResultType();
                        numeric = !m_TextColumns.isInRange(n);
                        switch (cellType) {
                        case Cell.CELL_TYPE_BLANK:
                        case Cell.CELL_TYPE_ERROR:
                            if (m_MissingValue.isEmpty())
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContent("");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(exCell))
                                spRow.addCell(n).setContent(
                                        dformat.format(HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                            else if (numeric)
                                spRow.addCell(n).setContent(exCell.getNumericCellValue());
                            else
                                spRow.addCell(n).setContentAsString(numericToString(exCell));
                            break;
                        default:
                            if (m_MissingValue.isMatch(exCell.getStringCellValue()))
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContentAsString(exCell.getStringCellValue());
                        }
                    }
                }
            }
        }
    } catch (Exception ioe) {
        getLogger().log(Level.SEVERE, "Failed to read range '" + m_SheetRange + "':", ioe);
        result = null;
        m_LastError = "Failed to read range '" + m_SheetRange + "' from stream!\n"
                + Utils.throwableToString(ioe);
    }

    return result;
}