Example usage for org.apache.poi.ss.usermodel Cell setCellStyle

List of usage examples for org.apache.poi.ss.usermodel Cell setCellStyle

Introduction

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

Prototype

void setCellStyle(CellStyle style);

Source Link

Document

Set the style for the cell.

Usage

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   ww  w.  ja va 2 s.  c om
            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;//  www  . ja v  a2  s  .c om
    Cell c;
    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:adams.data.io.output.ExcelSpreadSheetWriter.java

License:Open Source License

/**
 * Performs the actual writing. The caller must ensure that the writer gets
 * closed./*  ww  w.j  a  v  a  2s .c o m*/
 *
 * @param content   the spreadsheet to write
 * @param out      the writer to write the spreadsheet to
 * @return      true if successfully written
 */
@Override
protected boolean doWrite(SpreadSheet[] content, OutputStream out) {
    boolean result;
    Workbook workbook;
    Sheet sheet;
    Row row;
    adams.data.spreadsheet.Row spRow;
    adams.data.spreadsheet.Cell spCell;
    Cell cell;
    int i;
    int n;
    int count;
    CellStyle styleDate;
    CellStyle styleDateTime;
    CellStyle styleTime;
    HashSet<String> names;
    String name;

    result = true;

    try {
        if (getWriteOOXML())
            workbook = new XSSFWorkbook();
        else
            workbook = new HSSFWorkbook();
        styleDate = ExcelHelper.getDateCellStyle(workbook, Constants.DATE_FORMAT);
        styleDateTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIMESTAMP_FORMAT);
        styleTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIME_FORMAT);

        count = 0;
        names = new HashSet<>();
        for (SpreadSheet cont : content) {
            if (m_Stopped)
                return false;

            sheet = workbook.createSheet();
            if (cont.getName() != null) {
                name = cont.getName().replace("'", "");
                if (names.contains(name))
                    name += (count + 1);
            } else {
                name = m_SheetPrefix + (count + 1);
            }
            names.add(name);
            workbook.setSheetName(count, name);

            // header
            row = sheet.createRow(0);
            for (i = 0; i < cont.getColumnCount(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(cont.getHeaderRow().getCell(i).getContent());
            }

            // data
            for (n = 0; n < cont.getRowCount(); n++) {
                if (m_Stopped)
                    return false;
                row = sheet.createRow(n + 1);
                spRow = cont.getRow(n);
                for (i = 0; i < cont.getColumnCount(); i++) {
                    cell = row.createCell(i);
                    spCell = spRow.getCell(i);
                    if ((spCell == null) || spCell.isMissing()) {
                        if (m_MissingValue.length() > 0)
                            cell.setCellValue(m_MissingValue);
                        else
                            cell.setCellType(Cell.CELL_TYPE_BLANK);
                        continue;
                    }

                    if (spCell.isFormula() && !m_OutputAsDisplayed) {
                        cell.setCellFormula(spCell.getFormula().substring(1));
                    } else {
                        if (spCell.isDate()) {
                            cell.setCellValue(spCell.toDate());
                            cell.setCellStyle(styleDate);
                        } else if (spCell.isTime()) {
                            cell.setCellValue(spCell.toTime());
                            cell.setCellStyle(styleTime);
                        } else if (spCell.isDateTime()) {
                            cell.setCellValue(spCell.toDateTime());
                            cell.setCellStyle(styleDateTime);
                        } else if (spCell.isNumeric()) {
                            cell.setCellValue(Utils.toDouble(spCell.getContent()));
                        } else {
                            cell.setCellValue(spCell.getContent());
                        }
                    }
                }
            }

            // next sheet
            count++;
        }

        // save
        workbook.write(out);
    } catch (Exception e) {
        result = false;
        getLogger().log(Level.SEVERE, "Failed writing spreadsheet data", e);
    }

    return result;
}

From source file:adams.data.io.output.ExcelStreamingSpreadSheetWriter.java

License:Open Source License

/**
 * Performs the actual writing. The caller must ensure that the writer gets
 * closed./*  ww w  .  jav a  2s .co  m*/
 *
 * @param content   the spreadsheet to write
 * @param out      the writer to write the spreadsheet to
 * @return      true if successfully written
 */
