Example usage for org.apache.poi.xssf.usermodel XSSFSheet createRow

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet createRow

Introduction

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

Prototype

@Override
public XSSFRow createRow(int rownum) 

Source Link

Document

Create a new row within the sheet and return the high level representation Note: If a row already exists at this position, it is removed/overwritten and any existing cell is removed!

Usage

From source file:automatedhgl.AutomatedHGL.java

public static void main(String[] args) {

    try {/*from ww w . ja v  a 2 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:binaryproject.graphics.Juego.java

public void escribirExcel() throws FileNotFoundException, IOException, InvalidFormatException {
    long exitTime = System.currentTimeMillis();
    if (player != null) {
        // Actualiza el archivo de jugadores con la informacion que habia antes de cerrarse
        actualizarAchivoJugadoreS();/*from  www  . j  a v a2s .  c  o m*/
        // Actualiza el archivo del registro de sesiones
        EscritorDArchivos writer = new EscritorDArchivos(rutaArchivos + "logs.txt", true);
        String justAnotherLogForAnExistingPlayer = "";
        if (hasPlayerPastLogs(player.getNombre())) {
            ArrayList<Integer> logHistoryIndex = getPlayerSesionDataIndexes(player.getNombre());
            boolean[] loggedQuestions = new boolean[3];
            int i = 0;
            while (!loggedQuestions[0] && i < logHistoryIndex.size()) {
                int puntaje = Integer.parseInt(playerLogs.get(logHistoryIndex.get(i))[11]);
                if (puntaje > 3) {
                    loggedQuestions[0] = true;
                }
                i++;
            }
            i = 0;
            while (!loggedQuestions[1] && i < logHistoryIndex.size()) {
                int puntaje = Integer.parseInt(playerLogs.get(logHistoryIndex.get(i))[21]);
                if (puntaje > 3) {
                    loggedQuestions[1] = true;
                }
                i++;
            }
            i = 0;
            while (!loggedQuestions[2] && i < logHistoryIndex.size()) {
                int puntaje = Integer.parseInt(playerLogs.get(logHistoryIndex.get(i))[31]);
                if (puntaje > 3) {
                    loggedQuestions[2] = true;
                }
                i++;
            }
            justAnotherLogForAnExistingPlayer += player.getID() + ";" + player.getNombre() + ";"
                    + (playerLogs.size() + 1) + ";" + player.getLastTimeLogin() + ";" + exitTime + ";"
                    + (exitTime - player.getLastTimeLogin()) + ";";
            if (!loggedQuestions[0]) {
                justAnotherLogForAnExistingPlayer += getCorrectQuestionsIndividually(1);
                justAnotherLogForAnExistingPlayer += getAmmountOfCorrectQuestions(1) + ";";
                justAnotherLogForAnExistingPlayer += player.getTiempos().get(0)[0] + ";"
                        + player.getTiempos().get(0)[1] + ";" + player.getTiempos().get(0)[2] + ";";
            } else {
                justAnotherLogForAnExistingPlayer += "0;0;0;0;0;0;";
                justAnotherLogForAnExistingPlayer += "0;0;0;";
            }
            //Agregar STN1
            long STN = 0;
            if (logHistoryIndex.size() != 0 && !loggedQuestions[0]) {
                for (int j = 0; j < logHistoryIndex.size(); j++) {
                    STN += Long.parseLong(playerLogs.get(logHistoryIndex.get(j))[14]);
                }
                STN += player.getTiempos().get(0)[2];
                if (STN != 0) {
                    player.changeWritenState(0, true);
                }
            }
            justAnotherLogForAnExistingPlayer += STN + ";";
            if (!loggedQuestions[1]) {
                justAnotherLogForAnExistingPlayer += getCorrectQuestionsIndividually(2);
                justAnotherLogForAnExistingPlayer += getAmmountOfCorrectQuestions(2) + ";";
                justAnotherLogForAnExistingPlayer += player.getTiempos().get(1)[0] + ";"
                        + player.getTiempos().get(1)[1] + ";" + player.getTiempos().get(1)[2] + ";";
            } else {
                justAnotherLogForAnExistingPlayer += "0;0;0;0;0;0;";
            }
            //Agregar SNT2
            STN = 0;
            if (logHistoryIndex.size() != 0 && !loggedQuestions[1]) {
                for (int j = 0; j < logHistoryIndex.size(); j++) {
                    STN += Long.parseLong(playerLogs.get(logHistoryIndex.get(j))[24]);
                }
                STN += player.getTiempos().get(1)[2];
                if (STN != 0) {
                    player.changeWritenState(1, true);
                }
            }
            justAnotherLogForAnExistingPlayer += STN + ";";
            if (!loggedQuestions[2]) {
                justAnotherLogForAnExistingPlayer += getCorrectQuestionsIndividually(3);
                justAnotherLogForAnExistingPlayer += getAmmountOfCorrectQuestions(3) + ";";
                justAnotherLogForAnExistingPlayer += player.getTiempos().get(2)[0] + ";"
                        + player.getTiempos().get(2)[1] + ";" + player.getTiempos().get(2)[2] + ";";
            } else {
                justAnotherLogForAnExistingPlayer += "0;0;0;0;0;0;";
            }
            //Agregar SNT3
            STN = 0;
            if (logHistoryIndex.size() != 0 && !loggedQuestions[2]) {
                for (int j = 0; j < logHistoryIndex.size(); j++) {
                    STN += Long.parseLong(playerLogs.get(logHistoryIndex.get(j))[34]);
                }
                STN += player.getTiempos().get(2)[2];
                if (STN != 0) {
                    player.changeWritenState(2, true);
                }
            }
            justAnotherLogForAnExistingPlayer += STN + ";";
            //Cargar el CT Total
            justAnotherLogForAnExistingPlayer += player.getScore() + ";";
            long spentTime = 0;
            for (int j = 0; j < logHistoryIndex.size(); j++) {
                spentTime += Long.parseLong(playerLogs.get(logHistoryIndex.get(j))[5]);
            }
            justAnotherLogForAnExistingPlayer += (spentTime + (exitTime - player.getLastTimeLogin()));
        } else {
            justAnotherLogForAnExistingPlayer += player.getID() + ";" + player.getNombre() + ";"
                    + (playerLogs.size() + 1) + ";" + player.getLastTimeLogin() + ";" + exitTime + ";"
                    + (exitTime - player.getLastTimeLogin()) + ";";
            //Terminar de rellenar con el resto de informacion de toda la sesion
            justAnotherLogForAnExistingPlayer += getCorrectQuestionsIndividually(1);
            justAnotherLogForAnExistingPlayer += getAmmountOfCorrectQuestions(1) + ";";
            justAnotherLogForAnExistingPlayer += player.getTiempos().get(0)[0] + ";"
                    + player.getTiempos().get(0)[1] + ";" + player.getTiempos().get(0)[2] + ";";
            justAnotherLogForAnExistingPlayer += player.getTiempos().get(0)[2] + ";"; //STN1
            justAnotherLogForAnExistingPlayer += getCorrectQuestionsIndividually(2);
            justAnotherLogForAnExistingPlayer += getAmmountOfCorrectQuestions(2) + ";";
            justAnotherLogForAnExistingPlayer += player.getTiempos().get(1)[0] + ";"
                    + player.getTiempos().get(1)[1] + ";" + player.getTiempos().get(1)[2] + ";";
            justAnotherLogForAnExistingPlayer += player.getTiempos().get(1)[2] + ";"; //STN2
            justAnotherLogForAnExistingPlayer += getCorrectQuestionsIndividually(3);
            justAnotherLogForAnExistingPlayer += getAmmountOfCorrectQuestions(3) + ";";
            justAnotherLogForAnExistingPlayer += player.getTiempos().get(2)[0] + ";"
                    + player.getTiempos().get(2)[1] + ";" + player.getTiempos().get(2)[2] + ";";
            justAnotherLogForAnExistingPlayer += player.getTiempos().get(2)[2] + ";"; //STN3
            justAnotherLogForAnExistingPlayer += player.getScore() + ";";
            justAnotherLogForAnExistingPlayer += exitTime - player.getLastTimeLogin();
        }
        writer.escribir(justAnotherLogForAnExistingPlayer);
        writer.cerrar();
        ////////////////////////////////////////////////////////////////////
        ///////////Pasar la infrmacion a archivo excel//////////////////////
        ////////////////////////////////////////////////////////////////////
        LectorDArchivos reader = new LectorDArchivos(rutaArchivos + "logs.txt");
        XSSFWorkbook libro = new XSSFWorkbook();
        XSSFSheet hoja = libro.createSheet("Test");
        XSSFRow row;
        String[] informacion;
        String cellValue;
        int rowNumber = 0;
        reader.leerLinea();
        while (reader.getLineaActual() != null) {
            informacion = reader.getLineaActual().split(";");
            row = hoja.createRow(rowNumber);
            for (int i = 0; i < informacion.length; i++) {
                cellValue = informacion[i];
                row.createCell(i).setCellValue(cellValue);
            }
            reader.leerLinea();
            rowNumber++;
        }
        new File(rutaArchivos + "estadisticas.xls").delete();
        FileOutputStream archivoFinal = new FileOutputStream(new File(rutaArchivos + "estadisticas.xls"));
        libro.write(archivoFinal);
        archivoFinal.close();
    }
}

