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

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

Introduction

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

Prototype

Sheet createSheet(String sheetname);

Source Link

Document

Create a new sheet for this Workbook and return the high level representation.

Usage

From source file:Control.CtrlTema.java

public File writeExcelFile(String nombreArchivo) throws IOException {
    Collection preguntaTemaArray = new ArrayList<Pregunta_Tema>();
    Tema tema = new Tema();

    /*La ruta donde se crear el archivo*/
    String rutaArchivo = fileNameWrite + "/" + nombreArchivo + ".xls";
    /*Se crea el objeto de tipo File con la ruta del archivo*/
    File archivoXLS = new File(rutaArchivo);
    /*Si el archivo existe se elimina*/
    if (archivoXLS.exists()) {
        archivoXLS.delete();/*from   ww  w .  j  a  va 2s  .c  om*/
    }
    /*Se crea el archivo*/
    archivoXLS.createNewFile();

    /*Se crea el libro de excel usando el objeto de tipo Workbook*/
    Workbook libro = new HSSFWorkbook();
    /*Se inicializa el flujo de datos con el archivo xls*/
    FileOutputStream archivo = new FileOutputStream(archivoXLS);

    //Ciclo para los temas
    int j = 0;
    while (j <= 10) {
        tema = cargarTema(j);
        preguntaTemaArray = tema.getPreguntas();
        Iterator itPreguntaTemaArray = preguntaTemaArray.iterator();
        int pregunta = 0;
        String respuesta = "";
        /*Utilizamos la clase Sheet para crear una nueva hoja de trabajo dentro del libro que creamos anteriormente*/
        Sheet hoja = libro.createSheet("Tema " + j);
        //Ciclo para preguntaTema
        int f = 0;
        int a = preguntaTemaArray.size() + 1;
        while (f < a) {
            //  while (itPreguntaTemaArray.hasNext()) {

            /*Hacemos un ciclo para inicializar los valores de 10 filas de celdas*/
            /*La clase Row nos permitir crear las filas*/
            Row fila = hoja.createRow(f);

            for (int c = 0; c < 2; c++) {
                /*Creamos la celda a partir de la fila actual*/
                Cell celda = fila.createCell(c);

                /*Si la fila es la nmero 0, estableceremos los encabezados*/
                if (f == 0 && c == 0) {
                    celda.setCellValue("Pregunta");
                } else if (f == 0 && c == 1) {
                    celda.setCellValue("Respuesta");
                } else if (f != 0 && c == 1) {
                    /*Si no es la primera fila establecemos un valor*/
                    celda.setCellValue(respuesta);
                } else {
                    /*Si no es la primera fila establecemos un valor*/
                    celda.setCellValue(pregunta);
                }
            }

            f = f + 1;
            if (f < a) {
                Pregunta_Tema pt = (Pregunta_Tema) itPreguntaTemaArray.next();

                pregunta = pt.getNroPregunta();

                int rta = pt.getRespuesta();
                if (rta == 1) {
                    respuesta = "A";
                } else if (rta == 2) {
                    respuesta = "B";
                } else if (rta == 3) {
                    respuesta = "C";
                } else if (rta == 4) {
                    respuesta = "D";
                }
            }

        }
        j++;
    }
    /*Escribimos en el libro*/
    libro.write(archivo);
    /*Cerramos el flujo de datos*/
    archivo.close();
    /*Y abrimos el archivo con la clase Desktop*/

    return archivoXLS;
}

