Example usage for org.apache.poi.ss.usermodel Workbook write

List of usage examples for org.apache.poi.ss.usermodel Workbook write

Introduction

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

Prototype

void write(OutputStream stream) throws IOException;

Source Link

Document

Write out this workbook to an Outputstream.

Usage

From source file:bloodbank.Simulation.java

/**
 *
 * @param args//from   w ww . j  a  va 2  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();
}

From source file:bo.com.offercruzmail.imp.InterpretadorMensajeGenerico.java

protected Multipart enviarPlantilla(boolean plantillaNueva, String idCargar)
        throws MessagingException, IOException {
    String nombreArchivoOrigen;//from www .j av a  2 s  .  c o m
    String nombreAdjunto;
    List<T> lista = null;
    mensajesError = null;
    T entidad = null;
    getObjetoNegocio().setIdUsuario(idUsuario);
    getObjetoNegocio().setComandoPermiso(nombreEntidad);
    try {
        if (!plantillaNueva) {
            if ("todos".equals(idCargar)) {
                lista = getObjetoNegocio().obtenerTodos();
                nombreArchivoOrigen = nombreEntidad + "-" + "lista";
                nombreAdjunto = "lista_" + nombreEntidad + ".xlsx";
            } else {
                ID id;
                try {
                    id = convertirId(idCargar);
                } catch (Exception ex) {
                    return FormadorMensajes.enviarIdCargarNoValido();
                }
                entidad = getObjetoNegocio().recuperarPorId(id);
                if (entidad == null) {
                    return FormadorMensajes.enviarEntidadNoExiste(idCargar);
                }
                nombreArchivoOrigen = nombreEntidad;
                nombreAdjunto = nombreEntidad + "_" + idCargar + ".xlsx";
            }
        } else {
            nombreArchivoOrigen = nombreEntidad;
            nombreAdjunto = "plantilla_" + nombreEntidad + ".xlsx";
            //            if (this instanceof IInterpretadorFormularioDasometrico) {
            //                if (cargarPlantillaFormularios) {
            //                    nombreArchivoOrigen = "plantillafrm";
            //                }
            //            }
        }
        String nombreArchivoOriginal = "plantillas/" + nombreArchivoOrigen + ".xlsx";
        File archivoCopia = UtilitariosMensajes.reservarNombre(nombreEntidad);
        UtilitariosMensajes.copiarArchivo(new File(nombreArchivoOriginal), archivoCopia);
        archivosTemporales.add(archivoCopia);
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            Workbook libro;
            fis = new FileInputStream(archivoCopia);
            libro = WorkbookFactory.create(fis);
            hojaActual = new HojaExcelHelper(libro.getSheetAt(0));
            if (plantillaNueva) {
                preparPlantillaAntesDeEnviar(libro);
            } else {
                if (lista != null) {
                    mostrarLista(lista);
                } else {
                    mostrarEntidad(entidad, libro);
                }
            }
            if (mensajesError != null) {
                return FormadorMensajes.enviarErroresNegocio(mensajesError);
            }
            //Guardamos cambio
            os = new FileOutputStream(archivoCopia);
            libro.write(os);
        } catch (InvalidFormatException ex) {

        } finally {
            if (fis != null) {
                fis.close();
            }
            if (os != null) {
                os.close();
            }
        }
        String textoMensaje;
        if (plantillaNueva) {
            textoMensaje = escapeHtml4("La plantilla est adjunta a este mensaje.");
        } else if (lista != null) {
            textoMensaje = "La consulta ha devuelto " + lista.size() + " registro(s).";
        } else {
            textoMensaje = escapeHtml4("El registro solicitado est adjunto a este mensaje");
        }
        Multipart cuerpo = new MimeMultipart();
        BodyPart adjunto = new MimeBodyPart();
        DataSource origen = new FileDataSource(archivoCopia);
        adjunto.setDataHandler(new DataHandler(origen));
        adjunto.setFileName(nombreAdjunto);
        cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(textoMensaje));
        cuerpo.addBodyPart(adjunto);
        return cuerpo;
    } catch (PermisosInsuficientesException ex) {
        appendException(new BusinessExceptionMessage(ex.getMessage(), "Autentificacion"));
    }
    if (mensajesError != null) {
        return FormadorMensajes.enviarErroresNegocio(mensajesError);
    }
    return null;
}

From source file:bouttime.fileinput.ExcelFileInputTest.java

License:Open Source License

@BeforeClass
public static void setUpClass() throws Exception {
    // Create the input file
    inputFile = new File(INPUT_FILENAME);
    assertNotNull(inputFile);//from w  w w.jav a 2s . c om
    assertTrue(inputFile.createNewFile());
    Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet s = wb.createSheet();

    makeWrestler(s, 0, "David", "Robinson", "Open", "5", "88", "88", "Spurs", "A", "50", "SW");
    makeWrestler(s, 1, "Tim", "Duncan", "Open", "4", "99", "99", "Spurs", "A", "21", "SW");
    makeWrestler(s, 2, "Tony", "Parker", "Rookie", "1", "77", "77", "Spurs", "B", "6", "SW");
    makeWrestler(s, 3, "Manu", "Ginobili", "Rookie", "3", "82", "80", "Spurs", "B", "12", "SW");
    makeWrestler(s, 4, "David", "Robinson", "Open", "5", "88", "88", "Spurs", "A", "50", "SW");

    FileOutputStream outputStream = new FileOutputStream(inputFile);
    wb.write(outputStream);
    outputStream.close();
}

From source file:br.com.algoritmo.compilacao.CompilaXlsx.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;
    Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();
    data.put(0, new Object[] { 0, "Luiz Carlos Miyadaira Ribeiro Junior", "Base", "0468265522433921",
            "SOFTWARE", null, null, null });
    data.put(1, new Object[] { 1, "Sergio Antnio Andrade de Freitas", "Destino 1", "0395549254894676",
            "SOFTWARE", null, null, null });
    data.put(2, new Object[] { 2, "Andre Luiz Aquere de Cerqueira e Souza", "Destino 2", "8424412648258970",
            "CIVIL", null, null, null });
    data.put(3, new Object[] { 3, "Edson Mintsu Hung Destino", "Destino 3", "6753551743147880", "ELETRNICA",
            null, null, null });/*from w w  w .ja v  a2 s  . c om*/
    data.put(4, new Object[] { 4, "Edgard Costa Oliveira", "Destino 4", "1196380808351110", "SOFTWARE", null,
            null, null });
    data.put(5, new Object[] { 5, "Edson Alves da Costa Jnior", "Destino 5", "2105379147123450", "SOFTWARE",
            null, null, null });
    data.put(6, new Object[] { 6, "Andr Barros de Sales", "Destino 6", "7610669796869660", "SOFTWARE", null,
            null, null });
    data.put(7, new Object[] { 7, "Giovanni Almeida dos Santos", "Destino 7", "0580891429319047", "SOFTWARE",
            null, null, null });
    data.put(8, new Object[] { 8, "Cristiane Soares Ramos", "Destino 8", "9950213660160160", "SOFTWARE", null,
            null, null });
    data.put(9, new Object[] { 9, "Fabricio Ataides Braz", "Destino 9", "1700216932505000", "SOFTWARE", null,
            null, null });
    data.put(10, new Object[] { 10, "Alexandre Srgio de Arajo Bezerra", "Destino 10", "0255998976169051",
            "MEDICINA", null, null, null });
    data.put(11, new Object[] { 11, "Eduardo Stockler Tognetti", "Destino 11", "2443108673822680", "ELTRICA",
            null, null, null });
    data.put(12, new Object[] { 12, "Jan Mendona Correa", "Destino 12", "7844006017790570",
            "CINCIA DA COMPUTAO", null, null, null });
    data.put(13, new Object[] { 13, "Rejane Maria da Costa Figueiredo", "Destino 13", "2187680174312042",
            "SOFTWARE", null, null, null });
    data.put(14, new Object[] { 14, "Augusto Csar de Mendona Brasil", "Destino 14", "0571960641751286",
            "ENERGIA", null, null, null });
    data.put(15, new Object[] { 15, "Fbio Macdo Mendes", "Destino 15", "8075435338067780", "F?SICA", null,
            null, null });

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet aba1 = wb.createSheet("Percentual de similaridade 1");
    PrintSetup printSetup = aba1.getPrintSetup();
    printSetup.setLandscape(true);
    aba1.setFitToPage(true);
    aba1.setHorizontallyCenter(true);

    Sheet aba2 = wb.createSheet("Percentual de similaridade 2");
    PrintSetup printSetup2 = aba2.getPrintSetup();
    printSetup2.setLandscape(true);
    aba1.setFitToPage(true);
    aba1.setHorizontallyCenter(true);

    //title row
    Row titleRow = aba1.createRow(0);
    titleRow.setHeightInPoints(15);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue(
            "Resultado da aplicao do algoritmo de clculo do percentual de similaridade entre os indivduos");
    titleCell.setCellStyle(styles.get("title"));
    aba1.addMergedRegion(CellRangeAddress.valueOf("$A$1:$H$1"));

    //header row
    Row headerRow = aba1.createRow(1);
    headerRow.setHeightInPoints(15);
    Cell headerCell;
    for (int i = 1; i <= titles.length; i++) {
        headerCell = headerRow.createCell(i);
        headerCell.setCellValue(titles[i - 1]);
        headerCell.setCellStyle(styles.get("header"));
    }

    Row headerBase = aba1.createRow(2);
    headerBase.setHeightInPoints(15);
    Cell headerCellBase;
    for (int i = 1; i <= base.length; i++) {
        headerCellBase = headerBase.createCell(i);
        headerCellBase.setCellValue(base[i - 1]);
        headerCellBase.setCellStyle(styles.get("header1"));
    }

    Row headerDestino = aba1.createRow(4);
    headerDestino.setHeightInPoints(15);
    Cell headerCellDestino;
    for (int i = 1; i <= destino.length; i++) {
        headerCellDestino = headerDestino.createCell(i);
        headerCellDestino.setCellValue(destino[i - 1]);
        headerCellDestino.setCellStyle(styles.get("header1"));
    }

    /*int rownum = 2;
    for (int i = 0; i < 10; i++) {
        Row row = sheet.createRow(rownum++);
        for (int j = 0; j < titles.length; j++) {
     Cell cell = row.createCell(j);
     if(j == 9){
         //the 10th cell contains sum over week days, e.g. SUM(C3:I3)
         String ref = "C" +rownum+ ":I" + rownum;
         cell.setCellFormula("SUM("+ref+")");
         cell.setCellStyle(styles.get("formula"));
     } else if (j == 11){
         cell.setCellFormula("J" +rownum+ "-K" + rownum);
         cell.setCellStyle(styles.get("formula"));
     } else {
         cell.setCellStyle(styles.get("cell"));
     }
        }
    }
            
    rownum = 3;
    for (int i = 0; i < 10; i++) {
        Row row = sheet.createRow(rownum++);
        for (int j = 0; j < titles1.length; j++) {
     Cell cell = row.createCell(j);
     if(j == 9){
         //the 10th cell contains sum over week days, e.g. SUM(C3:I3)
         String ref = "C" +rownum+ ":I" + rownum;
         cell.setCellFormula("SUM("+ref+")");
         cell.setCellStyle(styles.get("formula"));
     } else if (j == 11){
         cell.setCellFormula("J" +rownum+ "-K" + rownum);
         cell.setCellStyle(styles.get("formula"));
     } else {
         cell.setCellStyle(styles.get("cell"));
     }
        }
    }
    */
    //set sample data
    //Iterate over data and write to sheet
    Set<Integer> keyset = data.keySet();
    int rownum = 0;
    for (Integer key : keyset) {
        Row row = aba1.createRow(3 + rownum++);
        Object[] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Integer)
                cell.setCellValue((Integer) obj);
        }
        if (row.getRowNum() == 3) {
            rownum++;
        }
    }
    //finally set column widths, the width is measured in units of 1/256th of a character width
    aba1.setColumnWidth(0, 2 * 256); //2 characters wide
    aba1.setColumnWidth(1, 26 * 256); //26 characters wide
    aba1.setColumnWidth(2, 20 * 256); //20 characters wide
    aba1.setColumnWidth(3, 18 * 256); //18 characters wide
    aba1.setColumnWidth(4, 20 * 256); //20 characters wide
    for (int i = 5; i < 9; i++) {
        aba1.setColumnWidth(i, 15 * 256); //6 characters wide
    }

    // Write the output to a file
    String file = "Sada/Percentual de similaridade.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:br.com.gartech.nfse.integrador.util.ExcelHelper.java