From source file:br.com.jinsync.controller.ExportExcelBook.java

License:Open Source License

@Override
protected Object doInBackground() throws Exception {

    final String dir = System.getProperty("user.dir") + "\\layouts";

    File arqProp = new File(dir);
    if (!arqProp.exists()) {
        arqProp.mkdirs();// w  ww.  ja  va2 s . c  o  m
    }

    String nameFile = this.nameFile;

    int lin = 0;
    int col = 0;
    int pos = 0;
    int posFim = 0;

    pos = nameFile.lastIndexOf("(");
    if (pos > 0) {
        posFim = nameFile.lastIndexOf(")");
        nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_layout" + ".xlsx";
    } else {
        pos = nameFile.lastIndexOf("\\");
        if (pos > 0) {
            posFim = nameFile.lastIndexOf(".");
            if (posFim > 0) {
                nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_layout" + ".xlsx";
            } else {
                nameFile = dir + nameFile.substring(pos) + "_layout" + ".xlsx";
            }
        }
    }

    FileOutputStream out;

    try {
        out = new FileOutputStream(nameFile);
        TableModel model = tableName.getModel();

        XSSFWorkbook wb = new XSSFWorkbook(); // Criando area de trabalho
        // para o excel
        XSSFSheet s = wb.createSheet(); // criando uma nova sheet

        XSSFFont f = wb.createFont();
        XSSFFont f2 = wb.createFont();

        XSSFCellStyle cs = wb.createCellStyle();
        XSSFCellStyle cs2 = wb.createCellStyle();
        XSSFCellStyle cs3 = wb.createCellStyle();
        XSSFCellStyle cs4 = wb.createCellStyle();

        f.setFontHeightInPoints((short) 8);
        f2.setFontHeightInPoints((short) 8);

        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        f.setFontName("Courier New");
        f2.setFontName("Courier New");

        XSSFRow r = null; // Criando uma referencia para Linha
        XSSFCell c = null; // Referencia para Celula

        cs.setFont(f);
        cs2.setFont(f2);
        cs3.setFont(f2);
        cs4.setFont(f);

        cs2.setAlignment(CellStyle.ALIGN_LEFT);
        cs3.setAlignment(CellStyle.ALIGN_RIGHT);
        cs4.setAlignment(CellStyle.ALIGN_RIGHT);

        r = s.createRow(lin);
        for (int i = 1; i < model.getColumnCount(); i++) {
            c = r.createCell(col);
            c.setCellStyle(cs);
            c.setCellValue(model.getColumnName(i));
            col = col + 1;
        }

        col = 0;
        for (int i = 0; i < model.getRowCount(); i++) {
            lin = lin + 1;
            r = s.createRow(lin);
            col = 0;
            for (int j = 1; j < model.getColumnCount(); j++) {
                String valor = model.getValueAt(i, j).toString();
                if (valor == null) {
                    valor = "";
                }

                c = r.createCell(col);
                c.setCellStyle(cs2);

                if (valor.matches("-?\\d+(\\.\\d+)?")) {
                    c.setCellValue(Double.parseDouble(valor));
                    c.setCellType(Cell.CELL_TYPE_NUMERIC);
                    c.setCellStyle(cs4);
                } else {
                    c.setCellValue(valor);
                }
                col = col + 1;
            }
        }

        for (int i = 0; i <= model.getColumnCount(); i++) {
            s.autoSizeColumn(i);
        }

        wb.write(out);
        wb.close();
        out.close();

        Desktop desktop = Desktop.getDesktop();
        desktop.open(new File(nameFile));

    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    }

    return null;

}