From source file:Controlador.GenerarCvs.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w  .  j a  v  a2 s .  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        ResultSet resultadoBD;
        GestionBD GestionBD = new GestionBD();
        resultadoBD = GestionBD.consultas();

        try {
            int r = 0;
            while (resultadoBD.next()) {
                BD1[r] = resultadoBD.getString("nom");
                BD2[r] = resultadoBD.getString("ape");
                BD3[r] = resultadoBD.getString("pais");
                BD4[r] = resultadoBD.getString("muni");
                BD5[r] = resultadoBD.getString("correo");
                r++;
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage() + "XDDDD");
        }

        int iteracion = Integer.valueOf(request.getParameter("iteracion2"));
        String tipoDato = request.getParameter("campos2");
        String delimitador = request.getParameter("delimit");
        String nameArchivo = request.getParameter("nameCVS");

        System.out.println(delimitador);
        System.out.println(nameArchivo);

        String atributos[] = new String[iteracion];

        for (int i = 0; i < iteracion; i++) {
            atributos[i] = request.getParameter("txt" + (i + 1));
        }

        String rutaArchivo = "C:\\" + nameArchivo + ".xls";//xls
        /*Se crea el objeto de tipo File con la ruta del archivo*/
        File archivoXLS = new File(rutaArchivo);
        /*Si el archivo existe se elimina*/
        if (archivoXLS.exists())
            archivoXLS.delete();
        /*Se crea el archivo*/
        archivoXLS.createNewFile();

        /*Se crea el libro de excel usando el objeto de tipo Workbook*/
        Workbook libro = new HSSFWorkbook();
        /*Se inicializa el flujo de datos con el archivo xls*/
        FileOutputStream archivo = new FileOutputStream(archivoXLS);

        /*Utilizamos la clase Sheet para crear una nueva hoja de trabajo dentro del libro que creamos anteriormente*/
        Sheet hoja = libro.createSheet("Datos");

        /*Hacemos un ciclo para inicializar los valores de 10 filas de celdas*/
        Row fila = hoja.createRow(0);
        Cell celda;
        Random rand = new Random();
        for (int f = 0; f < iteracion; f++) {
            celda = fila.createCell(f);
            celda.setCellValue(atributos[f]);
        }

        for (int j = iteracion; j < (10 + iteracion); j++) {
            celda = fila.createCell(j);

            for (int i = 0; i < tipoDato.length(); i++) {
                char c = tipoDato.charAt(i);
                if (c != ',') {

                    switch (c) {

                    case '1':
                        celda.setCellValue(BD1[rand.nextInt(399)]);
                        break;
                    case '2':
                        celda.setCellValue(BD2[rand.nextInt(399)]);
                        break;
                    case '3':
                        celda.setCellValue(BD3[rand.nextInt(399)]);
                        break;
                    case '4':
                        celda.setCellValue(BD4[rand.nextInt(399)]);
                        break;
                    case '5':
                        celda.setCellValue(String.valueOf(rand.nextInt(9999)));
                        break;
                    case '6':
                        celda.setCellValue(String.valueOf(rand.nextInt(999999999)));
                        break;
                    case '7':
                        celda.setCellValue(BD1[rand.nextInt(399)] + "@" + BD5[rand.nextInt(399)]);
                        break;
                    }
                    celda.setCellValue(String.valueOf(delimitador));
                }

            }

        }

        libro.write(archivo);
        archivo.close();
        Desktop.getDesktop().open(archivoXLS);
    }
}

From source file:Core.Core.java

