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

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

Introduction

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

Prototype

Cell createCell(int column);

Source Link

Document

Use this to create new cells within the row and return it.

Usage

From source file:automatedhgl.AutomatedHGL.java

public static void main(String[] args) {

    try {/* ww w.  j  a v a2 s .c o m*/

        FileInputStream excelFile = new FileInputStream(new File(INFILE_NAME));

        //create workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(excelFile);

        //get first desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //create workbook instance to output excel file
        XSSFWorkbook workbookHGL = new XSSFWorkbook();

        //create sheet in output excel file
        XSSFSheet sheetHGL = workbookHGL.createSheet("HGL");

        //iterate through each row one by one
        Iterator<Row> rowiterator = sheet.iterator();

        while (rowiterator.hasNext()) {
            Row row = rowiterator.next();

            //for each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();

                if (row.getRowNum() > 7 && count < 23) //to filter column headings
                {

                    //check the cell type and format accordingly
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        count++;

                        //assign get value to correct variable
                        if (count == 1) {
                            InletStr = cell.getNumericCellValue();
                        } else if (count == 2) {
                            OutWSE = cell.getNumericCellValue();
                        }

                        System.out.print(cell.getNumericCellValue() + " (" + count + ") ");
                        break;

                    case Cell.CELL_TYPE_STRING:
                        count++;

                        /*//assign get value to correct variable
                        if( count == 1 ){InletStr = cell.getStringCellValue();}*/

                        System.out.print(cell.getStringCellValue() + " (" + count + ") ");
                        break;

                    case Cell.CELL_TYPE_FORMULA:
                        count++;

                        /*//assign get value to correct variable
                        if( count == 1 ){InletStr = cell.getCachedFormulaResultType();}*/

                        System.out.print(cell.getCachedFormulaResultType() + " (" + count + ") ");
                        break;
                    }
                }

                else {
                    count = 0; //reset the count at the end of the row
                }

            }

            System.out.println("return");
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //Output Excel file

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
    Object[][] datatypes = { { "Datatype", "Type", "Size(in bytes)" }, { "int", "Primitive", 2 },
            { "float", "Primitive", 4 }, { "double", "Primitive", 8 }, { "char", "Primitive", 1 },
            { "String", "Non-Primitive", "No fixed size" } };

    int rowNum = 0;
    System.out.println("Creating excel");

    for (Object[] datatype : datatypes) {
        Row row = sheet.createRow(rowNum++);
        int colNum = 0;
        for (Object field : datatype) {
            Cell cell = row.createCell(colNum++);
            if (field instanceof String) {
                cell.setCellValue((String) field);
            } else if (field instanceof Integer) {
                cell.setCellValue((Integer) field);
            }
        }
    }

    try {
        FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
        workbook.write(outputStream);
        workbook.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(InletStr + " ");
    System.out.print(OutWSE + " ");
    System.out.println("HGL Done");

}

From source file:b01.officeLink.excel.ExcelRefiller.java

License:Apache License

public void fillGroupContent(String groupStr, FocObject object) {
    ExcelGroupDefinition grpDef = getGroupDefinition(groupStr);
    Sheet srcSheet = getSourceSheet();/* w  w w  .  ja va 2 s . c om*/
    Sheet tarSheet = getTargetSheet();
    if (grpDef != null) {
        for (int i = 0; i < grpDef.getRowCount(); i++) {
            int rowIdx = grpDef.getRowAt(i);
            Row sRow = srcSheet.getRow(rowIdx);
            if (sRow != null) {
                Row tRow = tarSheet.getRow(currentRow);
                if (tRow == null) {
                    tRow = tarSheet.createRow(currentRow);
                }
                if (tRow != null) {
                    tRow.setHeight(sRow.getHeight());
                    for (int c = 0; c < 20; c++) {
                        Cell sCell = sRow.getCell(c + 1);
                        if (sCell != null) {
                            Cell tCell = tRow.getCell(c);
                            if (tCell == null) {
                                tCell = tRow.createCell(c);
                            }
                            if (tCell != null) {
                                tCell.setCellStyle(sCell.getCellStyle());

                                String str = "";
                                if (sCell.getCellType() == Cell.CELL_TYPE_STRING) {
                                    RichTextString rts = sCell.getRichStringCellValue();
                                    str = rts.getString();
                                    str = analyseContent(str, object);
                                } else if (sCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                                    str = String.valueOf(sCell.getNumericCellValue());
                                }

                                if (str != null && !str.isEmpty()) {
                                    int iVal = convertString2Integer(str);
                                    double dVal = convertString2Double(str);
                                    if (iVal != Integer.MAX_VALUE) {
                                        tCell.setCellValue(iVal);
                                    } else if (!Double.isNaN(dVal)) {
                                        tCell.setCellValue(dVal);
                                    } else {
                                        if (getFocExcelDocument() != null
                                                && getFocExcelDocument().getWorkbook() != null) {
                                            tCell.setCellValue(getFocExcelDocument().getWorkbook()
                                                    .getCreationHelper().createRichTextString(str));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                currentRow++;
            }
        }
    }
}

From source file:b01.officeLink.excel.FocExcelSheet.java

License:Apache License

public void set(int coord0, int coord1, Double dVal) {
    Row row = sheet.getRow(coord0);
    Cell cell = null;/* w w w .j ava2s  . co  m*/

    if (row != null) {
        cell = row.getCell(coord1);
        if (cell == null)
            cell = row.createCell((short) coord1);
    }

    if (cell != null) {
        // cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
        cell.setCellValue(dVal);
    }
}

From source file:bad.robot.excel.row.CopyRow.java

License:Apache License

/**
 * Copies a row from a row index on the given workbook and sheet to another row index. If the destination row is
 * already occupied, shift all rows down to make room.
 *
 *//*from   w  ww  .  j a  va2s .c om*/
public static void copyRow(Workbook workbook, Sheet worksheet, RowIndex from, RowIndex to) {
    Row sourceRow = worksheet.getRow(from.value());
    Row newRow = worksheet.getRow(to.value());

    if (alreadyExists(newRow))
        worksheet.shiftRows(to.value(), worksheet.getLastRowNum(), 1);
    else
        newRow = worksheet.createRow(to.value());

    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        Cell oldCell = sourceRow.getCell(i);
        Cell newCell = newRow.createCell(i);
        if (oldCell != null) {
            copyCellStyle(workbook, oldCell, newCell);
            copyCellComment(oldCell, newCell);
            copyCellHyperlink(oldCell, newCell);
            copyCellDataTypeAndValue(oldCell, newCell);
        }
    }

    copyAnyMergedRegions(worksheet, sourceRow, newRow);
}

From source file:balony.tableWriter.java

public static void writeTable(JFrame parent, Object[][] tableData, String[] colNames) {
    String opts[] = { "Tab-delimited text (raw)", "Excel .xls", "Excel 2007+ .xlsx" };
    int i = JOptionPane.showOptionDialog(parent, "Choose output format:", "Export Table",
            JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, opts, opts[0]);
    if (i == JOptionPane.CLOSED_OPTION) {
        return;//  w  w w .  ja v a 2  s  . c  o m
    }

    String[] chars = { ":", "[", "]", "/", "\\", "?", "*" };
    String fname = parent.getTitle();
    for (String c : chars) {
        fname = fname.replace(c, "");
    }

    JFileChooser jfc = new JFileChooser();
    if (i == 0) {
        jfc.setFileFilter(new FileNameExtensionFilter("Tab-delimited text files", "txt"));
        jfc.setSelectedFile(new File(fname.concat(".txt")));
    }

    if (i == 1) {
        jfc.setFileFilter(new FileNameExtensionFilter("Excel .xls files", "xls"));
        jfc.setSelectedFile(new File(fname.concat(".xls")));
    }

    if (i == 2) {
        jfc.setFileFilter(new FileNameExtensionFilter("Excel .xlsx files", "xlsx"));
        jfc.setSelectedFile(new File(fname.concat(".xlsx")));
    }

    int rv = jfc.showSaveDialog(parent);
    if (rv == JFileChooser.APPROVE_OPTION) {
        File f = jfc.getSelectedFile();

        try {

            if (i == 0) {
                BufferedWriter out = new BufferedWriter(new FileWriter(f));
                for (String columnName : colNames) {
                    out.write(columnName);
                    out.write("\t");
                }
                out.newLine();
                for (Object[] tableData1 : tableData) {
                    for (int k = 0; k < colNames.length; k++) {
                        if (tableData1[k] != null) {
                            out.write(tableData1[k].toString());
                        }
                        out.write("\t");
                    }
                    out.newLine();
                }
                out.close();
            }

            if (i > 0) {

                Workbook wb;

                if (i == 1) {
                    wb = new HSSFWorkbook();
                } else {
                    wb = new XSSFWorkbook();
                }

                Sheet sheet = wb.createSheet(fname);
                Row r;
                CellStyle style;
                sheet.createFreezePane(0, 1);

                for (int j = 0; j < tableData.length; j++) {
                    r = sheet.createRow(j + 1);
                    for (int k = 0; k < colNames.length; k++) {

                        if (tableData[j][k] != null) {
                            Cell c = r.createCell(k);

                            if (tableData[j][k] instanceof Integer) {
                                c.setCellType(Cell.CELL_TYPE_NUMERIC);
                                int v = ((Integer) tableData[j][k]);
                                c.setCellValue(v);
                            } else {
                                if (tableData[j][k] instanceof Double) {
                                    c.setCellType(Cell.CELL_TYPE_NUMERIC);
                                    double v = ((Double) tableData[j][k]);
                                    c.setCellValue(v);
                                } else {

                                    c.setCellType(Cell.CELL_TYPE_STRING);
                                    c.setCellValue(tableData[j][k].toString());

                                }
                            }
                        }
                    }
                }

                r = sheet.createRow(0);
                style = wb.createCellStyle();
                Font font = wb.createFont();
                font.setBoldweight(Font.BOLDWEIGHT_BOLD);
                style.setFont(font);

                for (int k = 0; k < colNames.length; k++) {
                    Cell c = r.createCell(k);
                    c.setCellType(Cell.CELL_TYPE_STRING);
                    c.setCellStyle(style);
                    c.setCellValue(colNames[k]);
                }

                FileOutputStream fos = new FileOutputStream(f);
                wb.write(fos);
                fos.close();
            }

        } catch (Exception ex) {
            Logger.getLogger(dataTable.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(parent, "File error: ".concat(ex.getLocalizedMessage()), "File Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        int n = JOptionPane.showOptionDialog(parent, "File saved. Open in default application?", "Message",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
        if (n == JOptionPane.YES_OPTION) {
            try {
                Desktop d = Desktop.getDesktop();
                d.open(f);
            } catch (IOException e) {
                System.out.println(e.getLocalizedMessage());
            }
        }
    }
}

From source file:bandaru_excelreadwrite.WritetoExcel.java

public void writeSongsListToExcel(List<Song> songList) {

    /*/*w w w. ja va  2  s  . c  o m*/
    Use XSSF for xlsx format and for xls use HSSF
     */
    Workbook workbook = new XSSFWorkbook();

    /*
    create new sheet 
     */
    Sheet songsSheet = workbook.createSheet("Albums");

    XSSFCellStyle my_style = (XSSFCellStyle) workbook.createCellStyle();
    /* Create XSSFFont object from the workbook */
    XSSFFont my_font = (XSSFFont) workbook.createFont();

    /*
    setting cell color
     */
    CellStyle style = workbook.createCellStyle();
    style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    /*
     setting Header color
     */
    CellStyle style2 = workbook.createCellStyle();
    style2.setFillForegroundColor(IndexedColors.DARK_RED.getIndex());
    style2.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style2.setAlignment(style2.ALIGN_CENTER);

    Row rowName = songsSheet.createRow(1);

    /*
    Merging the cells
     */
    songsSheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));

    /*
    Applying style to attribute name
     */
    int nameCellIndex = 1;
    Cell namecell = rowName.createCell(nameCellIndex++);
    namecell.setCellValue("Name");
    namecell.setCellStyle(style);

    Cell cel = rowName.createCell(nameCellIndex++);
    cel.setCellValue("Bandaru, Sreekanth");

    /*
    Applying underline to Name
     */
    my_font.setUnderline(XSSFFont.U_SINGLE);
    my_style.setFont(my_font);
    /* Attaching the style to the cell */
    CellStyle combined = workbook.createCellStyle();
    combined.cloneStyleFrom(my_style);
    combined.cloneStyleFrom(style);
    combined.setAlignment(combined.ALIGN_CENTER);

    cel.setCellStyle(combined);

    /*
    Applying  colors to header 
     */
    Row rowMain = songsSheet.createRow(3);
    SheetConditionalFormatting sheetCF = songsSheet.getSheetConditionalFormatting();
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("3");

    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.LIME.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A4:F4") };

    sheetCF.addConditionalFormatting(regions, rule1);

    /*
    setting new rule to apply alternate colors to cells having same Genre
     */
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    fill2.setFillBackgroundColor(IndexedColors.LEMON_CHIFFON.index);
    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAction = { CellRangeAddress.valueOf("A5:F5"), CellRangeAddress.valueOf("A6:F6"),
            CellRangeAddress.valueOf("A7:F7"), CellRangeAddress.valueOf("A8:F8"),
            CellRangeAddress.valueOf("A13:F13"), CellRangeAddress.valueOf("A14:F14"),
            CellRangeAddress.valueOf("A15:F15"), CellRangeAddress.valueOf("A16:F16"),
            CellRangeAddress.valueOf("A23:F23"), CellRangeAddress.valueOf("A24:F24"),
            CellRangeAddress.valueOf("A25:F25"), CellRangeAddress.valueOf("A26:F26")

    };

    /*        
    setting new rule to apply alternate colors to cells having same Fenre
     */
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill3 = rule3.createPatternFormatting();
    fill3.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
    fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAdv = { CellRangeAddress.valueOf("A9:F9"), CellRangeAddress.valueOf("A10:F10"),
            CellRangeAddress.valueOf("A11:F11"), CellRangeAddress.valueOf("A12:F12"),
            CellRangeAddress.valueOf("A17:F17"), CellRangeAddress.valueOf("A18:F18"),
            CellRangeAddress.valueOf("A19:F19"), CellRangeAddress.valueOf("A20:F20"),
            CellRangeAddress.valueOf("A21:F21"), CellRangeAddress.valueOf("A22:F22"),
            CellRangeAddress.valueOf("A27:F27"), CellRangeAddress.valueOf("A28:F28"),
            CellRangeAddress.valueOf("A29:F29") };

    /*
    Applying above created rule formatting to cells
     */
    sheetCF.addConditionalFormatting(regionsAction, rule2);
    sheetCF.addConditionalFormatting(regionsAdv, rule3);

    /*
     Setting coloumn header values
     */
    int mainCellIndex = 0;
    CellStyle style4 = workbook.createCellStyle();
    XSSFFont my_font2 = (XSSFFont) workbook.createFont();
    my_font2.setBold(true);
    style4.setFont(my_font2);
    rowMain.setRowStyle(style4);
    rowMain.createCell(mainCellIndex++).setCellValue("SNO");
    rowMain.createCell(mainCellIndex++).setCellValue("Genre");
    rowMain.createCell(mainCellIndex++).setCellValue("Rating");
    rowMain.createCell(mainCellIndex++).setCellValue("Movie Name");
    rowMain.createCell(mainCellIndex++).setCellValue("Director");
    rowMain.createCell(mainCellIndex++).setCellValue("Release Date");

    /*
    populating cell values
     */
    int rowIndex = 4;
    int sno = 1;
    for (Song song : songList) {
        if (song.getSno() != 0) {

            Row row = songsSheet.createRow(rowIndex++);
            int cellIndex = 0;

            /*
            first place in row is Sno
             */
            row.createCell(cellIndex++).setCellValue(sno++);

            /*
            second place in row is  Genre
             */
            row.createCell(cellIndex++).setCellValue(song.getGenre());

            /*
            third place in row is Critic score
             */
            row.createCell(cellIndex++).setCellValue(song.getCriticscore());

            /*
            fourth place in row is Album name
             */
            row.createCell(cellIndex++).setCellValue(song.getAlbumname());

            /*
            fifth place in row is Artist
             */
            row.createCell(cellIndex++).setCellValue(song.getArtist());

            /*
            sixth place in row is marks in date
             */
            if (song.getReleasedate() != null) {

                Cell date = row.createCell(cellIndex++);

                DataFormat format = workbook.createDataFormat();
                CellStyle dateStyle = workbook.createCellStyle();

                dateStyle.setDataFormat(format.getFormat("dd-MMM-yyyy"));
                date.setCellStyle(dateStyle);

                date.setCellValue(song.getReleasedate());

                /*
                auto-resizing columns
                 */
                songsSheet.autoSizeColumn(6);
                songsSheet.autoSizeColumn(5);
                songsSheet.autoSizeColumn(4);
                songsSheet.autoSizeColumn(3);
                songsSheet.autoSizeColumn(2);
            }

        }
    }

    /*
    writing this workbook to excel file.
     */
    try {
        FileOutputStream fos = new FileOutputStream(FILE_PATH);
        workbook.write(fos);
        fos.close();

        System.out.println(FILE_PATH + " is successfully written");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:biz.webgate.dominoext.poi.component.kernel.simpleviewexport.WorkbooklExportProcessor.java

License:Apache License

public void process2HTTP(ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr,
        DateTimeHelper dth) {//  www.  j  a va2s  .  c  om
    try {
        String strFileName = uis.getDownloadFileName();

        Workbook wbCurrent = null;
        if (strFileName.toLowerCase().endsWith(".xlsx")) {
            wbCurrent = new XSSFWorkbook();
        } else {
            wbCurrent = new HSSFWorkbook();
        }
        HashMap<String, CellStyle> hsCS = new HashMap<String, CellStyle>();
        CreationHelper cr = wbCurrent.getCreationHelper();
        CellStyle csDate = wbCurrent.createCellStyle();
        csDate.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDate().toPattern()));

        CellStyle csDateTime = wbCurrent.createCellStyle();
        csDateTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDateTime().toPattern()));

        CellStyle csTime = wbCurrent.createCellStyle();
        csTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFTime().toPattern()));

        hsCS.put("DATE", csDate);
        hsCS.put("TIME", csTime);
        hsCS.put("DATETIME", csDateTime);

        Sheet sh = wbCurrent.createSheet("SVE Export");
        int nRowCount = 0;

        // BUILDING HEADER
        if (uis.isIncludeHeader()) {
            Row rw = sh.createRow(nRowCount);
            int nCol = 0;
            for (ExportColumn expColumn : expModel.getColumns()) {
                rw.createCell(nCol).setCellValue(expColumn.getColumnName());
                nCol++;
            }
            nRowCount++;
        }
        // Processing Values
        for (ExportDataRow expRow : expModel.getRows()) {
            Row rw = sh.createRow(nRowCount);
            int nCol = 0;
            for (ExportColumn expColumn : expModel.getColumns()) {
                Cell clCurrent = rw.createCell(nCol);
                setCellValue(expRow.getValue(expColumn.getPosition()), clCurrent, expColumn, hsCS);
                nCol++;
            }
            nRowCount++;
        }
        for (int nCol = 0; nCol < expModel.getColumns().size(); nCol++) {
            sh.autoSizeColumn(nCol);
        }
        if (strFileName.toLowerCase().endsWith(".xlsx")) {
            hsr.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        } else if (strFileName.toLowerCase().endsWith("xls")) {
            hsr.setContentType("application/vnd.ms-excel");

        } else {
            hsr.setContentType("application/octet-stream");
        }
        hsr.addHeader("Content-disposition", "inline; filename=\"" + strFileName + "\"");
        OutputStream os = hsr.getOutputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        wbCurrent.write(bos);
        bos.writeTo(os);
        os.close();
    } catch (Exception e) {
        ErrorPageBuilder.getInstance().processError(hsr, "Error during SVE-Generation (Workbook Export)", e);
    }
}

From source file:biz.webgate.dominoext.poi.component.kernel.WorkbookProcessor.java

License:Apache License

public void setCellValue(Sheet shProcess, int nRow, int nCol, Object objValue, boolean isFormula,
        PoiCellStyle pCellStyle) {/*from   w ww.  j av  a2s  .co m*/
    // Logger logCurrent =
    // LoggerFactory.getLogger(WorkbookProcessor.class.getCanonicalName());

    try {
        Row rw = shProcess.getRow(nRow);
        if (rw == null) {
            // logCurrent.finest("Create Row");
            rw = shProcess.createRow(nRow);
        }
        Cell c = rw.getCell(nCol);
        if (c == null) {
            // logCurrent.finest("Create Cell");
            c = rw.createCell(nCol);
        }
        if (isFormula) {
            c.setCellFormula((String) objValue);
        } else {
            if (objValue instanceof Double) {
                c.setCellValue((Double) objValue);
            } else if (objValue instanceof Integer) {
                c.setCellValue((Integer) objValue);
            } else {
                if (objValue instanceof Date) {
                    c.setCellValue((Date) objValue);
                } else {
                    c.setCellValue("" + objValue);
                }
            }
        }
        // *** STYLE CONFIG Since V 1.1.7 ***

        if (pCellStyle != null) {
            checkStyleConstantValues();
            if (pCellStyle.getCellStyle() != null) {
                c.setCellStyle(pCellStyle.getCellStyle());
            } else {
                CellStyle style = shProcess.getWorkbook().createCellStyle();

                if (pCellStyle.getAlignment() != null)
                    style.setAlignment(m_StyleConstantValues.get(pCellStyle.getAlignment()));

                if (pCellStyle.getBorderBottom() != null)
                    style.setBorderBottom(m_StyleConstantValues.get(pCellStyle.getBorderBottom()));

                if (pCellStyle.getBorderLeft() != null)
                    style.setBorderLeft(m_StyleConstantValues.get(pCellStyle.getBorderLeft()));

                if (pCellStyle.getBorderRight() != null)
                    style.setBorderRight(m_StyleConstantValues.get(pCellStyle.getBorderRight()));

                if (pCellStyle.getBorderTop() != null)
                    style.setBorderTop(m_StyleConstantValues.get(pCellStyle.getBorderTop()));

                if (pCellStyle.getBottomBorderColor() != null)
                    style.setBottomBorderColor(
                            IndexedColors.valueOf(pCellStyle.getBottomBorderColor()).getIndex());

                if (pCellStyle.getDataFormat() != null) {
                    DataFormat format = shProcess.getWorkbook().createDataFormat();
                    style.setDataFormat(format.getFormat(pCellStyle.getDataFormat()));
                }

                if (pCellStyle.getFillBackgroundColor() != null)
                    style.setFillBackgroundColor(
                            IndexedColors.valueOf(pCellStyle.getFillBackgroundColor()).getIndex());

                if (pCellStyle.getFillForegroundColor() != null)
                    style.setFillForegroundColor(
                            IndexedColors.valueOf(pCellStyle.getFillForegroundColor()).getIndex());

                if (pCellStyle.getFillPattern() != null)
                    style.setFillPattern(m_StyleConstantValues.get(pCellStyle.getFillPattern()));

                // Create a new font and alter it.
                Font font = shProcess.getWorkbook().createFont();

                if (pCellStyle.getFontBoldweight() != null)
                    font.setBoldweight(m_StyleConstantValues.get(pCellStyle.getFontBoldweight()));

                if (pCellStyle.getFontColor() != null)
                    font.setColor(IndexedColors.valueOf(pCellStyle.getFontColor()).getIndex());

                if (pCellStyle.getFontHeightInPoints() != 0)
                    font.setFontHeightInPoints(pCellStyle.getFontHeightInPoints());

                if (pCellStyle.getFontName() != null)
                    font.setFontName(pCellStyle.getFontName());

                if (pCellStyle.isFontItalic())
                    font.setItalic(pCellStyle.isFontItalic());

                if (pCellStyle.isFontStrikeout())
                    font.setStrikeout(pCellStyle.isFontStrikeout());

                if (pCellStyle.getFontUnderline() != null)
                    font.setUnderline(m_StyleByteConstantValues.get(pCellStyle.getFontUnderline()));

                if (pCellStyle.getFontTypeOffset() != null)
                    font.setTypeOffset(m_StyleConstantValues.get(pCellStyle.getFontTypeOffset()));

                // Set Font
                style.setFont(font);

                if (pCellStyle.isHidden())
                    style.setHidden(pCellStyle.isHidden());

                if (pCellStyle.getIndention() != null)
                    style.setIndention(m_StyleConstantValues.get(pCellStyle.getIndention()));

                if (pCellStyle.getLeftBorderColor() != null)
                    style.setLeftBorderColor(IndexedColors.valueOf(pCellStyle.getLeftBorderColor()).getIndex());

                if (pCellStyle.isLocked())
                    style.setLocked(pCellStyle.isLocked());

                if (pCellStyle.getRightBorderColor() != null)
                    style.setRightBorderColor(
                            IndexedColors.valueOf(pCellStyle.getRightBorderColor()).getIndex());

                if (pCellStyle.getRotation() != 0)
                    style.setRotation(pCellStyle.getRotation());

                if (pCellStyle.getTopBorderColor() != null)
                    style.setTopBorderColor(IndexedColors.valueOf(pCellStyle.getTopBorderColor()).getIndex());

                if (pCellStyle.getVerticalAlignment() != null)
                    style.setVerticalAlignment(m_StyleConstantValues.get(pCellStyle.getVerticalAlignment()));

                if (pCellStyle.isWrapText())
                    style.setWrapText(pCellStyle.isWrapText());

                c.setCellStyle(style);
                pCellStyle.setCellStyle(style);
            }

        }

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

From source file:bloodbank.Simulation.java

public void simulate(Sheet sheet, int runs) {
    FES fes = new FES();
    //Donor donor=new donor();
    SimResults results = new SimResults();
    //Queue queues[];
    //queues = new Queue[8];
    //Exception occurs if I use above code, I don't know why....       
    Queue queue0 = new Queue();
    Queue queue1 = new Queue();
    Queue queue2 = new Queue();
    Queue queue3 = new Queue();
    Queue queue4 = new Queue();
    Queue queue5 = new Queue();
    Queue queue6 = new Queue();
    Queue queue7 = new Queue();
    //0.reception 1.preinterview-plasma 2.preinterview-whole 
    //3.predonation-plasma 4.predonation-whole
    //5. Disconnect (not distinguishing donation type)    
    //6. Plasma connecting  7. Whole connecting

    Donor cDonor;//from   w  w  w .j a va 2s. c  om
    int cID = 0;//current id
    int cType = 0;//current type
    int listID = 0;//ID in the list
    double OldhourBedOccPl = 0;
    double OldhourBedOccWh = 0;
    double OldhourQueue0 = 0;
    double OldhourQueueDocPl = 0;
    double OldhourQueueDocWh = 0;
    double OldsojournPreDonPl = 0;
    double OldsojournPreDonWh = 0;
    double OldsojournTotDonPl = 0;
    double OldsojournTotDonWh = 0;
    double OldhourQueuePreDonPl = 0;
    double OldhourQueuePreDonWh = 0;
    double OldhourQuestionnaireN = 0;
    double OldavailableNurse = 0;
    double OldPwaitforconnect = 0;
    double OldWwaitforconnect = 0;
    double Oldwaitfordisconnect = 0;

    //double number is the arbitrary number 35, (this was initially the plan as I constructed half hour statistics)
    double endtime = 0;
    double[] hourBedOccPl = new double[35]; // make array for hourBedOccPl
    double[] hourBedOccWh = new double[35]; // make array for hourBedOccWh               
    double[] hourQueue0 = new double[35]; // make array for queue 0
    double[] hourQueueDocPl = new double[35]; // make array for queue docpl
    double[] hourQueueDocWh = new double[35]; // make array for queue docwh
    double[] hourQueuePreDonPl = new double[35];
    double[] hourQueuePreDonWh = new double[35];

    double[] sojournPreDonPl = new double[35];
    double[] sojournPreDonWh = new double[35];
    double[] sojournTotDonPl = new double[35];
    double[] sojournTotDonWh = new double[35];
    double[] questionnaireN = new double[35];
    double[] availableNurse = new double[35];
    double[] Pwaitforconnect = new double[35];
    double[] Wwaitforconnect = new double[35];
    double[] waitfordisconnect = new double[35];

    double t = 0;
    Event firstPlasma = new Event(0, Event.ARRIVAL, t, 0);
    fes.addEvent(firstPlasma);

    Event firsthour = new Event(0, Event.HOURSTAT, t + 60, 0);
    fes.addEvent(firsthour);

    results.registerNewDonor(listID++, Donor.PLASMA, t);//ID=0
    double it = wholeInterarrivalDistribution[0].nextRandom();
    Event firstWhole = new Event(1, Event.ARRIVAL, t + it, 0);
    fes.addEvent(firstWhole);
    results.registerNewDonor(listID++, Donor.WHOLE, it);// ID=1
    while (1 == 1) {
        Event e = fes.nextEvent();
        if (e == null)
            break;

        t = e.getTime();// tNurse=eNurse.getTime();
        cID = e.getEventID();
        cType = results.getTypeFromList(cID);

        if (fes.getSizeFES() == 1) {
            endtime = t;
        }

        if (e.getEventType() == e.HOURSTAT) {
            int hst = 0;
            hst = (int) Math.floor(t / 60);
            if (hst <= 14) {
                results.registerDonorNum(Event.REGISTRATION, t, queue0.getSize(), 0);
                results.registerDonorNum(Event.QUESTIONAIRE, t, results.questionnaireN, 0);
                results.registerDonorNum(Event.PREINTERVIEW, t, queue1.getSize(), 0);
                results.registerDonorNum(Event.PREINTERVIEW, t, queue2.getSize(), 1);
                results.registerDonorNum(Event.DOCINTERVIEW, t, 0, 0);
                results.registerDonorNum(Event.PREDONATION, t, queue3.getSize(), 0);
                results.registerDonorNum(Event.PREDONATION, t, queue4.getSize(), 1);
                results.registerDonorNum(Event.ENTERDONATIONROOM, t, results.plasmaAtDroom, 0);
                results.registerDonorNum(Event.ENTERDONATIONROOM, t, results.wholeAtDroom, 1);
                results.registerDonorNum(Event.NURSEFREE, t, 0, 0);
                results.registerDonorNum(Event.DISCONNECTION, t, queue5.getSize(), 0);
                results.registerDonorNum(Event.CONNECTION, t, queue6.getSize(), 0);
                results.registerDonorNum(Event.CONNECTION, t, queue7.getSize(), 1);

                hourBedOccPl[hst] = (results.getMeanDonorNum(Event.ENTERDONATIONROOM, 0) * hst
                        - OldhourBedOccPl * (hst - 1));
                hourBedOccWh[hst] = (results.getMeanDonorNum(Event.ENTERDONATIONROOM, 1) * hst
                        - OldhourBedOccWh * (hst - 1));
                hourQueue0[hst] = (results.getMeanDonorNum(Event.REGISTRATION, 0) * hst
                        - OldhourQueue0 * (hst - 1));
                hourQueueDocPl[hst] = (results.getMeanDonorNum(Event.PREINTERVIEW, 0) * hst
                        - OldhourQueueDocPl * (hst - 1));
                hourQueueDocWh[hst] = (results.getMeanDonorNum(Event.PREINTERVIEW, 1) * hst
                        - OldhourQueueDocWh * (hst - 1));
                hourQueuePreDonPl[hst] = (results.getMeanDonorNum(Event.PREDONATION, 0) * hst
                        - OldhourQueuePreDonPl * (hst - 1));
                hourQueuePreDonWh[hst] = (results.getMeanDonorNum(Event.PREDONATION, 1) * hst
                        - OldhourQueuePreDonWh * (hst - 1));
                questionnaireN[hst] = (results.getMeanDonorNum(Event.QUESTIONAIRE, 0) * hst
                        - OldhourQuestionnaireN * (hst - 1));
                availableNurse[hst] = (results.getMeanDonorNum(Event.NURSEFREE, 0) * hst
                        - OldavailableNurse * (hst - 1));
                Pwaitforconnect[hst] = (results.getMeanDonorNum(Event.CONNECTION, 0) * hst
                        - OldPwaitforconnect * (hst - 1));
                Wwaitforconnect[hst] = (results.getMeanDonorNum(Event.CONNECTION, 1) * hst
                        - OldWwaitforconnect * (hst - 1));
                waitfordisconnect[hst] = (results.getMeanDonorNum(Event.DISCONNECTION, 0) * hst
                        - Oldwaitfordisconnect * (hst - 1));

                sojournPreDonPl[hst] = (results.getMeanSojournTimePlasmaPreDonation() * hst
                        - OldsojournPreDonPl * (hst - 1));
                sojournTotDonPl[hst] = (results.getMeanSojournTimePlasmaDonation() * hst
                        - OldsojournTotDonPl * (hst - 1));
                sojournPreDonWh[hst] = (results.getMeanSojournTimeWholePreDonation() * hst
                        - OldsojournPreDonWh * (hst - 1));
                sojournTotDonWh[hst] = (results.getMeanSojournTimeWholeDonation() * hst
                        - OldsojournTotDonWh * (hst - 1));

                OldhourBedOccPl = results.getMeanDonorNum(Event.ENTERDONATIONROOM, 0);
                OldhourBedOccWh = results.getMeanDonorNum(Event.ENTERDONATIONROOM, 1);
                OldhourQueue0 = results.getMeanDonorNum(Event.REGISTRATION, 0);
                OldhourQueueDocPl = results.getMeanDonorNum(Event.PREINTERVIEW, 0);
                OldhourQueueDocWh = results.getMeanDonorNum(Event.PREINTERVIEW, 1);
                OldhourQueuePreDonPl = results.getMeanDonorNum(Event.PREDONATION, 0);
                OldhourQueuePreDonWh = results.getMeanDonorNum(Event.PREDONATION, 1);
                OldsojournPreDonPl = results.getMeanSojournTimePlasmaPreDonation();
                OldsojournTotDonPl = results.getMeanSojournTimePlasmaDonation();
                OldsojournPreDonWh = results.getMeanSojournTimeWholePreDonation();
                OldsojournTotDonWh = results.getMeanSojournTimeWholeDonation();
                OldhourQuestionnaireN = results.getMeanDonorNum(Event.QUESTIONAIRE, 0);
                OldavailableNurse = results.getMeanDonorNum(Event.NURSEFREE, 0);
                OldPwaitforconnect = results.getMeanDonorNum(Event.CONNECTION, 0);
                OldWwaitforconnect = results.getMeanDonorNum(Event.CONNECTION, 1);
                Oldwaitfordisconnect = results.getMeanDonorNum(Event.DISCONNECTION, 0);
            }
            if (hst <= 16) {
                Event hourstat = new Event(0, Event.HOURSTAT, t + 60, 0);
                fes.addEvent(hourstat);
            }
            if (hst == 15) {
                continue;
            } else
                continue;
        }

        if (e.getEventType() == e.ARRIVAL) {
            if (t >= 12 * 60)
                continue;//original setting:t>=12*60   
            if (cType == Donor.PLASMA) {
                if (t + 6 < 655) {//only 110 plasma donors
                    results.registerNewDonor(listID, Donor.PLASMA, t + 6);
                    Event nextPlasma = new Event(listID++, Event.ARRIVAL, t + 6, 0);
                    fes.addEvent(nextPlasma);
                }
                Random rnd = new Random();
                double s = rnd.nextDouble();
                if (s < 0.15) {
                    continue;//skip current iteration
                }
                cDonor = results.getDonorAt(cID);
                queue0.addDonor(cDonor);
                if (queue0.getSize() <= 1) {
                    queue0.removeFirstDonor();
                    Event registration = new Event(cID, Event.REGISTRATION, t, 0);
                    fes.addEvent(registration);
                }
            } else {//cType==WHOLE
                cDonor = results.getDonorAt(cID);
                queue0.addDonor(cDonor);
                if (queue0.getSize() <= 1) {
                    Event registration = new Event(cID, Event.REGISTRATION, t, 0);
                    fes.addEvent(registration);
                }
                int ti = 0;//time interval
                ti = (int) (Math.floor(t / 30));
                double tt = wholeInterarrivalDistribution[ti].nextRandom();
                if (t + tt > ((ti + 1) * 30)) {
                    ti++;
                    t = (Math.floor(t / 30) + 1) * 30;
                    if (ti == 24) {
                        tt = 1;//add 1 more minute to judge the end point
                    } else {
                        tt = wholeInterarrivalDistribution[ti].nextRandom();
                    }
                }
                results.registerNewDonor(listID, Donor.WHOLE, t + tt);
                Event nextWhole = new Event(listID++, Event.ARRIVAL, t + tt, 0);
                fes.addEvent(nextWhole);
            }
        }
        if (e.getEventType() == Event.REGISTRATION) {
            results.registerDonorNum(e.getEventType(), t, 1 + queue0.getSize(), 0);
            Event questionnaire = new Event(cID, Event.QUESTIONAIRE, t + procedureDistributions[0].nextRandom(),
                    0); // start questionnaire after reg.service complete
            fes.addEvent(questionnaire);
        }
        if (e.getEventType() == Event.QUESTIONAIRE) {//departure from register
            results.questionnaireN++;
            results.registerDonorNum(e.getEventType(), t, results.questionnaireN, 0);
            if (queue0.getSize() > 0) {
                Event registration = new Event(queue0.getFirstDonor().getIDdonor(), Event.REGISTRATION, t, 0);
                fes.addEvent(registration);
                queue0.removeFirstDonor();
            } else {//no one waits for registration
                results.registerDonorNum(Event.REGISTRATION, t, 0, 0);
            }
            Event preinterview = new Event(cID, Event.PREINTERVIEW, t + procedureDistributions[1].nextRandom(),
                    0);
            fes.addEvent(preinterview);
        }
        if (e.getEventType() == Event.PREINTERVIEW) {
            results.questionnaireN--;
            results.registerDonorNum(Event.QUESTIONAIRE, t, results.questionnaireN, 0); //questionnaire-1donor
            //results.docinterN++;
            if (cType == Donor.PLASMA) {
                //results.registerDonorNum(Event.PREINTERVIEW, t, queue1.getSize(),0);//preinterview
                queue1.addDonor(results.getDonorAt(cID));
                if (queue1.getSize() <= 1) {
                    for (int i = 0; i < results.isdocbusy.length; i++) {
                        if (results.isdocbusy[i] == 0) {
                            Event docinterview = new Event(cID, Event.DOCINTERVIEW, t, i);
                            fes.addEvent(docinterview);
                            queue1.removeFirstDonor();
                            //results.registerDonorNum(Event.PREINTERVIEW, t, queue1.getSize(),0);
                            break;
                        }
                    }
                }
                results.registerDonorNum(Event.PREINTERVIEW, t, queue1.getSize(), 0);
            } else {//whole donor
                //results.registerDonorNum(Event.PREINTERVIEW, t, queue2.getSize(),1);
                queue2.addDonor(results.getDonorAt(cID));
                if (queue2.getSize() <= 1 && queue1.getSize() == 0) {
                    for (int i = 0; i < results.isdocbusy.length; i++) {
                        if (results.isdocbusy[i] == 0) {
                            Event docinterview = new Event(cID, Event.DOCINTERVIEW, t, i);
                            fes.addEvent(docinterview);
                            queue2.removeFirstDonor();
                            //results.registerDonorNum(Event.PREINTERVIEW, t, queue2.getSize(),1);
                            break;
                        }
                    }
                }
                results.registerDonorNum(Event.PREINTERVIEW, t, queue2.getSize(), 1); //newplace of registration
            }
        }
        if (e.getEventType() == Event.DOCINTERVIEW) {
            results.registerDonorNum(Event.DOCINTERVIEW, t, 0, 0);
            results.isdocbusy[e.getFlag()] = 1;
            double itt = procedureDistributions[2].nextRandom();//interview time
            Event predonation = new Event(cID, Event.PREDONATION, t + itt, e.getFlag());//i:doctor i
            fes.addEvent(predonation);

        }
        if (e.getEventType() == Event.PREDONATION) {
            //results.registerTempSojournTime(t-);
            results.registerDonorNum(Event.DOCINTERVIEW, t, 0, 0);
            results.isdocbusy[e.flag] = 0;
            if (queue1.getSize() > 0) {//plasma donor's waiting for interview
                Event docinterview = new Event(queue1.getFirstDonor().getIDdonor(), Event.DOCINTERVIEW, t, 0);
                fes.addEvent(docinterview);
                queue1.removeFirstDonor();
                results.registerDonorNum(Event.PREINTERVIEW, t, queue1.getSize(), 0);
            } else if (queue2.getSize() > 0) {//check whole donor's waiting
                Event docinterview = new Event(queue2.getFirstDonor().getIDdonor(), Event.DOCINTERVIEW, t, 0);
                fes.addEvent(docinterview);
                queue2.removeFirstDonor();
                results.registerDonorNum(Event.PREINTERVIEW, t, queue2.getSize(), 1);
            }
            Random rnd = new Random();
            double s = rnd.nextDouble();
            if (s < 0.05)//ineligible
            {
                continue;//skip current iteration
            }
            if (cType == Donor.PLASMA) {
                queue3.addDonor(results.getDonorAt(cID));//add plasma donor to pre-donation queue
                results.registerDonorNum(Event.PREDONATION, t, queue3.getSize(), 0);//register 
                if (queue3.getSize() <= 1) {//also needs to check any bed and nurse available or not
                    if (results.isBedAvailable(Donor.PLASMA) == 1) {
                        queue3.removeFirstDonor();
                        Event donation = new Event(cID, Event.ENTERDONATIONROOM, t, 0);
                        fes.addEvent(donation);
                    }
                }
            } else {
                queue4.addDonor(results.getDonorAt(cID));//add whole donor to pre-donation queue
                results.registerDonorNum(Event.PREDONATION, t, queue4.getSize(), 1);//register 
                if (queue4.getSize() <= 1) {//also needs to check any bed is available or not
                    if (results.isBedAvailable(Donor.WHOLE) == 1) {
                        queue4.removeFirstDonor();
                        Event donation = new Event(cID, Event.ENTERDONATIONROOM, t, 0);
                        fes.addEvent(donation);
                    }
                }
            }
        }
        if (e.getEventType() == Event.ENTERDONATIONROOM) {
            if (cType == Donor.PLASMA) {
                results.registerPlasmaPreDonationSojournTime(t - results.getDonorAt(cID).arrivalTime);
                results.registerDonorNum(Event.PREDONATION, t, queue3.getSize(), 0);
                results.plasmaAtDroom++;
                results.registerDonorNum(e.getEventType(), t, results.plasmaAtDroom, 0);
                results.registerDonorNum(Event.CONNECTION, t, queue6.getSize(), 0);
            } else {
                results.registerWholePreDonationSojournTime(t - results.getDonorAt(cID).arrivalTime);
                results.registerDonorNum(Event.PREDONATION, t, queue4.getSize(), 1);
                results.wholeAtDroom++;
                results.registerDonorNum(e.getEventType(), t, results.wholeAtDroom, 1);
                results.registerDonorNum(Event.CONNECTION, t, queue7.getSize(), 1);
            }
            results.registerPreDonationSojournTime(t - results.getDonorAt(cID).arrivalTime);
            //check any nurse is available
            results.registerBed(1, cType);
            int iflag = 0;
            int i = 0;
            do {
                if (results.isnursebusy[i] == 0) {
                    //results.isnursebusy[i]=1;
                    Event connection = new Event(cID, Event.CONNECTION, t, i);//i:nurse num i
                    fes.addEvent(connection);
                    iflag = 1;
                    break;
                }
                i++;
            } while (i < results.isnursebusy.length);
            //if no nurse available, enter queue
            if (iflag == 0) {
                if (cType == Donor.PLASMA) {
                    queue6.addDonor(results.getDonorAt(cID));
                } else {
                    queue7.addDonor(results.getDonorAt(cID));
                }
            }
        }
        if (e.getEventType() == Event.CONNECTION) {
            results.registerDonorNum(Event.NURSEFREE, t, 0, 0);
            results.isnursebusy[e.getFlag()] = 1;//nursebusy0->1
            double nt;
            nt = procedureDistributions[3].nextRandom();//nurse connection time
            //we can simply check three queues when this nurse finishes connection here,
            //but to simplify the code, we create event.NURSEFREE
            //Similarly, we can create event.DOCFREE, but we will only use it once, ...so ,..
            Event nurseFree = new Event(0, Event.NURSEFREE, t + nt, e.getFlag());
            fes.addEvent(nurseFree);
            if (cType == Donor.PLASMA) {
                results.registerDonorNum(Event.CONNECTION, t, queue6.getSize(), 0);
                Event predisconnect = new Event(cID, Event.DISCONNECTION,
                        t + nt + procedureDistributions[5].nextRandom(), 0);
                fes.addEvent(predisconnect);
            } else {
                results.registerDonorNum(Event.CONNECTION, t, queue7.getSize(), 1);
                Event predisconnect = new Event(cID, Event.DISCONNECTION,
                        t + nt + procedureDistributions[4].nextRandom(), 0);
                fes.addEvent(predisconnect);
            }
        }
        if (e.getEventType() == Event.PREDISCONNECT) {
            results.registerDonorNum(Event.DISCONNECTION, t, queue5.getSize(), 0);
            int iflag = 0;
            for (int i = 0; i <= results.isnursebusy.length; i++) {//check if any nurse is available
                if (results.isnursebusy[i] == 0) {
                    //results.isnursebusy[i]=1;
                    Event disconnection = new Event(cID, Event.DISCONNECTION, t, i);//i:nurse num i
                    fes.addEvent(disconnection);
                    iflag = 1;
                    break;
                }
            }
            if (iflag == 0) {//no nurse is available at this time
                queue5.addDonor(results.getDonorAt(cID));
            }
        }
        if (e.getEventType() == Event.DISCONNECTION) {
            results.registerDonorNum(Event.DISCONNECTION, t, queue5.getSize(), 0);
            results.registerDonorNum(Event.NURSEFREE, t, 0, 0);
            results.isnursebusy[e.getFlag()] = 1;//nursebusy0->1
            double nt;
            nt = procedureDistributions[6].nextRandom();//nurse disconnection time
            Event nurseFree = new Event(0, Event.NURSEFREE, t + nt, e.getFlag());
            fes.addEvent(nurseFree);
            //schedule recovery and leave
            Event leavedonationroom = new Event(cID, Event.LEAVEDONATIONROOM,
                    t + nt + procedureDistributions[7].nextRandom(), 0);
            fes.addEvent(leavedonationroom);
        }
        if (e.getEventType() == Event.NURSEFREE) {
            results.registerDonorNum(Event.DISCONNECTION, t, queue5.getSize(), 0);
            results.registerDonorNum(Event.CONNECTION, t, queue6.getSize(), 0);
            results.registerDonorNum(Event.CONNECTION, t, queue7.getSize(), 1);
            //flag1->0
            //check three queues.
            results.registerDonorNum(Event.NURSEFREE, t, 0, 0);
            results.isnursebusy[e.getFlag()] = 0;
            if (queue5.getSize() > 0) {//disconnection
                cDonor = queue5.getFirstDonor();
                Event disconnection = new Event(cDonor.getIDdonor(), Event.DISCONNECTION, t, e.getFlag());//i:nurse num i
                fes.addEvent(disconnection);
                queue5.removeFirstDonor();
            } else if (queue6.getSize() > 0) {//connect plasma
                cDonor = queue6.getFirstDonor();
                Event connection = new Event(cDonor.getIDdonor(), Event.CONNECTION, t, e.getFlag());//i:nurse num i
                fes.addEvent(connection);
                queue6.removeFirstDonor();
            } else if (queue7.getSize() > 0) {//connect whole
                cDonor = queue7.getFirstDonor();
                Event connection = new Event(cDonor.getIDdonor(), Event.CONNECTION, t, e.getFlag());//i:nurse num i
                fes.addEvent(connection);
                queue7.removeFirstDonor();
            }
        }
        if (e.getEventType() == Event.LEAVEDONATIONROOM) {
            if (cType == Donor.PLASMA) {
                results.registerPlasmaSojournTime(t - results.getDonorAt(cID).arrivalTime);
                results.plasmaAtDroom--;
                results.registerDonorNum(e.getEventType(), t, results.plasmaAtDroom, 0);
            } else {
                results.registerWholeSojournTime(t - results.getDonorAt(cID).arrivalTime);
                results.wholeAtDroom--;
                results.registerDonorNum(e.getEventType(), t, results.wholeAtDroom, 1);
            }
            results.registerSojournTime(t - results.getDonorAt(cID).arrivalTime);
            results.registerBed(0, cType);//1 bed becomes available

            if (cType == Donor.PLASMA && queue3.getSize() > 0) { //queue3.getSize()>0  //cType==Donor.PLASMA&&queue3.getSize()>0
                Event donation = new Event(cID, Event.ENTERDONATIONROOM, t, 0);
                fes.addEvent(donation);
                queue3.removeFirstDonor();
                results.registerDonorNum(Event.PREDONATION, t, queue3.getSize(), 0);
            }

            if (cType == Donor.WHOLE && queue4.getSize() > 0) {//queue4.getSize()>0  //cType==Donor.WHOLE&&queue4.getSize()>0
                Event donation = new Event(cID, Event.ENTERDONATIONROOM, t, 0);
                fes.addEvent(donation);
                queue4.removeFirstDonor();
                results.registerDonorNum(Event.PREDONATION, t, queue4.getSize(), 1);
            }
        }

    }

    Row row = sheet.createRow((short) runs);
    Cell cell = row.createCell(0);
    cell.setCellValue(endtime);
    cell = row.createCell(1);
    cell.setCellValue(results.getMeanSojournTimePlasmaPreDonation());
    cell = row.createCell(2);
    cell.setCellValue(results.getMeanSojournTimeWholePreDonation());
    cell = row.createCell(3);
    cell.setCellValue(results.getMeanSojournTimePlasmaDonation());
    cell = row.createCell(4);
    cell.setCellValue(results.getMeanSojournTimeWholeDonation());
    cell = row.createCell(5);
    cell.setCellValue(results.getMeanDonorNum(Event.REGISTRATION, 0));//
    cell = row.createCell(6);
    cell.setCellValue(results.getMeanDonorNum(Event.QUESTIONAIRE, 0));
    cell = row.createCell(7);
    cell.setCellValue(results.getMeanDonorNum(Event.PREINTERVIEW, 0));//preinterview plasma
    cell = row.createCell(8);
    cell.setCellValue(results.getMeanDonorNum(Event.PREINTERVIEW, 1));//preinterview whole
    cell = row.createCell(9);
    cell.setCellValue(results.getMeanDonorNum(Event.DOCINTERVIEW, 0));//number of available doctors
    cell = row.createCell(10);
    cell.setCellValue(results.getMeanDonorNum(Event.PREDONATION, 0));//
    cell = row.createCell(11);
    cell.setCellValue(results.getMeanDonorNum(Event.PREDONATION, 1));//
    cell = row.createCell(12);
    cell.setCellValue(results.getMeanDonorNum(Event.ENTERDONATIONROOM, 0));//donor room
    cell = row.createCell(13);
    cell.setCellValue(results.getMeanDonorNum(Event.ENTERDONATIONROOM, 1));//donor room

    for (int i = 0; i < 16; i++) {
        /*cell=row.createCell(13+i);cell.setCellValue(Math.round(hourBedOccPl[i]* 10000.0) / 10000.0);//donor room Plasma
        cell=row.createCell(13+1*16+i);cell.setCellValue(Math.round(hourBedOccWh[i]* 10000.0) / 10000.0);//donor room Whole
        cell=row.createCell(13+2*16+i);cell.setCellValue(Math.round(hourQueue0[i]* 10000.0) / 10000.0);//Queue lenght reception
        cell=row.createCell(13+3*16+i);cell.setCellValue(Math.round(hourQueueDocPl[i]* 10000.0) / 10000.0);//Queue length doctor plasma
        cell=row.createCell(13+4*16+i);cell.setCellValue(Math.round(hourQueueDocWh[i]* 10000.0) / 10000.0);//Queue length doctor whole
        cell=row.createCell(13+5*16+i);cell.setCellValue(Math.round(sojournPreDonPl[i]* 10000.0) / 10000.0);
        cell=row.createCell(13+6*16+i);cell.setCellValue(Math.round(sojournTotDonPl[i]* 10000.0) / 10000.0);
        cell=row.createCell(13+7*16+i);cell.setCellValue(Math.round(sojournPreDonWh[i]* 10000.0) / 10000.0);
        cell=row.createCell(13+8*16+i);cell.setCellValue(Math.round(sojournTotDonWh[i]* 10000.0) / 10000.0);
        cell=row.createCell(13+9*16+i);cell.setCellValue(Math.round(hourQueuePreDonPl[i]* 10000.0) / 10000.0);
        cell=row.createCell(13+10*16+i);cell.setCellValue(Math.round(hourQueuePreDonWh[i]* 10000.0) / 10000.0);
        cell=row.createCell(13+11*16+i);cell.setCellValue(Math.round(questionnaireN[i]* 10000.0) / 10000.0);*/
        cell = row.createCell(13 + 1 * 16 + i);
        cell.setCellValue(Math.round(availableNurse[i] * 10000.0) / 10000.0);
        cell = row.createCell(13 + 2 * 16 + i);
        cell.setCellValue(Math.round(Pwaitforconnect[i] * 10000.0) / 10000.0);
        cell = row.createCell(13 + 3 * 16 + i);
        cell.setCellValue(Math.round(Wwaitforconnect[i] * 10000.0) / 10000.0);
        cell = row.createCell(13 + 4 * 16 + i);
        cell.setCellValue(Math.round(waitfordisconnect[i] * 10000.0) / 10000.0);
        cell = row.createCell(13 + 5 * 16);
        cell.setCellValue(Math.round(results.donorList.size()) * 10000.0 / 10000.0);
    }

    //other measures can be added
}

From source file:bloodbank.Simulation.java

/**
 *
 * @param args/*  w w w  . j  a  va2  s .  c  o  m*/
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    //from 8am to 20pm 
    Random rng = new Random();

    Distribution plasmaInter = new DiscreteUniformDistribution(6, 6, rng);
    Distribution[] wholeInter = new Distribution[24];
    Distribution[] procedures = new Distribution[10];
    constructDistribution(wholeInter, procedures, rng);

    Simulation sim = new Simulation(plasmaInter, wholeInter, procedures);
    // Create the sheet
    Workbook wb = new HSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("new sheet");

    int runs = 1;
    Row row = sheet.createRow((short) 0);
    Cell cell = row.createCell(0);
    cell.setCellValue(createHelper.createRichTextString("Total running time"));
    cell = row.createCell(1);
    cell.setCellValue(createHelper.createRichTextString("P pre-donation sojourn time"));
    cell = row.createCell(2);
    cell.setCellValue(createHelper.createRichTextString("W pre-donation sojourn time"));
    cell = row.createCell(3);
    cell.setCellValue(createHelper.createRichTextString("P total sojourn time"));
    cell = row.createCell(4);
    cell.setCellValue(createHelper.createRichTextString("W total sojourn time"));
    cell = row.createCell(5);
    cell.setCellValue(createHelper.createRichTextString("Qmean # P&W at registration"));
    cell = row.createCell(6);
    cell.setCellValue(createHelper.createRichTextString("Qmean # P&W at questionnaire"));
    cell = row.createCell(7);
    cell.setCellValue(createHelper.createRichTextString("Qmean # P at (pre-)interview"));
    cell = row.createCell(8);
    cell.setCellValue(createHelper.createRichTextString("Qmean # W at (pre-)interview"));
    cell = row.createCell(9);
    cell.setCellValue(createHelper.createRichTextString("# of available doctors"));

    cell = row.createCell(10);
    cell.setCellValue(createHelper.createRichTextString("Qmean # P at pre-donation room"));
    cell = row.createCell(11);
    cell.setCellValue(createHelper.createRichTextString("Qmean # W at pre-donation room"));
    cell = row.createCell(12);
    cell.setCellValue(createHelper.createRichTextString("Qmean # P at donation room"));
    cell = row.createCell(13);
    cell.setCellValue(createHelper.createRichTextString("Qmean # W at donation room"));

    for (int i = 0; i < 16; i++) {
        /*cell=row.createCell(13+i);cell.setCellValue(createHelper.createRichTextString("BedOcc.Pl " + "hr " + (8 + i)));//donor room Plasma
        cell=row.createCell(13+1*16+i);cell.setCellValue(createHelper.createRichTextString("BedOcc.Wh " + "hr" + (8 + i)));//donor room Whole
        cell=row.createCell(13+2*16+i);cell.setCellValue(createHelper.createRichTextString("Queue0" + "hr" + (8 + i)));//Queue lenght reception
        cell=row.createCell(13+3*16+i);cell.setCellValue(createHelper.createRichTextString("QueueDocPl" + "hr" + (8 + i)));//Queue length doctor plasma
        cell=row.createCell(13+4*16+i);cell.setCellValue(createHelper.createRichTextString("QueueDocWh" + "hr" + (8 + i)));//Queue length doctor whole
        cell=row.createCell(13+5*16+i);cell.setCellValue(createHelper.createRichTextString("SJT Pl PreDon" + "hr" + (8 + i)));
        cell=row.createCell(13+6*16+i);cell.setCellValue(createHelper.createRichTextString("SJT Pl TotDon" + "hr" + (8 + i)));
        cell=row.createCell(13+7*16+i);cell.setCellValue(createHelper.createRichTextString("SJT Wh PreDon" + "hr" + (8 + i)));
        cell=row.createCell(13+8*16+i);cell.setCellValue(createHelper.createRichTextString("SJT Wh TotDon" + "hr" + (8 + i)));
        cell=row.createCell(13+9*16+i);cell.setCellValue(createHelper.createRichTextString("QueuePreDonPl" + "hr" + (8 + i)));
        cell=row.createCell(13+10*16+i);cell.setCellValue(createHelper.createRichTextString("QueuePreDonWh" + "hr" + (8 + i)));   
        cell=row.createCell(13+11*16+i);cell.setCellValue(createHelper.createRichTextString("QuestionNaire" + "hr" + (8 + i))); */
        cell = row.createCell(13 + 1 * 16 + i);
        cell.setCellValue(createHelper.createRichTextString("AvailableNurse" + "hr" + (8 + i)));
        cell = row.createCell(13 + 2 * 16 + i);
        cell.setCellValue(createHelper.createRichTextString("P Wait for connect" + "hr" + (8 + i)));
        cell = row.createCell(13 + 3 * 16 + i);
        cell.setCellValue(createHelper.createRichTextString("W Wait for connect" + "hr" + (8 + i)));
        cell = row.createCell(13 + 4 * 16 + i);
        cell.setCellValue(createHelper.createRichTextString("Wait for disconnect" + "hr" + (8 + i)));
    }

    //other measures can be added, see all measures in line 364-379, as well as variance  
    while (runs <= 10000) {//runs=10000 costs 9 seconds
        sim.simulate(sheet, runs);
        runs++;
    }
    FileOutputStream fileOut = new FileOutputStream("correct.xls");//name of the excel file
    wb.write(fileOut);
    fileOut.close();
}