From source file:br.com.jinsync.controller.ExportExcelFile.java

License:Open Source License

@Override
protected Object doInBackground() throws Exception {

    int valuePgsBar = 0;
    int qtdTotLin = 0;

    final String dir = System.getProperty("user.dir") + "\\file";

    File arqProp = new File(dir);
    if (!arqProp.exists()) {
        arqProp.mkdirs();/* w w w.  jav  a  2 s.  c om*/
    }

    String nameFile = name;

    int lin = 0;
    int col = 0;
    int pos = 0;
    int posEnd = 0;

    pos = nameFile.lastIndexOf("(");
    if (pos > 0) {
        posEnd = nameFile.lastIndexOf(")");
        nameFile = dir + "\\" + nameFile.substring(pos + 1, posEnd) + "_file" + ".xlsx";
    } else {
        pos = nameFile.lastIndexOf("\\");
        if (pos > 0) {
            posEnd = nameFile.lastIndexOf(".");
            if (posEnd > 0) {
                nameFile = dir + "\\" + nameFile.substring(pos + 1, posEnd) + "_file" + ".xlsx";
            } else {
                nameFile = dir + nameFile.substring(pos) + "_file" + ".xlsx";
            }
        }
    }

    FileOutputStream out;

    try {
        out = new FileOutputStream(nameFile);
        TableModel model = tableName.getModel();

        XSSFWorkbook wb = new XSSFWorkbook(); // Criando area de trabalho
        // para o excel
        XSSFSheet s = wb.createSheet(); // criando uma nova sheet

        XSSFFont f = wb.createFont();
        XSSFFont f2 = wb.createFont();

        XSSFCellStyle cs = wb.createCellStyle();
        XSSFCellStyle cs2 = wb.createCellStyle();
        XSSFCellStyle cs3 = wb.createCellStyle();
        XSSFCellStyle cs4 = wb.createCellStyle();

        f.setFontHeightInPoints((short) 8);
        f2.setFontHeightInPoints((short) 8);

        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        f.setFontName("Courier New");
        f2.setFontName("Courier New");

        XSSFRow r = null; // Criando uma referencia para Linha
        XSSFCell c = null; // Referencia para Celula

        cs.setFont(f);
        cs2.setFont(f2);
        cs3.setFont(f2);
        cs4.setFont(f2);

        cs2.setAlignment(CellStyle.ALIGN_LEFT);
        cs3.setAlignment(CellStyle.ALIGN_RIGHT);
        cs4.setAlignment(CellStyle.ALIGN_RIGHT);

        r = s.createRow(lin);
        for (int i = 1; i < model.getColumnCount(); i++) {
            c = r.createCell(col);
            c.setCellStyle(cs);
            c.setCellValue(model.getColumnName(i));
            col = col + 1;
        }

        col = 0;
        qtdTotLin = model.getRowCount() - 1;

        if (qtdTotLin == 0) {
            qtdTotLin = 1;
        }

        for (int i = 0; i < model.getRowCount(); i++) {
            valuePgsBar = (i * 100) / qtdTotLin;
            lin = lin + 1;
            r = s.createRow(lin);
            col = 0;
            for (int j = 1; j < model.getColumnCount(); j++) {
                String valor = model.getValueAt(i, j).toString();
                if (valor == null) {
                    valor = "";
                }

                c = r.createCell(col);
                c.setCellStyle(cs2);

                valor = valor.trim();
                if (valor.matches("-?\\d+(\\.\\d+)?")) {
                    c.setCellValue(Double.parseDouble(valor));
                    c.setCellType(Cell.CELL_TYPE_NUMERIC);
                    c.setCellStyle(cs4);
                } else {
                    c.setCellValue(valor);
                }
                col = col + 1;
                setProgress(valuePgsBar);
            }
        }

        for (int i = 0; i <= model.getColumnCount(); i++) {
            s.autoSizeColumn(i);
        }

        wb.write(out);
        wb.close();
        out.close();

        Desktop desktop = Desktop.getDesktop();
        desktop.open(new File(nameFile));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:br.com.jinsync.controller.ExportExcelString.java

License:Open Source License

@Override
protected Object doInBackground() throws Exception {

    final String dir = System.getProperty("user.dir") + "\\string";

    File arqProp = new File(dir);
    if (!arqProp.exists()) {
        arqProp.mkdirs();//from www  .j  a  v  a 2  s  . c  o  m
    }

    String nameFile = this.nameFile;

    int lin = 0;
    int col = 0;
    int pos = 0;
    int posFim = 0;
    int valDec = 0;

    pos = nameFile.lastIndexOf("(");
    if (pos > 0) {
        posFim = nameFile.lastIndexOf(")");
        nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_string" + ".xlsx";
    } else {
        pos = nameFile.lastIndexOf("\\");
        if (pos > 0) {
            posFim = nameFile.lastIndexOf(".");
            if (posFim > 0) {
                nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_string" + ".xlsx";
            } else {
                nameFile = dir + nameFile.substring(pos) + "_string" + ".xlsx";
            }
        }
    }

    FileOutputStream out;

    try {
        out = new FileOutputStream(nameFile);
        TableModel model = tableName.getModel();

        XSSFWorkbook wb = new XSSFWorkbook(); // Criando area de trabalho
        // para o excel
        XSSFSheet s = wb.createSheet(); // criando uma nova sheet

        XSSFFont f = wb.createFont();
        XSSFFont f2 = wb.createFont();

        XSSFCellStyle cs = wb.createCellStyle();
        XSSFCellStyle cs2 = wb.createCellStyle();
        XSSFCellStyle cs3 = wb.createCellStyle();
        XSSFCellStyle cs4 = wb.createCellStyle();

        f.setFontHeightInPoints((short) 8);
        f2.setFontHeightInPoints((short) 8);

        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        f.setFontName("Courier New");
        f2.setFontName("Courier New");

        XSSFRow r = null; // Criando uma referencia para Linha
        XSSFCell c = null; // Referencia para Celula

        cs.setFont(f);
        cs2.setFont(f2);
        cs3.setFont(f2);
        cs4.setFont(f);

        cs2.setAlignment(CellStyle.ALIGN_LEFT);
        cs3.setAlignment(CellStyle.ALIGN_RIGHT);
        cs4.setAlignment(CellStyle.ALIGN_RIGHT);

        r = s.createRow(lin);

        r = s.createRow(0); // Criando a primeira linha na LINHA zero, que
        // seria o nmero 1
        c = r.createCell(0); // Criando a celula na posicao ZERO, que seria
                             // A, com referencia na linha zero acima =
                             // A1
        c.setCellStyle(cs);
        c.setCellValue(Language.stringFieldName);

        c = r.createCell(1);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringType);

        c = r.createCell(2);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringLength);

        c = r.createCell(3);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringDecimal);

        c = r.createCell(4);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringTotal);

        c = r.createCell(5);
        c.setCellStyle(cs4);
        c.setCellValue(Language.stringContent);

        col = 0;
        lin = lin + 1;
        for (int i = 0; i < model.getColumnCount(); i++) {

            r = s.createRow(lin);
            c = r.createCell(col);
            c.setCellStyle(cs2);
            c.setCellValue(model.getColumnName(i));

            col = col + 1;

            c = r.createCell(col);
            c.setCellStyle(cs2);
            c.setCellValue(tipoConteudo.get(i));

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);
            if (tamanhoConteudo.get(i).matches("-?\\d+(\\.\\d+)?")) {
                c.setCellValue(Double.parseDouble(tamanhoConteudo.get(i)));
                c.setCellType(Cell.CELL_TYPE_NUMERIC);
                c.setCellStyle(cs3);
            } else {
                c.setCellValue(tamanhoConteudo.get(i));
            }

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);
            if (decimalConteudo.get(i).matches("-?\\d+(\\.\\d+)?")) {
                c.setCellValue(Integer.parseInt(decimalConteudo.get(i)));
                valDec = Integer.parseInt(decimalConteudo.get(i));
                c.setCellType(Cell.CELL_TYPE_NUMERIC);
                c.setCellStyle(cs3);
            } else {
                c.setCellValue(decimalConteudo.get(i));
                valDec = 0;
            }

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);
            c.setCellValue(totalConteudo.get(i));

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);

            String valor = model.getValueAt(0, i).toString().trim();
            if (valor == null) {
                valor = "";
            }

            if (valor.matches("-?\\d+(\\.\\d+)?")) {

                if (Double.parseDouble(valor) > 0 && valDec > 0) {
                    double val2 = Double.parseDouble(valor) / (Math.pow(10, valDec));
                    NumberFormat format = NumberFormat.getInstance();
                    format.setMinimumFractionDigits(2);
                    format.setMaximumFractionDigits(valDec);
                    c.setCellValue(format.format(val2).toString());

                } else {
                    c.setCellValue(Double.parseDouble(valor));
                }

                // c.setCellType(Cell.CELL_TYPE_NUMERIC);
                c.setCellStyle(cs3);
            } else {
                c.setCellValue(valor);
            }

            lin = lin + 1;
            col = 0;
        }

        for (int i = 0; i <= model.getColumnCount(); i++) {
            s.autoSizeColumn(i);
        }

        wb.write(out);
        wb.close();
        out.close();

        Desktop desktop = Desktop.getDesktop();
        desktop.open(new File(nameFile));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        //e.printStackTrace();
    }

    return null;
}