public void printRes(double[] rapport, int[] errorForCouple, double[] dataQuality, int[] real, int noEnc) {
    StringTokenizer st = new StringTokenizer(Extractor.dpsFileLocation);
    st.nextToken("-");
    st.nextToken("-");
    String name = st.nextToken("_");
    //int numOfPage = 4;

    try {//from  ww w  .  j a  v  a 2  s. c  o  m

        String filename = "/home/gabriele/Documenti/risultati prophetSpy/result " + name + ".xlsx";
        FileInputStream fileInput = null;
        Sheet sheet;
        Workbook workbook = null;
        try {
            fileInput = new FileInputStream(filename);
            workbook = create(fileInput);
            sheet = workbook.getSheetAt(0);

            System.out.println("found xlsx file");
        } catch (FileNotFoundException fileNotFoundException) {
            workbook = new XSSFWorkbook();
            sheet = workbook.createSheet("foglio 1");

            System.out.println("no file found");
        }

        Row rowhead = sheet.createRow(0);
        rowhead.createCell(0).setCellValue("rapport");
        rowhead.createCell(1).setCellValue("errorForCouple");
        rowhead.createCell(2).setCellValue("dataQuality");
        rowhead.createCell(3).setCellValue("real");
        rowhead.createCell(7).setCellValue("est = 0");
        rowhead.createCell(8).setCellValue("Total Couple");

        int numRow = 1;
        for (int j = 0; j < rapport.length; j++) {
            if (rapport[j] != -1) {
                Row row = sheet.createRow(numRow);
                row.createCell(0).setCellValue(rapport[j]);
                row.createCell(1).setCellValue(errorForCouple[j]);
                row.createCell(2).setCellValue(dataQuality[j]);
                row.createCell(3).setCellValue(real[j]);
                numRow++;
            }
        }

        sheet.getRow(1).createCell(7).setCellValue(noEnc);
        sheet.getRow(1).createCell(8).setCellValue(rapport.length);

        FileOutputStream fileOut = new FileOutputStream(filename);
        workbook.write(fileOut);
        fileOut.close();
        System.out.println("Your excel file has been generated!");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:CPUGalenia.FrmExportarConsultas.java

private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
    // TODO add your handling code here:
    int numeroFila = 5;
    Date fechaInicial = null;//ww w .  j  a v  a  2 s  .c o  m
    Date fechaFinal = null;

    try {
        fechaInicial = formatoFecha.parse(txtFechaInicial.getText());
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Ingresa un fecha inicial correcta.", "CPUGalenia", 0);
        return;
    }

    try {
        fechaFinal = formatoFecha.parse(txtFechaFinal.getText());
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Ingresa un fecha final correcta.", "CPUGalenia", 0);
        return;
    }

    List<Consulta> listaConsultas = ConsultaBLO.obtenerTodosPorFecha(fechaInicial, fechaFinal);

    String rutaArchivo = System.getProperty("user.home") + "/CPUGalenia-Consultas.xls";
    File archivoXLS = new File(rutaArchivo);
    if (archivoXLS.exists())
        archivoXLS.delete();
    try {
        archivoXLS.createNewFile();
    } catch (IOException ex) {
        Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }

    Workbook libro = new HSSFWorkbook();
    FileOutputStream archivo = null;
    try {
        archivo = new FileOutputStream(archivoXLS);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }

    Sheet hoja = libro.createSheet("Consultas");

    //TITULO
    Row titulo = hoja.createRow(0);
    Cell ctitulo = titulo.createCell(0);
    ctitulo.setCellValue("REPORTE DE CONSULTAS");

    //FECHA
    Row fecha1 = hoja.createRow(2);
    Cell cFecha1 = fecha1.createCell(0);
    cFecha1.setCellValue("Fecha inicial:");

    Cell cFecha11 = fecha1.createCell(1);
    cFecha11.setCellValue(formatoFecha.format(fechaInicial));

    Row fecha2 = hoja.createRow(3);
    Cell cFecha2 = fecha2.createCell(0);
    cFecha2.setCellValue("Fecha final:");

    Cell cFecha22 = fecha2.createCell(1);
    cFecha22.setCellValue(formatoFecha.format(fechaFinal));

    // TITULOS
    Row encabezado = hoja.createRow(5);

    Cell tId = encabezado.createCell(0);
    tId.setCellValue("Id Consulta");

    Cell tFecha = encabezado.createCell(1);
    tFecha.setCellValue("Fecha");

    Cell tApellidoPaterno = encabezado.createCell(2);
    tApellidoPaterno.setCellValue("Apellido paterno");

    Cell tApellidoMaterno = encabezado.createCell(3);
    tApellidoMaterno.setCellValue("Apellido materno");

    Cell tNombres = encabezado.createCell(4);
    tNombres.setCellValue("Nombres");

    Cell tFechaNacimiento = encabezado.createCell(5);
    tFechaNacimiento.setCellValue("Fecha de nacimiento");

    Cell tSexo = encabezado.createCell(6);
    tSexo.setCellValue("Sexo");

    Cell tDiagnostico = encabezado.createCell(7);
    tDiagnostico.setCellValue("Diagnostico");

    for (Consulta consulta : listaConsultas) {
        numeroFila++;
        Row fila = hoja.createRow(numeroFila);

        Cell cId = fila.createCell(0);
        cId.setCellValue(consulta.getId());

        Cell cFecha = fila.createCell(1);
        cFecha.setCellValue(formatoFecha.format(consulta.getFecha()));

        Cell cApellidoPaterno = fila.createCell(2);
        cApellidoPaterno.setCellValue(consulta.getPaciente().getApellidoPaterno());

        Cell cApellidoMaterno = fila.createCell(3);
        cApellidoMaterno.setCellValue(consulta.getPaciente().getApellidoMaterno());

        Cell cNombres = fila.createCell(4);
        cNombres.setCellValue(consulta.getPaciente().getNombres());

        Cell cFechaNacimiento = fila.createCell(5);
        cFechaNacimiento.setCellValue(formatoFecha.format(consulta.getPaciente().getFechaNacimiento()));

        Cell cSexo = fila.createCell(6);
        cSexo.setCellValue(consulta.getPaciente().getSexo().toString());

        Cell cDiagnostico = fila.createCell(7);
        cDiagnostico.setCellValue(consulta.getDiagnostico().getDescripcion());
    }

    try {
        libro.write(archivo);
    } catch (IOException ex) {
        Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        archivo.close();
    } catch (IOException ex) {
        Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        /*Y abrimos el archivo con la clase Desktop*/
        Desktop.getDesktop().open(archivoXLS);
    } catch (IOException ex) {
        Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Creator.MainFrame.java

private void _MenuItem_PrintVarNamesXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__MenuItem_PrintVarNamesXActionPerformed

    _FileChooser.setDialogTitle("Save IO Imports As Excel File");
    _FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    _FileChooser.setFileFilter(new FileNameExtensionFilter("Excel workbook (.xlsx)", new String[] { "xlsx" }));
    _FileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
    _FileChooser.setApproveButtonText("Save Excel file");
    _FileChooser.setApproveButtonToolTipText("Save");

    int returnVal = _FileChooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        File file = _FileChooser.getSelectedFile();
        //System.out.println("File: " + file.getAbsolutePath());
        String filePath = file.getAbsolutePath();
        if (!filePath.endsWith(".xlsx")) {
            filePath += ".xlsx";
        }//from www .ja  v  a 2  s. c o m

        try {
            Workbook wb = new XSSFWorkbook();
            FileOutputStream fileOut = new FileOutputStream(filePath);

            List<String[]> list = store.formatStrings();
            int rowNum = 0;
            Sheet sheet = wb.createSheet("Var Names");

            for (String[] r : list) {
                // Create a row and put some cells in it. Rows are 0 based.
                Row row = sheet.createRow(rowNum);
                // Create a cell and put a value in it.
                for (int i = 0; i < r.length; i++) {
                    Cell cell = row.createCell(i);

                    // If the string is a number, write it as a number
                    if (r[i].equals("")) {
                        // Empty field, do nothing

                    } else if (isStringNumeric(r[i])) {
                        cell.setCellValue(Double.parseDouble(r[i].replace("\"", "")));
                    } else {
                        cell.setCellValue(r[i]);
                    }

                }

                rowNum++;

            }

            wb.write(fileOut);
            fileOut.close();
        } catch (Exception e) {
            controlPanel.writeToLog("Error with creating excel file " + e.getMessage());
        }

    } else {
        System.out.println("File access cancelled by user.");
    }
}

From source file:Creator.MainFrame.java

private void _MenuItem_SaveAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__MenuItem_SaveAllActionPerformed

    _FileChooser.setDialogTitle("Save everything into a folder");
    _FileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    _FileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
    _FileChooser.setApproveButtonText("Save Here");
    _FileChooser.setApproveButtonToolTipText("Save");

    int returnVal = _FileChooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        String filePathORIGINAL = _FileChooser.getSelectedFile().toString();
        String fn = filePathORIGINAL + "\\" + this.store.getStoreName() + ".xml";

        // What to do with the file, e.g. display it in a TextArea
        if (xmlParser != null) {
            if (xmlParser.writeOut(this.store, fn)) {
                controlPanel.writeToLog("Store " + this.store.getStoreName() + " saved");
            } else {
                controlPanel.writeToLog("Store " + this.store.getStoreName() + " had a problem saving");
            }//  w  ww  . j  av  a  2  s  . co  m
        } else {
            System.out.println("Problem with the XMLParser");
        }

        // -------------------- Save all displays --------------------------
        String filePath = filePathORIGINAL + "\\Displays\\";

        if (!new File(filePath).mkdir()) {
            filePath = filePath.replace("Displays\\", "");
        }
        //System.out.println("FP: " + filePath);
        String[] fileNames = controlPanel.getFileNames(filePath, displayFrame.bg.getSize());
        int numDisplays = displayFrame.getTabCount();
        BufferedImage bi;

        int numRacks = store.cs.getNumRacks();
        for (int i = 0; i < numDisplays; i++) {
            //System.out.println(i + ": " + fileNames[i]);
            try {
                if (i == 0) {
                    bi = ScreenImage.createImage(displayFrame.bg);
                } else if (i > 0 && i <= numRacks) {
                    bi = ScreenImage.createImage(displayFrame.rackTabs.get(i - 1));
                    /*} else if (i > numRacks && i <= (numRacks * 2)) {
                        bi = ScreenImage.createImage(displayFrame.loadTabs.get(i - (numRacks + 1)));
                    */} else if (i == (numDisplays - 3)) {
                    bi = ScreenImage.createImage(displayFrame.bgf);
                } else if (i == (numDisplays - 2)) {
                    bi = ScreenImage.createImage(displayFrame.bge);
                } else if (i == (numDisplays - 1)) {
                    bi = ScreenImage.createImage(displayFrame.bgg);
                } else {
                    System.out.println("Screen Print else on i = " + i);
                    bi = ScreenImage.createImage(displayFrame.bg);
                }

                ScreenImage.writeImage(bi, fileNames[i]);
                //ScreenImage.createImage();

            } catch (IOException e) {
                controlPanel.writeToLog("Error writing image file" + e.getMessage());
            }
        }

        // -------------------------- Save XLSX --------------------
        File file = new File(filePathORIGINAL + "\\" + this.store.getStoreName() + "-IOVariables.xlsx");
        //System.out.println("File: " + file.getAbsolutePath());
        String excelPath = file.getAbsolutePath();

        try {
            Workbook wb = new XSSFWorkbook();
            FileOutputStream fileOut = new FileOutputStream(excelPath);

            List<String[]> list = store.formatStrings();
            int rowNum = 0;
            Sheet sheet = wb.createSheet("Var Names");

            for (String[] r : list) {
                // Create a row and put some cells in it. Rows are 0 based.
                Row row = sheet.createRow(rowNum);
                // Create a cell and put a value in it.
                for (int i = 0; i < r.length; i++) {
                    Cell cell = row.createCell(i);

                    // If the string is a number, write it as a number
                    if (r[i].equals("")) {
                        // Empty field, do nothing

                    } else if (isStringNumeric(r[i])) {
                        cell.setCellValue(Double.parseDouble(r[i].replace("\"", "")));
                    } else {
                        cell.setCellValue(r[i]);
                    }

                }

                rowNum++;

            }

            wb.write(fileOut);
            fileOut.close();
        } catch (NumberFormatException | IOException e) {
            controlPanel.writeToLog("Error with creating excel file " + e.getMessage());
        }

    } else {
        System.out.println("File access cancelled by user.");
    }
}