@Override
protected boolean doWrite(SpreadSheet[] content, OutputStream out) {
    boolean result;
    SXSSFWorkbook workbook;
    Sheet sheet;
    Row row;
    adams.data.spreadsheet.Row spRow;
    adams.data.spreadsheet.Cell spCell;
    Cell cell;
    int i;
    int n;
    int count;
    CellStyle styleDate;
    CellStyle styleDateTime;
    CellStyle styleTime;
    HashSet<String> names;
    String name;

    result = true;

    try {
        workbook = new SXSSFWorkbook(m_MaxRows);
        styleDate = ExcelHelper.getDateCellStyle(workbook, Constants.DATE_FORMAT);
        styleDateTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIMESTAMP_FORMAT);
        styleTime = ExcelHelper.getDateCellStyle(workbook, Constants.TIME_FORMAT);

        count = 0;
        names = new HashSet<>();
        for (SpreadSheet cont : content) {
            if (m_Stopped)
                return false;

            sheet = workbook.createSheet();
            if (cont.getName() != null) {
                name = cont.getName().replace("'", "");
                if (names.contains(name))
                    name += (count + 1);
            } else {
                name = m_SheetPrefix + (count + 1);
            }
            names.add(name);
            workbook.setSheetName(count, name);

            // header
            row = sheet.createRow(0);
            for (i = 0; i < cont.getColumnCount(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(cont.getHeaderRow().getCell(i).getContent());
            }

            // data
            for (n = 0; n < cont.getRowCount(); n++) {
                if (m_Stopped)
                    return false;

                row = sheet.createRow(n + 1);
                spRow = cont.getRow(n);
                for (i = 0; i < cont.getColumnCount(); i++) {
                    cell = row.createCell(i);
                    spCell = spRow.getCell(i);
                    if ((spCell == null) || spCell.isMissing()) {
                        if (m_MissingValue.length() > 0)
                            cell.setCellValue(m_MissingValue);
                        else
                            cell.setCellType(Cell.CELL_TYPE_BLANK);
                        continue;
                    }

                    if (spCell.isFormula() && !m_OutputAsDisplayed) {
                        cell.setCellFormula(spCell.getFormula().substring(1));
                    } else {
                        if (spCell.isDate()) {
                            cell.setCellValue(spCell.toDate());
                            cell.setCellStyle(styleDate);
                        } else if (spCell.isTime()) {
                            cell.setCellValue(spCell.toTime());
                            cell.setCellStyle(styleTime);
                        } else if (spCell.isDateTime()) {
                            cell.setCellValue(spCell.toDateTime());
                            cell.setCellStyle(styleDateTime);
                        } else if (spCell.isNumeric()) {
                            cell.setCellValue(Utils.toDouble(spCell.getContent()));
                        } else {
                            cell.setCellValue(spCell.getContent());
                        }
                    }
                }
            }

            // next sheet
            count++;
        }

        // save
        workbook.write(out);
    } catch (Exception e) {
        result = false;
        getLogger().log(Level.SEVERE, "Failed writing spreadsheet data", e);
    }

    return result;
}

From source file:ambit2.core.io.XLSFileWriter.java

License:Open Source License

public void writeMolecule(IMolecule molecule) {

    Object value;//from   w  w w  .  ja  v a2 s. co  m

    try {
        //give it a chance to create a header just before the first write
        if (!writingStarted) {
            if (header == null)
                setHeader(molecule.getProperties());
            writeHeader();
            writingStarted = true;
        }
        Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
        String s;
        for (int i = 0; i < header.size(); i++) {
            value = molecule.getProperty(header.list.get(i));
            if (i == smilesIndex) {

                if (value == null) //no SMILES available
                    try {
                        value = sg.createSMILES(molecule);
                    } catch (Exception x) {
                        logger.log(Level.WARNING, "Error while createSMILES\t", x);
                        value = "";
                    }
            }

            if (value != null) {
                Cell cell = row.createCell((short) (i + 1));

                if (value instanceof Number) {
                    cell.setCellStyle(style);
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(((Number) value).doubleValue());
                } else {
                    try {
                        double d = Double.parseDouble(value.toString());
                        cell.setCellStyle(style);
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(d);
                    } catch (Exception x) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(value.toString());
                    }
                }

            }
        }
    } catch (Exception x) {
        logger.log(Level.WARNING, "ERROR while writing Molecule: ", x);
    }
}