public File exportExcel(String sourceFilePath, String targetFilePath, boolean hasTemplete) throws IOException,
        SAXException, ParserConfigurationException, XPathExpressionException, InvalidFormatException {
    sourceFile = new File(sourceFilePath);
    targetFile = new File(targetFilePath);

    InputStream xmlInputStream = new FileInputStream(sourceFile);
    InputStream excelInputStream = new FileInputStream(targetFile);

    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlInputStream);
    Workbook workbook = WorkbookFactory.create(excelInputStream);

    workbook = bindXml(document, workbook);

    document = null;//from  w w w .  j a  v a  2s  .  c o m
    xmlInputStream.close();
    xmlInputStream = null;
    excelInputStream.close();
    excelInputStream = null;

    OutputStream excelOutputStream = new FileOutputStream(targetFile);
    workbook.write(excelOutputStream);
    excelOutputStream.close();
    excelOutputStream = null;
    return targetFile;
}

From source file:br.com.itfox.test.Excel.java

public void gerarExcel(boolean simple) {
    try {//ww  w. j a v a2 s.co m
        String ini = "01/01/2015";
        String fim = "22/06/2016";
        String seg = "'21','22','23'";
        String areaOper = "'47','24','23','29','4','18','5','48','10','31','43','35','36','7','33','45','3','32','9','39','13','38','16','44','30','15','2','17','12','6','42','41','34','40','1','19','14','26','22','51','46','49','27','25','8','50','52','28','11','20','37','21'";
        BusinessDelegate bd = new BusinessDelegate();
        String path = "/Users/belchiorpalma/Desktop/template/";
        String pathTemplate = "/Users/belchiorpalma/NetBeansProjects/Quest_Iveco/src/br/com/itfox/generator/";
        InputStream is = null;
        try {
            is = new FileInputStream(pathTemplate + "TemplateGic.xlsx");
        } catch (FileNotFoundException ex) {
            // Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        //try(InputStream is = GeneratorObjectCollection.class.getResourceAsStream(pathTemplate+"TemplateGic.xlsx"))
        // {
        SimpleDateFormat sdf = new SimpleDateFormat("dd_M_yyyy_hh_mm_ss");
        String date = sdf.format(new Date());

        Workbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk
        Sheet sh = wb.createSheet();

        ini = (Utils.dateFormat(ini));
        fim = (Utils.dateFormat(fim));

        List<Gic> gics = bd.selectGic(ini, fim, seg, areaOper);
        int i = 0;
        for (Gic g : gics) {
            Row row = sh.createRow(i);
            for (int cellnum = 0; cellnum < 153; cellnum++) {
                Cell cell = row.createCell(cellnum);
                cell.setCellValue(g.getC_nomeproprietario());
            }
            i++;
        }
        /*
        for (int rownum = 0; rownum < 1000000; rownum++) {
            Row row = sh.createRow(rownum);
            for (int cellnum = 0; cellnum < 2; cellnum++) {
                Cell cell = row.createCell(cellnum);
                String address = new CellReference(cell).formatAsString();
                cell.setCellValue(address);
            }
        }*/

        FileOutputStream out;
        try {
            out = new FileOutputStream(path + "object_collection_output.xlsx");
            wb.write(out);
            out.close();
        } catch (FileNotFoundException ex) {
            //Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

    } catch (IOException ex) {
        // Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    }
}

From source file:br.ufal.cideei.util.count.SummaryBuilder.java

License:Open Source License

public static void buildSummary(String splShortName)
        throws InvalidFormatException, FileNotFoundException, IOException {

    // final String userHomeFolder = System.getProperty("user.home").substring(3);
    String userHomeFolder = "C:\\tst";
    final String output = userHomeFolder + File.separator + "summ.xls";
    File outputFile = new File(output);
    Workbook outputWorkbook;
    if (!outputFile.exists()) {
        outputFile.createNewFile();// w w  w.  j  a va 2s .c o m
        outputWorkbook = new HSSFWorkbook();
    } else {
        FileInputStream inputFileStream = new FileInputStream(outputFile);
        outputWorkbook = WorkbookFactory.create(inputFileStream);
    }

    {
        List<String> referencesForRDA3 = new ArrayList<String>();
        List<String> referencesForUVA3 = new ArrayList<String>();
        List<String> referencesForRDA2 = new ArrayList<String>();
        List<String> referencesForUVA2 = new ArrayList<String>();
        String fileName = "fs-" + splShortName + ".xls";
        String filePath = userHomeFolder + File.separator;
        String fullFileName = filePath + File.separator + "fs-" + splShortName + ".xls";
        Workbook workbook = WorkbookFactory.create(new FileInputStream(new File(fullFileName)));
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            Row headerRow = sheet.getRow(0);
            for (Cell cell : headerRow) {
                String stringCellValue = cell.getStringCellValue();
                if (stringCellValue.equals("rd")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForRDA2.add(cellRefForAnotherSheet);
                } else if (stringCellValue.equals("uv")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForUVA2.add(cellRefForAnotherSheet);
                } else if (stringCellValue.equals("rd (a3)")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForRDA3.add(cellRefForAnotherSheet);
                } else if (stringCellValue.equals("uv (a3)")) {
                    Row sumRow = sheet.getRow(sheet.getLastRowNum() - 1);
                    Cell sumCell = sumRow.getCell(i);
                    CellReference sumCellRef = new CellReference(sumCell);
                    String cellRefForAnotherSheet = "\'" + filePath + "[" + fileName + "]Sheet" + i + "\'!"
                            + sumCellRef.formatAsString();
                    referencesForUVA3.add(cellRefForAnotherSheet);
                }
            }
        }
        if (outputWorkbook.getSheet(splShortName) != null) {
            outputWorkbook.removeSheetAt(outputWorkbook.getSheetIndex(splShortName));
        }
        Sheet outputSheet = outputWorkbook.createSheet(splShortName);
        Row RDA2Row = outputSheet.createRow(0);
        RDA2Row.createCell(0).setCellValue("RD A2");
        for (int i = 0; i < referencesForRDA2.size(); i++) {
            Cell createdCell = RDA2Row.createCell(i + 1);
            System.out.println(referencesForRDA2.get(i));
            createdCell.setCellType(Cell.CELL_TYPE_FORMULA);
            createdCell.setCellValue(referencesForRDA2.get(i));
        }
        Row UVA2Row = outputSheet.createRow(1);
        UVA2Row.createCell(0).setCellValue("UV A2");
        for (int i = 0; i < referencesForUVA2.size(); i++) {
            Cell createdCell = UVA2Row.createCell(i + 1);
            createdCell.setCellFormula(referencesForUVA2.get(i));
        }
        Row RDA3Row = outputSheet.createRow(2);
        RDA3Row.createCell(0).setCellValue("RD A3");
        for (int i = 0; i < referencesForRDA3.size(); i++) {
            Cell createdCell = RDA3Row.createCell(i + 1);
            createdCell.setCellFormula(referencesForRDA3.get(i));
        }
        Row UVA3Row = outputSheet.createRow(3);
        UVA3Row.createCell(0).setCellValue("UV A3");
        for (int i = 0; i < referencesForUVA3.size(); i++) {
            Cell createdCell = UVA3Row.createCell(i + 1);
            createdCell.setCellFormula(referencesForUVA3.get(i));
        }
    }
    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
    outputWorkbook.write(fileOutputStream);
    fileOutputStream.close();
}

From source file:br.ufpa.psi.comportamente.labgame.relatorios.RelatorioJogadasExperimento.java

License:Open Source License

public InputStream relatorioOntogenese(Long idExp) throws FileNotFoundException, IOException {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Relatrio Ontognese");

    JogadaDAO jogadaDAO = new JogadaDAO();

    jogadaDAO.beginTransaction();//from  w  ww.  j a va  2  s .co  m
    List<Jogada> jogadasAux = jogadaDAO.encontrarPorExperimento(idExp);
    jogadaDAO.stopOperation(false);

    ExperimentoDAO expDAO = new ExperimentoDAO();

    expDAO.beginTransaction();
    Experimento experimento = expDAO.find(Experimento.class, idExp);
    expDAO.stopOperation(false);

    JogadorDAO jogDAO = new JogadorDAO();

    jogDAO.beginTransaction();
    List<Jogador> jogadoresTotais = jogDAO.encontraPorExperimento(experimento);
    jogDAO.stopOperation(false);

    //CRIA O CABEALHO "ONTOGNESE
    int quantidadeColunas = 6;
    int quantidadeJogadoresPorCiclo = experimento.getTamanhoFilaJogadores(); //Vai pegar o valor de acordo com o experimento.
    int larguraColuna = 4600;
    int colunaAtual;
    int colunaFinalOntogenese = (quantidadeColunas * quantidadeJogadoresPorCiclo) + 1;

    // --- DEFINE AS PROPRIEDADES DAS CLULAS
    sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 0));
    sheet.addMergedRegion(new CellRangeAddress(0, 2, 1, 1));
    sheet.setColumnWidth(0, 1500);
    sheet.setColumnWidth(1, 2000);
    sheet.addMergedRegion(new CellRangeAddress(0, 1, 2, colunaFinalOntogenese));
    sheet.addMergedRegion(new CellRangeAddress(1, 2, colunaFinalOntogenese + 1, colunaFinalOntogenese + 1));
    sheet.setColumnWidth(colunaFinalOntogenese + 1, 3000);
    sheet.addMergedRegion(new CellRangeAddress(1, 3, colunaFinalOntogenese + 2, colunaFinalOntogenese + 2));
    sheet.setColumnWidth(colunaFinalOntogenese + 2, 4000);

    // --- FIM

    //for (int i = 0; i < quantidadeJogadoresPorCiclo; i++)
    //if(i == 1){
    sheet.setColumnWidth(2, larguraColuna); // Campo com o nome do participante fica nessa coluna.
    colunaAtual = 2 + quantidadeColunas;
    //} else {
    sheet.setColumnWidth((colunaAtual), larguraColuna);
    colunaAtual += quantidadeColunas;
    sheet.setColumnWidth(colunaAtual, larguraColuna);

    //}
    // ---DEFINE AS CORES DE CADA FONTE
    XSSFFont fonteBranca = (XSSFFont) wb.createFont();
    fonteBranca.setColor(new XSSFColor(Color.WHITE));
    XSSFFont fonteNegra = (XSSFFont) wb.createFont();
    fonteNegra.setColor(new XSSFColor(Color.BLACK));
    XSSFFont fonteVermelha = (XSSFFont) wb.createFont();
    fonteVermelha.setColor(new XSSFColor(Color.RED));

    // --- FIM

    // --- DEFINE ESTILOS CLULAS
    //ESTILO COLUNA LINHA
    XSSFCellStyle estiloColunaLinha = (XSSFCellStyle) wb.createCellStyle();

    estiloColunaLinha.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloColunaLinha.setAlignment(CellStyle.ALIGN_CENTER);
    estiloColunaLinha.setFillForegroundColor(new XSSFColor(Color.LIGHT_GRAY));
    estiloColunaLinha.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloColunaLinha.getFont().setBold(true);
    estiloColunaLinha.setBorderBottom(BorderStyle.MEDIUM);
    estiloColunaLinha.setBorderLeft(BorderStyle.MEDIUM);
    estiloColunaLinha.setBorderRight(BorderStyle.MEDIUM);
    estiloColunaLinha.setBorderTop(BorderStyle.MEDIUM);

    XSSFCellStyle estiloColunaColuna = (XSSFCellStyle) wb.createCellStyle();

    estiloColunaColuna.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloColunaColuna.setAlignment(CellStyle.ALIGN_CENTER);
    estiloColunaColuna.getFont().setBold(true);

    //ESTILO CABEALHO
    XSSFCellStyle estiloCabecalhoColunaAB = (XSSFCellStyle) wb.createCellStyle();

    estiloCabecalhoColunaAB.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloCabecalhoColunaAB.setAlignment(CellStyle.ALIGN_CENTER);
    estiloCabecalhoColunaAB.setFillForegroundColor(new XSSFColor(Color.LIGHT_GRAY));
    estiloCabecalhoColunaAB.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloCabecalhoColunaAB.getFont().setBold(true);

    XSSFCellStyle estiloCabecalhoColunaP = (XSSFCellStyle) wb.createCellStyle();

    estiloCabecalhoColunaP.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloCabecalhoColunaP.setAlignment(CellStyle.ALIGN_CENTER);
    estiloCabecalhoColunaP.setFont(fonteNegra);
    estiloCabecalhoColunaP.getFont().setBold(true);

    //ESTILO MUDANA DE CICLO
    XSSFCellStyle estiloMudancaCiclo = (XSSFCellStyle) wb.createCellStyle();
    estiloMudancaCiclo.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloMudancaCiclo.setAlignment(CellStyle.ALIGN_CENTER);
    estiloMudancaCiclo.setFillForegroundColor(new XSSFColor(Color.RED));
    estiloMudancaCiclo.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloMudancaCiclo.setFont(fonteBranca);

    //ESTILO CICLO SEM MUDANA
    XSSFCellStyle estiloCicloSemMudanca = (XSSFCellStyle) wb.createCellStyle();
    estiloCicloSemMudanca.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloCicloSemMudanca.setAlignment(CellStyle.ALIGN_CENTER);
    estiloCicloSemMudanca.setFont(fonteNegra);

    //ESTILO NOME PARTICIPANTE
    XSSFCellStyle estiloNomeP = (XSSFCellStyle) wb.createCellStyle();
    estiloNomeP.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloNomeP.setAlignment(CellStyle.ALIGN_CENTER);
    estiloNomeP.setBorderBottom(BorderStyle.DOTTED);
    estiloNomeP.setBorderTop(BorderStyle.DOTTED);
    estiloNomeP.setFillForegroundColor(new XSSFColor(Color.BLACK));
    estiloNomeP.setFillPattern(CellStyle.SOLID_FOREGROUND);
    estiloNomeP.setFont(fonteBranca);
    estiloNomeP.getFont().setBold(true);

    //ESTILO ESTABILIDADE
    XSSFCellStyle estiloEstabilidade = (XSSFCellStyle) wb.createCellStyle();
    estiloEstabilidade.setVerticalAlignment(VerticalAlignment.CENTER);
    estiloEstabilidade.setAlignment(CellStyle.ALIGN_CENTER);
    estiloEstabilidade.setFont(fonteVermelha);
    estiloEstabilidade.getFont().setBold(true);

    // --- FIM

    int cr = 0;

    // --- CRIA PRIMEIRA COLUNA (CABEALHO)
    XSSFRow row1 = (XSSFRow) sheet.createRow((short) cr++);

    //CRIA CLULA 1
    XSSFCell c1 = row1.createCell(0);

    c1.setCellValue("FASE");
    c1.setCellStyle(estiloCabecalhoColunaAB);

    //CRIA CLULA 2
    XSSFCell c2 = row1.createCell(1);

    c2.setCellValue("CICLO");
    c2.setCellStyle(estiloCabecalhoColunaAB);

    //CRIA CLULA 3 (ONTOGNESE)
    XSSFCell cOnto = row1.createCell(2);
    cOnto.setCellValue("ONTOGNESE");
    cOnto.setCellStyle(estiloCicloSemMudanca);

    //CRIA CLULA 'CC'
    XSSFRow row2 = (XSSFRow) sheet.createRow(1);
    XSSFCell cCC = row2.createCell(colunaFinalOntogenese + 1);
    cCC.setCellValue("CC");
    cCC.setCellStyle(estiloCicloSemMudanca);

    //CRIA CLULA 'ESTABILIDADE'
    XSSFCell cEstab = row2.createCell(colunaFinalOntogenese + 2);
    cEstab.setCellValue("ESTABILIDADE");
    cEstab.setCellStyle(estiloEstabilidade);

    // --- FIM

    int contadorCelulasCabecalho = 2;
    int contadorAcertosCultural = 0;
    XSSFRow row3 = (XSSFRow) sheet.createRow((short) 2);
    //GERA O CABEALHO DAS JOGADAS
    for (int i = 0; i < experimento.getTamanhoFilaJogadores(); i++) {
        //CRIA CLULA 3 NA LINHA 3
        XSSFCell c3 = row3.createCell(contadorCelulasCabecalho++);

        c3.setCellValue("P");
        c3.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 4 NA LINHA 3
        XSSFCell c4 = row3.createCell(contadorCelulasCabecalho++);

        c4.setCellValue("Linha");
        c4.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 5 NA LINHA 3
        XSSFCell c5 = row3.createCell(contadorCelulasCabecalho++);

        c5.setCellValue("Cor");
        c5.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 6 NA LINHA 3
        XSSFCell c6 = row3.createCell(contadorCelulasCabecalho++);

        c6.setCellValue("Col");
        c6.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 7 NA LINHA 3
        XSSFCell c7 = row3.createCell(contadorCelulasCabecalho++);

        c7.setCellValue("CI");
        c7.setCellStyle(estiloCabecalhoColunaP);

        //CRIA CLULA 8 NA LINHA 3
        XSSFCell c8 = row3.createCell(contadorCelulasCabecalho++);

        c8.setCellValue("CI Cum");
        c8.setCellStyle(estiloCabecalhoColunaP);

    }

    //VARI?VEIS INICIAIS DA ELABORAO DO RELATRIO
    int quantidadeCiclosTotais = (jogadasAux.size() / experimento.getTamanhoFilaJogadores());
    int contRowJogadas = 4;
    int contadorCiclo = 1;

    //INICIA LISTA DOS JOGADORES POR ORDEM
    List<Jogador> jogadoresAtuais = new ArrayList<>();
    int contOrdem = 1;
    for (int i = 0; i < quantidadeJogadoresPorCiclo; i++) {
        for (Jogador jgdr : jogadoresTotais) {
            if (jgdr.getOrdem() == contOrdem) {
                jogadoresAtuais.add(jgdr);
                contOrdem++;
                break;
            }
        }
    }

    //FAZ A REMOO DO(S) ELEMENTO(S) DA LISTA PRA POUPAR RECURSO EM BUSCA FUTURA
    jogadoresTotais.removeAll(jogadoresAtuais);

    //CRIA INSTNCIA CONTROLE DE PONTUAO CULTURAL
    int pontCulturalCiclo;

    //FOR (JOGADOR : JOGADORES POR CICLO)
    //CRIA LISTA DE CADA JOGADOR AT FIM DO CICLO
    for (int i = 0; i < quantidadeCiclosTotais; i++) {
        //PEGA JOGADAS DO CICLO
        List<Jogada> jogadasCiclo = new ArrayList<>();
        for (Jogada jogada : jogadasAux) {
            if (jogada.getRodada() == i + 1) {
                jogadasCiclo.add(jogada);
                if (jogadasCiclo.size() == quantidadeJogadoresPorCiclo) {
                    break;
                }
            }
        }
        //FAZ A REMOO DO(S) ELEMENTO(S) DA LISTA PRA POUPAR RECURSO EM BUSCA FUTURA
        jogadasAux.removeAll(jogadasCiclo);

        //VERIFICA SE A ORDEM MUDOU
        int contJogadoresIguais = 0;
        List<Jogada> jogadasARemover = new ArrayList<>();
        for (Jogador jogador : jogadoresAtuais) {
            for (Jogada jogada : jogadasCiclo) {
                if (jogada.getJogador().compareTo(jogador) == 0) {
                    jogador.setUltimaJogada(jogada);
                    jogador.incrementaPontuacaoRelatorio();
                    jogadasARemover.add(jogada);
                    contJogadoresIguais++;
                }
            }
        }

        jogadasCiclo.removeAll(jogadasARemover);

        boolean mudouGeracaoCiclo = false;
        if (contJogadoresIguais == quantidadeJogadoresPorCiclo) {
            //CONTINUA COM OS MESMOS JOGADORES
        } else {
            mudouGeracaoCiclo = true;
            Jogador jogadorARemover = new Jogador();
            jogadoresAtuais.remove(0);
            for (Jogador jgdr : jogadoresTotais) {
                if (jgdr.getOrdem() == contOrdem) {
                    //PEGA A PRIMEIRA POSIO PQ ESSA TEM QUE SER A NICA COM ELEMENTO
                    jgdr.setUltimaJogada(jogadasCiclo.get(0));
                    jgdr.incrementaPontuacaoRelatorio();
                    jogadoresAtuais.add(jgdr);
                    contOrdem++;
                    jogadorARemover = jgdr;
                    break;
                }
            }
            jogadoresTotais.remove(jogadorARemover);
        }
        // --- ENCERRA ETAPAS DE VERIFICAO, INICIA A POPULAO DE NOVA LINHA DO XLSX E
        //VERIFICA SE EXISTE PONTUAO CULTURAL.
        int contCellJogadas = 1;
        if (jogadoresAtuais.get(0).getUltimaJogada().getPontuacaoCultural() != 0) {
            pontCulturalCiclo = jogadoresAtuais.get(0).getUltimaJogada().getPontuacaoCultural();
            contadorAcertosCultural++;
        } else {
            pontCulturalCiclo = 0;
        }

        XSSFRow row = (XSSFRow) sheet.createRow((short) contRowJogadas);
        XSSFCell cell = row.createCell(contCellJogadas++);
        //CICLO
        if (contRowJogadas == 4 || mudouGeracaoCiclo == true) {
            //QUANDO HOUVER MUDANA DA GERAO
            cell.setCellValue(contadorCiclo++);
            cell.setCellStyle(estiloMudancaCiclo);
        } else {
            cell.setCellValue(contadorCiclo++);
            cell.setCellStyle(estiloCicloSemMudanca);
        }

        for (int j = 0; j < quantidadeJogadoresPorCiclo; j++) {

            //P
            XSSFCell cell1 = row.createCell(contCellJogadas++);
            cell1.setCellValue(jogadoresAtuais.get(j).getNome());
            cell1.setCellStyle(estiloNomeP);

            //Linha
            XSSFCell cell2 = row.createCell(contCellJogadas++);
            cell2.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getLinhaSelecionada());
            cell2.setCellStyle(estiloColunaLinha);

            //Cor
            XSSFCell cell3 = row.createCell(contCellJogadas++);
            cell3.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getCorSelecionada());
            cell3.setCellStyle(EstiloCelula.retornaEstilo(
                    jogadoresAtuais.get(j).getUltimaJogada().getCorSelecionada(), wb, fonteBranca, fonteNegra));

            //Col
            XSSFCell cell4 = row.createCell(contCellJogadas++);
            cell4.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getColunaSelecionada());
            cell4.setCellStyle(estiloColunaColuna);

            //CI
            XSSFCell cell5 = row.createCell(contCellJogadas++);
            cell5.setCellValue(jogadoresAtuais.get(j).getUltimaJogada().getPontuacaoIndividual());
            cell5.setCellStyle(estiloColunaColuna);

            //CI Cum
            XSSFCell cell6 = row.createCell(contCellJogadas++);
            cell6.setCellValue(jogadoresAtuais.get(j).getPontuacaoExibidaRelatorio());
            cell6.setCellStyle(estiloColunaColuna);
        }
        //CC
        XSSFCell cell7 = row.createCell(contCellJogadas++);
        cell7.setCellValue(pontCulturalCiclo);
        cell7.setCellStyle(estiloCabecalhoColunaAB);

        // ESTABILIDADE
        XSSFCell cell8 = row.createCell(contCellJogadas);
        cell8.setCellValue((contadorAcertosCultural * 100) / (i + 1) + "%");
        cell8.setCellStyle(estiloColunaColuna);

        contRowJogadas++;
    }

    //ESCREVE O ARQUIVO
    byte[] bytes;
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        wb.write(out);
        bytes = out.toByteArray();
    }
    return new ByteArrayInputStream(bytes);
}