From source file:Creator.MainFrame.java

public void returnIoItems(List<String[]> list) {

    ioFrame.dispose();/*www .  j a  v  a2s  .c  om*/

    _FileChooser.setDialogTitle("Save Specific IO Imports As Excel File");
    _FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    _FileChooser.setFileFilter(new FileNameExtensionFilter("Excel workbook (.xlsx)", new String[] { "xlsx" }));
    _FileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
    _FileChooser.setApproveButtonText("Save Excel file");
    _FileChooser.setApproveButtonToolTipText("Save");

    int returnVal = _FileChooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        File file = _FileChooser.getSelectedFile();
        //System.out.println("File: " + file.getAbsolutePath());
        String filePath = file.getAbsolutePath();
        if (!filePath.endsWith(".xlsx")) {
            filePath += ".xlsx";
        }

        try {
            Workbook wb = new XSSFWorkbook();
            FileOutputStream fileOut = new FileOutputStream(filePath);

            int rowNum = 0;
            Sheet sheet = wb.createSheet("Var Names");

            for (String[] r : list) {
                // Create a row and put some cells in it. Rows are 0 based.
                Row row = sheet.createRow(rowNum);
                // Create a cell and put a value in it.
                for (int i = 0; i < r.length; i++) {
                    Cell cell = row.createCell(i);

                    // If the string is a number, write it as a number
                    if (r[i].equals("")) {
                        // Empty field, do nothing

                    } else if (isStringNumeric(r[i])) {
                        cell.setCellValue(Double.parseDouble(r[i].replace("\"", "")));
                    } else {
                        cell.setCellValue(r[i]);
                    }

                }

                rowNum++;

            }

            wb.write(fileOut);
            fileOut.close();
        } catch (Exception e) {
            controlPanel.writeToLog("Error with creating excel file " + e.getMessage());
        }

    } else {
        System.out.println("File access cancelled by user.");
    }
}

