Example usage for org.apache.poi.ss.usermodel Sheet createRow

List of usage examples for org.apache.poi.ss.usermodel Sheet createRow

Introduction

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

Prototype

Row createRow(int rownum);

Source Link

Document

Create a new row within the sheet and return the high level representation

Usage

From source file:controladores.ExportExcel.java

public String ConsultaExportarExcel(ResultSet rs, String nombreArchivo) {

    String respuesta = "No se realizo con exito la exportacin.";
    ResultSetMetaData rsMd;//from   w  ww.j  a v a  2s. c  o m
    try {
        //crea el jtable
        rsMd = rs.getMetaData();
        int numeroColumnas = rsMd.getColumnCount();
        DefaultTableModel modelo = new DefaultTableModel();
        JTable tablaD = new JTable();
        tablaD.setModel(modelo);
        for (int i = 1; i <= numeroColumnas; i++) {
            modelo.addColumn(rsMd.getColumnLabel(i));
        }
        while (rs.next()) {
            Object[] fila = new Object[numeroColumnas];
            for (int i = 0; i < numeroColumnas; i++) {
                fila[i] = rs.getObject(i + 1);
            }
            modelo.addRow(fila);
        }
        //crea el archivo excel
        File archivo = new File(RUTA_REPORTE + "Reporte " + nombreArchivo + ".xls");
        archivo.createNewFile();

        //aade datos al doc de excel 
        int numFila = tablaD.getRowCount(), numColumna = tablaD.getColumnCount();
        if (archivo.getName().endsWith("xls")) {
            wb = new HSSFWorkbook();
        } else {
            wb = new XSSFWorkbook();
        }
        Sheet hoja = wb.createSheet("Reporte " + nombreArchivo);
        for (int i = -1; i < numFila; i++) {
            Row fila = hoja.createRow(i + 1);
            for (int j = 0; j < numColumna; j++) {
                Cell celda = fila.createCell(j);
                if (i == -1) {
                    celda.setCellValue(String.valueOf(tablaD.getColumnName(j)));
                } else {
                    celda.setCellValue(String.valueOf(tablaD.getValueAt(i, j)));

                }
                wb.write(new FileOutputStream(archivo));
            }
        }
        respuesta = "Exportacin exitosa.";
    } catch (SQLException ex) {
        Logger.getLogger(ExportExcel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ExportExcel.class.getName()).log(Level.SEVERE, null, ex);
    }
    return respuesta;

}

From source file:Controladores.HacerReporte.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from www .j av  a2s. c  o  m*/
 *
 * @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("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=Reporte.xlsx");

    // Se crea el libro
    Workbook libro = new XSSFWorkbook();
    //
    //        Manager_BD bd= new  Manager_BD();
    //        bd.iniciarConexion();
    //        
    //        libro=bd.tareasParaReporte(request.getParameter("fechaI"), request.getParameter("fechaF"), request.getParameter("cliente"), request.getParameter("proyecto"));
    //        
    //        bd.cerrarConexion();

    // Se crea una hoja dentro del libro
    Sheet hoja = libro.createSheet();

    // Se crea una fila dentro de la hoja
    Row fila = hoja.createRow(1);

    Cell celda = fila.createCell(1);
    celda.setCellValue("Hola");

    libro.write(response.getOutputStream());

}

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  w  ww.  ja  v a 2  s .co 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;//from ww w. j av  a2 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   w  w w. ja va2  s.  co 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");
            }//  ww  w  . j  av a 2s.  c  o  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();/*from  w ww.  j a v  a2 s  .  c  o  m*/

    _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:cs.handmail.processtable.ExportExcel.java

public void export() {
    try {//from   ww  w  .  j  av  a2  s. c o m
        new WorkbookFactory();
        Workbook wb = new XSSFWorkbook(); //Excell workbook
        Sheet sheet = wb.createSheet(); //WorkSheet
        Row row = sheet.createRow(2); //Row created at line 3
        TableModel model = _tableExport.getModel();
        String temp;

        Row headerRow = sheet.createRow(0); //Create row at line 0
        for (int headings = 0; headings < model.getColumnCount(); headings++) {
            headerRow.createCell(headings).setCellValue(model.getColumnName(headings));//Write column name
        }

        for (int rows = 0; rows < model.getRowCount(); rows++) { //For each table row
            for (int cols = 0; cols < _tableExport.getColumnCount(); cols++) { //For each table column
                if (model.getValueAt(rows, cols) != null)
                    temp = model.getValueAt(rows, cols).toString();
                else
                    temp = "";
                row.createCell(cols).setCellValue(temp);
            }

            //Set the row to the next one in the sequence
            row = sheet.createRow((rows + 3));
        }
        wb.write(new FileOutputStream(_pathFolder + "/" + _nameFile));//Save the file    
        JOptionPane.showMessageDialog(null, "Save file Success");
    } catch (IOException ex) {
        Logger.getLogger(ExportExcel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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);
    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(/*  w  w w. j  a va 2  s.  com*/
                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;
}