From source file:apm.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?// w w  w.  ja va  2s .  co  m
 * @param title ?
 * @param headerList 
 */
private void initialize(String title, List<String> headerList) {
    this.wb = new SXSSFWorkbook(500);
    this.sheet = wb.createSheet("Export");
    this.styles = createStyles(wb);
    // Create title
    if (StringUtils.isNotBlank(title)) {
        Row titleRow = sheet.createRow(rownum++);
        titleRow.setHeightInPoints(30);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellStyle(styles.get("title"));
        titleCell.setCellValue(title);
        sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(),
                titleRow.getRowNum(), headerList.size() - 1));
    }
    // Create header
    if (headerList == null) {
        throw new RuntimeException("headerList not null!");
    }
    Row headerRow = sheet.createRow(rownum++);
    headerRow.setHeightInPoints(16);
    for (int i = 0; i < headerList.size(); i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellStyle(styles.get("header"));
        String[] ss = StringUtils.split(headerList.get(i), "**", 2);
        if (ss.length == 2) {
            cell.setCellValue(ss[0]);
            Comment comment = this.sheet.createDrawingPatriarch()
                    .createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
            comment.setString(new XSSFRichTextString(ss[1]));
            cell.setCellComment(comment);
        } else {
            cell.setCellValue(headerList.get(i));
        }
        sheet.autoSizeColumn(i);
    }
    for (int i = 0; i < headerList.size(); i++) {
        int colWidth = sheet.getColumnWidth(i) * 2;
        sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
    }
    log.debug("Initialize success.");
}

From source file:apm.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?/*from   w  w w .  j  ava 2s . c  o  m*/
 * @param row 
 * @param column ?
 * @param val 
 * @param align ??1?23??
 * @return ?
 */
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) {
    Cell cell = row.createCell(column);
    CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : ""));
    try {
        if (val == null) {
            cell.setCellValue("");
        } else if (val instanceof String) {
            cell.setCellValue((String) val);
        } else if (val instanceof Integer) {
            cell.setCellValue((Integer) val);
        } else if (val instanceof Long) {
            cell.setCellValue((Long) val);
        } else if (val instanceof Double) {
            cell.setCellValue((Double) val);
        } else if (val instanceof Float) {
            cell.setCellValue((Float) val);
        } else if (val instanceof Date) {
            DataFormat format = wb.createDataFormat();
            style.setDataFormat(format.getFormat("yyyy-MM-dd"));
            cell.setCellValue((Date) val);
        } else {
            if (fieldType != Class.class) {
                cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
            } else {
                cell.setCellValue((String) Class
                        .forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                                "fieldtype." + val.getClass().getSimpleName() + "Type"))
                        .getMethod("setValue", Object.class).invoke(null, val));
            }
        }
    } catch (Exception ex) {
        log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
        cell.setCellValue(val.toString());
    }
    cell.setCellStyle(style);
    return cell;
}

From source file:ar.edu.unrc.gametictactoe.performanceandtraining.configurations.StatisticExperiment.java

License:Open Source License

/**
 *
 * @param filePath//www  .j a v  a 2s .  c  o m
 * @param backupFiles
 * @param resultsPerFile
 * @param resultsRandom
 * @param randomPerceptronFile <p>
 * @throws IOException
 * @throws InvalidFormatException
 */