From source file:csns.web.controller.SectionRosterController.java

License:Open Source License

@RequestMapping("/section/roster/export")
public String export(@RequestParam Long id, HttpServletResponse response) throws IOException {
    Section section = sectionDao.getSection(id);
    GradeSheet gradeSheet = new GradeSheet(section);

    response.setContentType(contentTypes.getProperty("xlsx"));
    response.setHeader("Content-Disposition", "attachment; filename=" + section.getCourse().getCode() + "-"
            + section.getQuarter().getShortString() + ".xlsx");

    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Grades");

    int n = section.getAssignments().size();
    Row row = sheet.createRow(0);/*www.j  a v a 2 s .co m*/
    row.createCell(0).setCellValue("Name");
    for (int i = 0; i < n; ++i)
        row.createCell(i + 1).setCellValue(section.getAssignments().get(i).getAlias());
    row.createCell(n + 1).setCellValue("Grade");

    int rowIndex = 1;
    Map<Enrollment, String[]> studentGrades = gradeSheet.getStudentGrades();
    for (Enrollment enrollment : studentGrades.keySet()) {
        row = sheet.createRow(rowIndex++);
        row.createCell(0).setCellValue(
                enrollment.getStudent().getLastName() + ", " + enrollment.getStudent().getFirstName());
        for (int i = 0; i < n; ++i) {
            Cell cell = row.createCell(i + 1);
            String grade = studentGrades.get(enrollment)[i];
            if (StringUtils.hasText(grade) && grade.matches("-?\\d+(\\.\\d+)?"))
                cell.setCellValue(Double.parseDouble(grade));
            else
                cell.setCellValue(grade);
        }
        if (enrollment.getGrade() != null)
            row.createCell(n + 1).setCellValue(enrollment.getGrade().getSymbol());
    }

    wb.write(response.getOutputStream());

    logger.info(SecurityUtils.getUser().getUsername() + " exported the roster of section " + id);

    return null;
}