From source file:business.SongExcelParser.java

private boolean writeWorkbookToFile(Workbook wb, File fileSelected) {
    try {//w  w w .j a va  2  s.c o m
        FileOutputStream fos = new FileOutputStream(fileSelected);
        wb.write(fos);
        fos.close();
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:campmanager.CampUI.java

public void exportToExcel() {
    JFrame parentFrame = new JFrame();
    File fileToSave = null;//from w w  w. j ava2s  .  co m
    ;
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Export to Excel");

    int userSelection = fileChooser.showSaveDialog(parentFrame);

    if (userSelection == JFileChooser.APPROVE_OPTION) {
        fileToSave = fileChooser.getSelectedFile();
        // System.out.println("Save as file: " + fileToSave.getAbsolutePath());
    }
    if (fileToSave != null) {

        String fileName = fileToSave.getAbsolutePath();
        if (!fileName.endsWith(".xls"))
            fileName += ".xls";
        try {
            DefaultTableModel dtm = (DefaultTableModel) jTable_records.getModel();
            Workbook wb = new HSSFWorkbook();
            CreationHelper createhelper = wb.getCreationHelper();
            Sheet sheet = wb.createSheet("new sheet");
            Row row = null;
            Cell cell = null;
            row = sheet.createRow(0);

            HSSFFont font = (HSSFFont) wb.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            HSSFCellStyle style = (HSSFCellStyle) wb.createCellStyle();

            style.setFont(font);

            for (int t = 0; t < dtm.getColumnCount() - 1; t++) {
                cell = row.createCell(t);
                cell.setCellStyle(style);
                cell.setCellValue(dtm.getColumnName(t));
            }

            HSSFCellStyle style_gray = (HSSFCellStyle) wb.createCellStyle();
            style_gray.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
            // style_gray.setFillPattern(CellStyle.ALT_BARS);
            for (int i = 1; i <= dtm.getRowCount(); i++) {
                row = sheet.createRow(i);

                for (int j = 0; j < dtm.getColumnCount() - 1; j++) {
                    cell = row.createCell(j);
                    if (i % 2 == 0)
                        cell.setCellStyle(style_gray);
                    cell.setCellValue(dtm.getValueAt(i - 1, j).toString());

                }
            }

            FileOutputStream out = new FileOutputStream(fileName);
            wb.write(out);
            out.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}