From source file:br.uff.ic.kraken.extractdata.excel.ConflictingChunkData.java

public static void main(String[] args) {

    String bdName = "automaticAnalysisUpdated";
    String outputPath = "/Users/gleiph/Dropbox/doutorado/publication/TSE Manual + Automatic/TSE 2/report1.0.xlsx";

    //Excel stuff
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Data");
    int rowNumber = 0;

    XSSFRow row = sheet.createRow(rowNumber);
    XSSFCell cell = row.createCell(PROJECT_ID);
    cell.setCellValue("Project ID");

    row = sheet.createRow(rowNumber++);//www.j  av a2  s  .  c o  m
    cell = row.createCell(PROJECT_NAME);
    cell.setCellValue("Project name");

    cell = row.createCell(REVISION_SHA);
    cell.setCellValue("Revision SHA");

    cell = row.createCell(FILE_NAME);
    cell.setCellValue("File name");

    cell = row.createCell(CONFLICTING_CHUNK_IDENTIFIER);
    cell.setCellValue("Conflicting chunk identifier");

    cell = row.createCell(OUTMOST_KIND_CONFLICT);
    cell.setCellValue("Kind of conflict");

    cell = row.createCell(AMOUNT_LANGUAGE_CONSTRUCTS);
    cell.setCellValue("#Language constructs");

    cell = row.createCell(DEVELOPER_DECISION);
    cell.setCellValue("Developer decision");

    cell = row.createCell(LOC_VERSION_1);
    cell.setCellValue("#LOC Version 1");

    cell = row.createCell(LOC_VERSION_2);
    cell.setCellValue("#LOC Version 2");

    cell = row.createCell(DEVELOPERS);
    cell.setCellValue("Developers");

    try (Connection connection = (new JDBCConnection()).getConnection(bdName)) {

        ProjectJDBCDAO projectDAO = new ProjectJDBCDAO(connection);
        RevisionJDBCDAO revisionDAO = new RevisionJDBCDAO(connection);
        ConflictingFileJDBCDAO conflictingFileDAO = new ConflictingFileJDBCDAO(connection);
        ConflictingChunkJDBCDAO conflictingChunkDAO = new ConflictingChunkJDBCDAO(connection);

        List<Project> projects = projectDAO.selectAnalyzedMainProjects();

        for (Project project : projects) {

            System.out.println(project.getName());

            List<Revision> revisions = revisionDAO.selectByProjectId(project.getId());
            for (Revision revision : revisions) {

                List<ConflictingFile> conflictingFiles = conflictingFileDAO
                        .selectByRevisionId(revision.getId());
                for (ConflictingFile conflictingFile : conflictingFiles) {

                    if (!conflictingFile.getName().toLowerCase().endsWith(".java")) {
                        continue;
                    }

                    List<ConflictingChunk> conflictingChunks = conflictingChunkDAO
                            .selectByConflictingFileId(conflictingFile.getId());
                    for (ConflictingChunk conflictingChunk : conflictingChunks) {

                        row = sheet.createRow(rowNumber++);
                        cell = row.createCell(PROJECT_ID);
                        cell.setCellValue(project.getId());
                        //                            System.out.print(project.getId() + ", ");

                        cell = row.createCell(PROJECT_NAME);
                        cell.setCellValue(project.getName());
                        //                            System.out.print(project.getName() + ", ");

                        cell = row.createCell(REVISION_SHA);
                        cell.setCellValue(revision.getSha());
                        //                            System.out.print(revision.getSha() + ", ");

                        cell = row.createCell(FILE_NAME);
                        cell.setCellValue(conflictingFile.getName());
                        //                            System.out.print(conflictingFile.getName() + ", ");

                        cell = row.createCell(CONFLICTING_CHUNK_IDENTIFIER);
                        cell.setCellValue(conflictingChunk.getId());
                        //                            System.out.print(conflictingChunk.getIdentifier() + ", ");

                        String generalKindConflictOutmost = conflictingChunk.getGeneralKindConflictOutmost();
                        cell = row.createCell(OUTMOST_KIND_CONFLICT);
                        String newKindConflict = replaceAttributeByVariable(generalKindConflictOutmost);

                        cell.setCellValue(newKindConflict);
                        //                            System.out.print(generalKindConflictOutmost + ", ");

                        String[] languageConstructs = generalKindConflictOutmost.split(", ");
                        cell = row.createCell(AMOUNT_LANGUAGE_CONSTRUCTS);
                        cell.setCellValue(languageConstructs.length);
                        //                                                        System.out.print(languageConstructs.length + ", ");

                        String developerDecision = conflictingChunk.getDeveloperDecision().toString();
                        cell = row.createCell(DEVELOPER_DECISION);
                        cell.setCellValue(developerDecision);
                        //                            System.out.print(developerDecision + ", ");

                        int locVersion1 = conflictingChunk.getSeparatorLine() - conflictingChunk.getBeginLine()
                                - 1;
                        int locVersion2 = conflictingChunk.getEndLine() - conflictingChunk.getSeparatorLine()
                                - 1;

                        cell = row.createCell(LOC_VERSION_1);
                        cell.setCellValue(locVersion1);

                        cell = row.createCell(LOC_VERSION_2);
                        cell.setCellValue(locVersion2);
                        //                            System.out.println(locVersion1 + ", " + locVersion2);

                        cell = row.createCell(DEVELOPERS);
                        cell.setCellValue(project.getDevelopers());

                        if (rowNumber % 10 == 0) {
                            FileOutputStream out;
                            out = new FileOutputStream(outputPath);
                            wb.write(out);
                            out.close();

                        }

                    }
                }
            }

        }

    } catch (SQLException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        FileOutputStream out;
        out = new FileOutputStream(outputPath);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ConflictingChunkData.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:BUS.FileManager.java

public void exportToXLSXFile(String fileName) throws FileNotFoundException, IOException {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();
    List<LichThi> Data = LichThiManager.getInstance().getDsLichThi();
    int rowNum = 0;
    // set title/*from   w ww. ja  v a  2  s.c  o m*/
    Row row = sheet.createRow(rowNum++);
    Cell cell = row.createCell(0);
    cell.setCellValue("M Lp");
    cell = row.createCell(1);
    cell.setCellValue("Tn MH");
    cell = row.createCell(2);
    cell.setCellValue("SBD");
    cell = row.createCell(3);
    cell.setCellValue("Phng");
    cell = row.createCell(4);
    cell.setCellValue("Ngy");
    cell = row.createCell(5);
    cell.setCellValue("Ca");

    // set contents
    for (LichThi lt : Data) {
        row = sheet.createRow(rowNum++);
        int cellNum = 0;

        for (int i = 0; i < 6; i++) {
            cell = row.createCell(cellNum++);
            cell.setCellValue(lt.getValueAt(i));
        }
    }

    try (FileOutputStream fos = new FileOutputStream(new File(fileName))) {
        wb.write(fos);
        fos.close();
    }
}

From source file:Business.ExcelReportCreator.java

public static int create(EcoSystem system) {

    //          Steps:-
    //          Create a Workbook.
    //          Create a Sheet.
    //          Repeat the following steps until all data is processed:
    //          Create a Row.
    //          Create Cells in a Row. Apply formatting using CellStyle.
    //          Write to an OutputStream.
    //          Close the output stream.

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Customer Details");

    //Custom font style for header
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    Font font = sheet.getWorkbook().createFont();
    font.setBold(true);/*from   ww  w .  j  ava 2 s .  co  m*/
    cellStyle.setFont(font);

    int rowCount = 0;
    int columnCount1 = 0;

    //Creating header row

    String s[] = { "CUSTOMER ID", "CUSTOMER NAME", "CONTACT NO.", "EMAIL ID", "USAGE(Gallons)", "BILLING DATE",
            "TOTAL BILL($)" };
    Row row1 = sheet.createRow(++rowCount);
    for (String s1 : s) {
        Cell header = row1.createCell(++columnCount1);
        header.setCellValue(s1);
        header.setCellStyle(cellStyle);
    }

    for (Network network : system.getNetworkList()) {
        for (Enterprise enterprise : network.getEnterpriseDirectory().getEnterpriseList()) {
            if (enterprise instanceof WaterEnterprise) {
                for (Organization organization : enterprise.getOrganizationDirectory().getOrganizationList()) {
                    if (organization instanceof CustomerOrganization) {
                        for (Employee employee : organization.getEmployeeDirectory().getEmployeeList()) {
                            Customer customer = (Customer) employee;
                            Row row = sheet.createRow(++rowCount);
                            int columnCount = 0;
                            for (int i = 0; i < 7; i++) {
                                Cell cell = row.createCell(++columnCount);
                                if (i == 0) {
                                    cell.setCellValue(customer.getId());
                                } else if (i == 1) {
                                    cell.setCellValue(customer.getName());
                                } else if (i == 2) {
                                    cell.setCellValue(customer.getContactNo());
                                } else if (i == 3) {
                                    cell.setCellValue(customer.getEmailId());
                                } else if (i == 4) {
                                    cell.setCellValue(customer.getTotalUsageVolume());
                                } else if (i == 5) {
                                    if (customer.getBillingDate() != null)
                                        cell.setCellValue(String.valueOf(customer.getBillingDate()));
                                    else
                                        cell.setCellValue("Bill Not yet available");
                                } else if (i == 6) {
                                    if (customer.getTotalBill() != 0)
                                        cell.setCellValue(customer.getTotalBill());
                                    else
                                        cell.setCellValue("Bill Not yet available");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    try (FileOutputStream outputStream = new FileOutputStream("Customer_details.xlsx")) {
        workbook.write(outputStream);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "File not found");
        return 0;
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "IOException");
        return 0;
    }
    return 1;
}

From source file:CE.CyberedgeInterface.java

public void toExcel() {

    try {/*from   w  ww  .java  2s. com*/
        con = DbConnection.getConnection();
        String query = "Select * from Candidates_record";
        ps = con.prepareStatement(query);
        rs = ps.executeQuery();

        XSSFWorkbook w = new XSSFWorkbook();
        XSSFSheet ws = w.createSheet("Candidates Record");
        XSSFRow header = ws.createRow(0);
        header.createCell(0).setCellValue("ID");
        header.createCell(1).setCellValue("Name");
        header.createCell(2).setCellValue("Position");
        header.createCell(3).setCellValue("Client");
        header.createCell(4).setCellValue("Location");
        header.createCell(5).setCellValue("Contact");
        header.createCell(6).setCellValue("Email");
        header.createCell(7).setCellValue("Experience");
        header.createCell(8).setCellValue("Remark");

        ws.setColumnWidth(1, 256 * 25);
        ws.setColumnWidth(2, 256 * 25);
        ws.setColumnWidth(3, 256 * 25);
        ws.setColumnWidth(4, 256 * 25);
        ws.setColumnWidth(5, 256 * 25);
        ws.setColumnWidth(6, 256 * 25);
        ws.setColumnWidth(7, 256 * 25);
        ws.setColumnWidth(8, 256 * 25);
        ws.setColumnWidth(9, 256 * 25);
        int index = 1;
        while (rs.next()) {
            XSSFRow row = ws.createRow(index);
            row.createCell(0).setCellValue(rs.getInt("Candidate_id"));
            row.createCell(1).setCellValue(rs.getString("Name"));
            row.createCell(2).setCellValue(rs.getString("Position"));
            row.createCell(3).setCellValue(rs.getString("Client"));
            row.createCell(4).setCellValue(rs.getString("Location"));
            row.createCell(5).setCellValue(rs.getString("Contact"));
            row.createCell(6).setCellValue(rs.getString("Email"));
            row.createCell(7).setCellValue(rs.getInt("Experience"));
            row.createCell(8).setCellValue(rs.getString("Remark"));
            index++;

        }
        String file = "C:\\..\\..\\..\\..\\..\\Cyberedge\\CandidateDetails.xlsx";
        FileOutputStream fileout = new FileOutputStream(file);
        w.write(fileout);

        fileout.close();

        JOptionPane.showMessageDialog(null, "File Saved");

        ps.close();
        rs.close();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

From source file:ch.admin.isb.hermes5.business.userszenario.projektstrukturplan.ProjektstrukturplanGeneratorExcel.java

License:Apache License

private int addPhase(XSSFSheet sheet, int currentRow, Phase phase, LocalizationEngine localizationEngine,
        XSSFCellStyle ergebnisStyle, XSSFCellStyle modulStyle, XSSFCellStyle defaultStyle,
        SzenarioItem szenarioTree) {//from   ww w .  j a  v  a 2  s.  c  om
    XSSFRow row = sheet.createRow(currentRow++);
    XSSFCell phaseCell = row.createCell(MAIN_COL);
    phaseCell.setCellStyle(defaultStyle);
    String phaseName = localizationEngine.localize(phase.getPresentationName());
    phaseCell.setCellValue(isNotBlank(phaseName) ? phaseName.toUpperCase() : phaseName);
    List<Aufgabe> aufgabenInPhase = phase.getAufgaben();
    List<Modul> module = phase.getModule();
    for (Modul modul : module) {
        currentRow = addModul(sheet, currentRow, localizationEngine, ergebnisStyle, modulStyle, defaultStyle,
                phase, modul, aufgabenInPhase, szenarioTree);
    }
    return currentRow;
}