From source file:csns.web.controller.SurveyController.java

License:Open Source License

private void exportExcel(Survey survey, int sectionIndex, Workbook wb) {
    Sheet sheet = wb.createSheet("Section " + (sectionIndex + 1));
    int numOfResponses = survey.getNumOfResponses();

    // The first column is the timestamp of the response.
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Row row = sheet.createRow(0);/*from w  w w. j  a v  a 2  s . co m*/
    row.createCell(0).setCellValue("Date");
    for (int i = 0; i < numOfResponses; ++i)
        sheet.createRow(1 + i).createCell(0)
                .setCellValue(dateFormat.format(survey.getResponses().get(i).getAnswerSheet().getDate()));

    // If the survey is NAMED, the next two columns are the CIN and name
    // of the respondent.
    int startColumnIndex = 1;
    if (survey.getType() == SurveyType.NAMED) {
        row = sheet.getRow(0);
        row.createCell(1).setCellValue("CIN");
        row.createCell(2).setCellValue("Name");
        for (int i = 0; i < numOfResponses; ++i) {
            User respondent = survey.getResponses().get(i).getAnswerSheet().getAuthor();
            row = sheet.getRow(1 + i);
            row.createCell(1).setCellValue(respondent.getCin());
            row.createCell(2).setCellValue(respondent.getLastName() + ", " + respondent.getFirstName());
        }
        startColumnIndex = 3;
    }

    int numOfQuestions = survey.getQuestionSheet().getSections().get(sectionIndex).getQuestions().size();
    for (int i = 0; i < numOfQuestions; ++i) {
        sheet.getRow(0).createCell(startColumnIndex + i).setCellValue("Q" + (i + 1));
        for (int j = 0; j < numOfResponses; ++j)
            sheet.getRow(1 + j).createCell(startColumnIndex + i).setCellValue(survey.getResponses().get(j)
                    .getAnswerSheet().getSections().get(sectionIndex).getAnswers().get(i).toString());
    }
}

From source file:csvsimulator.model.ModelSuonata.java

public void saveOnExcel(int numero_colonne, final Window w) {
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Excel (*.xlsx)", "*.xlsx");
    fileChooser.getExtensionFilters().add(extFilter);

    File file = fileChooser.showSaveDialog(w);

    if (file != null) {

        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Spartito_Suonata");
        int rowIndex = 0;
        int columnIndex = 0;
        Cell cell;//from  w w w  .j  a  va2s.  c  om
        Row row = sheet.createRow(rowIndex);
        for (ModelBattuta modelBattuta : this.getListaBattute()) {
            cell = row.createCell(columnIndex);
            cell.setCellValue(modelBattuta.getNomeBattuta(this.concerto));

            columnIndex++;
            if (columnIndex >= numero_colonne) {
                rowIndex++;
                columnIndex = 0;
                row = sheet.createRow(rowIndex);
            }
        }

        // Write the output to a file
        try {
            FileOutputStream out = new FileOutputStream(file);
            wb.write(out);
            out.close();
        } catch (Exception e) {
        }

    }
}