public void exportToExcel(String filePath, List<File> backupFiles, Map<File, StatisticForCalc> resultsPerFile,
        Map<File, StatisticForCalc> resultsRandom, File randomPerceptronFile)
        throws IOException, InvalidFormatException {
    InputStream inputXLSX = this.getClass()
            .getResourceAsStream("/ar/edu/unrc/gametictactoe/resources/EstadisticasTicTacToe.xlsx");
    Workbook wb = WorkbookFactory.create(inputXLSX);

    try (FileOutputStream outputXLSX = new FileOutputStream(
            filePath + "_" + dateFormater.format(dateForFileName) + "_STATISTICS" + ".xlsx")) {
        //============= imptimimos en la hoja de % Of Games Won ===================
        Sheet sheet = wb.getSheetAt(0);
        //Estilo par los titulos de las tablas
        int rowStartTitle = 0;
        int colStartTitle = 2;
        int rowStart = 1;
        int colStart = 3;
        Row rowPlayer1;
        Row rowPlayer2;
        Row rowDraw;
        // Luego creamos el objeto que se encargar de aplicar el estilo a la celda
        Font fontCellTitle = wb.createFont();
        fontCellTitle.setFontHeightInPoints((short) 10);
        fontCellTitle.setFontName("Arial");
        fontCellTitle.setBoldweight(Font.BOLDWEIGHT_BOLD);
        CellStyle CellStyleTitle = wb.createCellStyle();
        CellStyleTitle.setWrapText(true);
        CellStyleTitle.setAlignment(CellStyle.ALIGN_CENTER);
        CellStyleTitle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
        CellStyleTitle.setFont(fontCellTitle);

        // Establecemos el tipo de sombreado de nuestra celda
        CellStyleTitle.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        CellStyleTitle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        loadTitle(rowStartTitle, colStartTitle, sheet, backupFiles.size(), CellStyleTitle);
        //estilo titulo finalizado

        //Estilo de celdas con los valores de las estadisticas
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);
        /* We are now ready to set borders for this style */
        /* Draw a thin left border */
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        /* Add medium right border */
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        /* Add dashed top border */
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        /* Add dotted bottom border */
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        //estilo celdas finalizado
        //loadTitle(rowStartTitle, colStartTitle, sheet, backupFiles.size(), CellStyleTitle);
        rowPlayer1 = sheet.getRow(rowStart);
        rowPlayer2 = sheet.getRow(rowStart + 1);
        rowDraw = sheet.getRow(rowStart + 2);
        for (int file = 0; file < backupFiles.size(); file++) {
            Cell cellPlayer1 = rowPlayer1.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC);
            Cell cellPlayer2 = rowPlayer2.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC);
            Cell cellDraw = rowDraw.createCell(file + colStart, Cell.CELL_TYPE_NUMERIC);
            cellPlayer1.setCellStyle(cellStyle);
            cellPlayer2.setCellStyle(cellStyle);
            cellDraw.setCellStyle(cellStyle);
            Double cellValuePlayer1 = resultsPerFile.get(backupFiles.get(file)).getWinRatePlayer1();
            Double cellValuePlayer2 = resultsPerFile.get(backupFiles.get(file)).getWinRatePlayer2();
            Double cellValueDraw = resultsPerFile.get(backupFiles.get(file)).getDrawRate();
            assert cellValuePlayer1 <= 100 && cellValuePlayer1 >= 0;
            assert cellValuePlayer2 <= 100 && cellValuePlayer2 >= 0;
            assert cellValueDraw <= 100 && cellValueDraw >= 0;
            //assert cellValueDraw + cellValuePlayer1 + cellValuePlayer2 == 100;
            cellDraw.setCellValue(cellValueDraw);
            cellPlayer1.setCellValue(cellValuePlayer1);
            cellPlayer2.setCellValue(cellValuePlayer2);
        }
        if (!resultsRandom.isEmpty()) {
            int file = 0;//hay que ir a buscar el randomfile
            Cell cellDraw = rowDraw.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC);
            Cell cellPlayer1 = rowPlayer1.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC);
            Cell cellPlayer2 = rowPlayer2.createCell(file + colStart - 1, Cell.CELL_TYPE_NUMERIC);
            cellDraw.setCellStyle(cellStyle);
            cellPlayer1.setCellStyle(cellStyle);
            cellPlayer2.setCellStyle(cellStyle);
            //                StatisticForCalc get = resultsRandom.get(randomPerceptronFile);
            //                Double cellValuePlayer1 = get.getWinRatePlayer1();
            Double cellValuePlayer1 = resultsRandom.get(randomPerceptronFile).getWinRatePlayer1();
            Double cellValuePlayer2 = resultsRandom.get(randomPerceptronFile).getWinRatePlayer2();
            Double cellValueDraw = resultsRandom.get(randomPerceptronFile).getDrawRate();
            //assert cellValueDraw + cellValuePlayer1 + cellValuePlayer2 == 100;

            cellPlayer1.setCellValue(cellValuePlayer1);
            cellPlayer2.setCellValue(cellValuePlayer2);
            cellDraw.setCellValue(cellValueDraw);
        }
        wb.write(outputXLSX);
    }
}

From source file:ar.edu.unrc.gametictactoe.performanceandtraining.configurations.StatisticExperiment.java

License:Open Source License

/**
 *
 * @param rowStartTitle/*from  w  w w  .  j av a 2 s.  c o  m*/
 * @param colStartTitle
 * @param sheet
 * @param backupFilesSize
 * @param CellStyleTitle
 */
public void loadTitle(int rowStartTitle, int colStartTitle, Sheet sheet, int backupFilesSize,
        CellStyle CellStyleTitle) {
    int total_juegos = saveBackupEvery;
    Row row1 = sheet.getRow(rowStartTitle);
    for (int file = 1; file <= backupFilesSize; file++) {
        Cell cell = row1.createCell(file + colStartTitle, Cell.CELL_TYPE_NUMERIC);
        cell.setCellStyle(CellStyleTitle);
        Integer value = total_juegos * file;
        String valueStr = value.toString();
        String cellV = valueStr;
        if (valueStr.length() > 3) {
            cellV = valueStr.substring(0, valueStr.length() - 3) + "K";
        }
        cell.setCellValue(cellV);
    }
}

From source file:at.fh.swenga.firefighters.report.ExcelFireEngineReportView.java

@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    List<FireEngineModel> fireEngines = (List<FireEngineModel>) model.get("fireEngines");

    // create a worksheet
    Sheet sheet = workbook.createSheet("FireEngine Report");

    // create style for header cells
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setFontName("Arial");
    style.setFillForegroundColor(HSSFColor.BLUE.index);
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    font.setColor(HSSFColor.WHITE.index);
    style.setFont(font);/* ww  w  .  j ava  2s  .c o  m*/

    // create a new row in the worksheet
    Row headerRow = sheet.createRow(0);

    // create a new cell in the row
    Cell cell0 = headerRow.createCell(0);
    cell0.setCellValue("ID");
    cell0.setCellStyle(style);

    // create a new cell in the row
    Cell cell1 = headerRow.createCell(1);
    cell1.setCellValue("Modell");
    cell1.setCellStyle(style);

    // create a new cell in the row
    Cell cell2 = headerRow.createCell(2);
    cell2.setCellValue("Kennzeichen");
    cell2.setCellStyle(style);

    // create a new cell in the row
    Cell cell3 = headerRow.createCell(3);
    cell3.setCellValue("Leistung");
    cell3.setCellStyle(style);

    // create a new cell in the row
    Cell cell4 = headerRow.createCell(4);
    cell4.setCellValue("Baujahr");
    cell4.setCellStyle(style);

    // create a new cell in the row
    Cell cell5 = headerRow.createCell(5);
    cell5.setCellValue("Aktiv");
    cell5.setCellStyle(style);

    // create a new cell in the row
    Cell cell6 = headerRow.createCell(6);
    cell6.setCellValue("Funktion");
    cell6.setCellStyle(style);

    // create a new cell in the row
    Cell cell7 = headerRow.createCell(7);
    cell7.setCellValue("Feuerwehr");
    cell7.setCellStyle(style);

    // create multiple rows with fireEngines data
    int rowNum = 1;
    for (FireEngineModel fireEngine : fireEngines) {
        // create the row data
        Row row = sheet.createRow(rowNum++);
        row.createCell(0).setCellValue(fireEngine.getId());
        row.createCell(1).setCellValue(fireEngine.getModel());
        row.createCell(2).setCellValue(fireEngine.getLicensePlate());
        row.createCell(3).setCellValue(fireEngine.getPerformance());
        row.createCell(4).setCellValue(fireEngine.getBuildYear());
        row.createCell(5).setCellValue(fireEngine.getActive());
        row.createCell(6).setCellValue(fireEngine.getAbbreviation().getAbbreviation());
        row.createCell(7).setCellValue(fireEngine.getFireBrigade().getName());
    }

    // adjust column width to fit the content
    sheet.autoSizeColumn((short) 0);
    sheet.autoSizeColumn((short) 1);
    sheet.autoSizeColumn((short) 2);
    sheet.autoSizeColumn((short) 3);
    sheet.autoSizeColumn((short) 4);
    sheet.autoSizeColumn((short) 5);
    sheet.autoSizeColumn((short) 6);
    sheet.autoSizeColumn((short) 7);

}