Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook createSheet

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook createSheet

Introduction

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

Prototype

@Override
public XSSFSheet createSheet() 

Source Link

Document

Create an XSSFSheet for this workbook, adds it to the sheets and returns the high level representation.

Usage

From source file:si_piket_smkn3.frm_tampil_piket.java

private void exportexcel(String alamat) {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();

    //load data dari tabel ke treemap
    TreeMap<Integer, Object[]> data = new TreeMap<>();
    data.put(0,/*  ww w  . jav  a  2  s. c  o m*/
            new Object[] { tableModel.getColumnName(0), tableModel.getColumnName(1),
                    tableModel.getColumnName(2), tableModel.getColumnName(3), tableModel.getColumnName(4),
                    tableModel.getColumnName(5), tableModel.getColumnName(6), tableModel.getColumnName(7),
                    tableModel.getColumnName(8) });
    for (int i = 1; i < tableModel.getRowCount() + 1; i++) {

        data.put(i,
                new Object[] { getCellValue(i - 1, 0), getCellValue(i - 1, 1), getCellValue(i - 1, 2),
                        getCellValue(i - 1, 3), getCellValue(i - 1, 4), getCellValue(i - 1, 5),
                        getCellValue(i - 1, 6), getCellValue(i - 1, 7), getCellValue(i - 1, 8), });
    }

    //menulis ke kertas
    Set<Integer> ids = data.keySet();
    XSSFRow row;
    int rowID = 0;

    for (Integer key : ids) {
        row = ws.createRow(rowID++);

        //get data as per key
        Object[] values = data.get(key);

        int cellID = 0;
        for (Object o : values) {
            XSSFCell cell = row.createCell(cellID++);
            cell.setCellValue(o.toString());
        }
    }

    //write excel to file system
    try {
        FileOutputStream fos = new FileOutputStream(new File(alamat));
        wb.write(fos);
        fos.close();
    } catch (Exception ex) {
        System.err.println(ex.getMessage());
        JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
    }
}

From source file:standarapp.algorithm.Lecture.java

public static XSSFSheet lectureXLSX(String nameFile, int page) {
    FileInputStream file;/*from ww w. j av  a 2 s  . c  om*/
    XSSFWorkbook excelFile = new XSSFWorkbook();
    XSSFSheet xsheet = excelFile.createSheet();
    //Reading the file which contains registries
    //Lectura del archivo xls de registros
    try {
        file = new FileInputStream(new File(nameFile));
        excelFile = new XSSFWorkbook(file);
        xsheet = excelFile.getSheetAt(page);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReadRegistry.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReadRegistry.class.getName()).log(Level.SEVERE, null, ex);
    }

    return xsheet;
}

From source file:sv.com.mined.sieni.controller.GestionNotasController.java

public StreamedContent getFilePlantilla() {
    filePlantilla = null;//from  www  .  java2s.co  m
    String ruthPath = null;
    try {
        if (this.getEvaluacionSubir() != null && this.getEvaluacionSubir().getIdEvaluacion() != null) {
            // Se crea el libro
            XSSFWorkbook libro = new XSSFWorkbook();
            // Se crea una hoja dentro del libro
            XSSFSheet sheetD = libro.createSheet();
            //Obtener lista de alumnos del curso
            List<SieniAlumno> alumnosEval = sieniAlumnoFacadeRemote
                    .findAlumnosInscritos(this.getEvaluacionSubir().getIdCurso().getIdCurso());
            //Leer datos y colocarlos en la hoja
            int f = 0;
            //Guardar datos en celda
            for (SieniAlumno alumno : alumnosEval) {
                // Se crea una fila dentro de la hoja
                XSSFRow fila = sheetD.createRow(f);
                f++;
                // Se crea las celdas dentro de la fila
                XSSFCell celdaCarnet = fila.createCell((short) 0);
                XSSFCell celdaAlumno = fila.createCell((short) 1);
                XSSFCell celdaNota = fila.createCell((short) 2);
                //Colocar valor en celda
                celdaCarnet.setCellValue(alumno.getAlCarnet());
                celdaAlumno.setCellValue(alumno.getNombreCompleto());
                celdaNota.setCellValue((double) 0.00);
            }
            //Encabezados desde plantilla
            InputStream stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                    .getContext()).getResourceAsStream("/resources/templates/PlantillaAlumnosEval.xlsx");
            StreamedContent plantillaXLS = new DefaultStreamedContent(stream,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Plantilla.xlsx");
            XSSFWorkbook plantilla = new XSSFWorkbook(plantillaXLS.getStream());
            XSSFSheet sheetP = plantilla.getSheetAt(0);

            //Filas que ocupa el encabezado de plantilla
            int encabezado = 3;
            //Quitar encabezado y desplazar Datos
            sheetD.shiftRows(0, sheetD.getLastRowNum(), encabezado);
            //Copiar contenido de plantilla a la hoja del reporte
            int inicio = 0;
            for (int row = 0; row < encabezado; row++) {
                copyRow(sheetP, sheetD, row, inicio);
                inicio++;
            }
            //Combinar las columnas al igual que la plantilla
            for (int m = 0; m < sheetP.getNumMergedRegions(); m++) {
                CellRangeAddress cellRangeAddress = sheetP.getMergedRegion(m).copy();
                sheetD.addMergedRegion(cellRangeAddress);
            }
            //Evaluacion
            XSSFCell celdaEval = sheetD.getRow(0).getCell(1);
            celdaEval.setCellValue(this.getEvaluacionSubir().getEvNombre());
            // Se salva el libro.
            FileOutputStream elFichero = new FileOutputStream("ListaAlumnos.xlsx");
            libro.write(elFichero);
            elFichero.close();
            //Leer libro para descarga
            FileInputStream file = new FileInputStream(new File("ListaAlumnos.xlsx"));
            filePlantilla = new DefaultStreamedContent(file,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "AlumnosEval.xlsx");

        } else {
            new ValidationPojo().printMsj("Seleccione una evaluacion", FacesMessage.SEVERITY_ERROR);
        }
    } catch (Exception exc) {
        new ValidationPojo().printMsj(
                "Ocurrio un error al descargar plantilla ... consulte con el administrador" + ruthPath,
                FacesMessage.SEVERITY_ERROR);
    }
    return filePlantilla;
}

From source file:uk.gov.ofwat.RefTest.java

License:Open Source License

public void writeXLS() throws IOException {
    XSSFWorkbook wb = new XSSFWorkbook();
    CreationHelper creationHelper = wb.getCreationHelper();
    // create a new sheet
    Sheet s = wb.createSheet();
    // declare a row object reference
    Row r = null;/* w ww  .  j a  v a2  s .  c o m*/
    // declare a cell object reference
    Cell c = null;
    // create 2 cell styles
    XSSFCellStyle cs = wb.createCellStyle();

    XSSFCellStyle cs2 = wb.createCellStyle();
    DataFormat df = wb.createDataFormat();

    // create 2 fonts objects
    Font f = wb.createFont();
    Font f2 = wb.createFont();

    // Set font 1 to 12 point type, blue and bold
    f.setFontHeightInPoints((short) 12);
    f.setColor(IndexedColors.RED.getIndex());
    f.setBoldweight(Font.BOLDWEIGHT_BOLD);

    // Set font 2 to 10 point type, red and bold
    f2.setFontHeightInPoints((short) 10);
    f2.setColor(IndexedColors.RED.getIndex());
    f2.setBoldweight(Font.BOLDWEIGHT_BOLD);

    // Set cell style and formatting
    cs.setFont(f);
    cs.setDataFormat(df.getFormat("#,##0.0"));

    // Set the other cell style and formatting
    cs2.setBorderBottom(cs2.BORDER_THIN);
    cs2.setDataFormat((short) BuiltinFormats.getBuiltinFormat("text"));
    cs2.setFont(f2);

    // Define a few rows
    for (int rownum = 0; rownum < 30; rownum++) {
        r = s.createRow(rownum);
        for (int cellnum = 0; cellnum < 10; cellnum += 2) {
            c = r.createCell(cellnum);
            Cell c2 = r.createCell(cellnum + 1);

            c.setCellValue((double) rownum + (cellnum / 10));
            c2.setCellValue(creationHelper.createRichTextString("Hello! " + cellnum));
        }
    }

    File file = new File("d:\\out.xls");
    FileOutputStream fos = new FileOutputStream(file);
    wb.write(fos);
    //      fos.write(wb.getBytes());
    //      fos.flush();
    //      fos.close();

}

From source file:util.ExcelConverter.java

public static File createXlsx(String[] header, String[][] data, String path) {

    try {//from   w  w w . j av  a 2 s . c om
        XSSFWorkbook xwb = new XSSFWorkbook();
        XSSFSheet sheet = xwb.createSheet();

        CellStyle cellStyle = xwb.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
        cellStyle.setAlignment(CellStyle.VERTICAL_TOP);
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setWrapText(false);

        Font bold = xwb.createFont();
        bold.setBoldweight(Font.BOLDWEIGHT_BOLD);
        bold.setFontHeightInPoints((short) 10);

        CellStyle cellStyleHeader = xwb.createCellStyle();
        cellStyleHeader.setAlignment(CellStyle.ALIGN_LEFT);
        cellStyleHeader.setAlignment(CellStyle.VERTICAL_TOP);
        cellStyleHeader.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyleHeader.setFont(bold);
        cellStyleHeader.setWrapText(false);

        XSSFRow row;
        Cell cell;

        //header
        row = sheet.createRow(0);
        for (int i = 0; i < header.length; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(cellStyleHeader);
            cell.setCellValue(header[i]);
        }

        int colCount = header.length;
        int no = 1;

        for (String[] obj : data) {
            row = sheet.createRow(no);
            for (int i = 0; i < colCount; i++) {
                cell = row.createCell(i);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(obj[i]);
            }
            no++;
        }

        for (int i = 0; i < header.length; i++) {
            sheet.autoSizeColumn(i);
        }

        File newFile = new File(path);
        try (FileOutputStream fileOut = new FileOutputStream(path)) {
            xwb.write(fileOut);
        }

        return newFile;
    } catch (IOException e) {
        return null;
    }
}

From source file:VentanaJava.ConsultarCosechaCortoExportar.java

private void ExportarPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExportarPlanActionPerformed
    DefaultTableModel model = (DefaultTableModel) TablaPlanesCosechaCorto.getModel();
    int filas = TablaPlanesCosechaCorto.getRowCount();
    JFileChooser GuardarArchivo = new JFileChooser();
    int opcion = GuardarArchivo.showSaveDialog(this);
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String direccion = GuardarArchivo.getSelectedFile().toString();
        XSSFWorkbook libro = new XSSFWorkbook();
        XSSFSheet hoja = libro.createSheet();
        XSSFRow fila = hoja.createRow(0);
        fila.createCell(0).setCellValue("Secuencia");
        fila.createCell(1).setCellValue("Fecha de Cosecha");
        fila.createCell(2).setCellValue("Granja");
        fila.createCell(3).setCellValue("Galera");
        fila.createCell(4).setCellValue("Cantidad a Cosechar");
        fila.createCell(5).setCellValue("Peso Promedio");

        XSSFRow hileras;//  w  w  w  .  j a v a 2s  .  c om
        for (int i = 0; i < filas; i++) {
            hileras = hoja.createRow((i + 1));
            for (int e = 0; e < 6; e++) {
                hileras.createCell(e).setCellValue(model.getValueAt(i, e).toString());
            }
        }
        try {
            libro.write(new FileOutputStream(new File(direccion + ".xlsx")));
            Desktop.getDesktop().open(new File(direccion + ".xlsx"));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    this.dispose();
}

From source file:VentanaJava.ConsultarCosechaMedianoExportar.java

private void ExportarPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExportarPlanActionPerformed
    DefaultTableModel model = (DefaultTableModel) TablaCosechaMedianoConsulta.getModel();
    int filas = TablaCosechaMedianoConsulta.getRowCount();
    JFileChooser GuardarArchivo = new JFileChooser();
    int opcion = GuardarArchivo.showSaveDialog(this);
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String direccion = GuardarArchivo.getSelectedFile().toString();
        XSSFWorkbook libro = new XSSFWorkbook();
        XSSFSheet hoja = libro.createSheet();
        XSSFRow fila = hoja.createRow(0);
        fila.createCell(0).setCellValue("Secuencia");
        fila.createCell(1).setCellValue("Fecha de Cosecha");
        fila.createCell(2).setCellValue("Granja");
        fila.createCell(3).setCellValue("Galera");
        fila.createCell(4).setCellValue("Cantidad a Cosechar");
        fila.createCell(5).setCellValue("Peso Promedio");

        XSSFRow hileras;/* w w  w  . ja va  2  s  .  c o  m*/
        for (int i = 0; i < filas; i++) {
            hileras = hoja.createRow((i + 1));
            for (int e = 0; e < 6; e++) {
                hileras.createCell(e).setCellValue(model.getValueAt(i, e).toString());
            }
        }
        try {
            libro.write(new FileOutputStream(new File(direccion + ".xlsx")));
            Desktop.getDesktop().open(new File(direccion + ".xlsx"));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        this.dispose();
    }
}

From source file:VentanaJava.ConsultarIngresoCortoExportar.java

private void ExportarPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExportarPlanActionPerformed
    DefaultTableModel model = (DefaultTableModel) TablaPlanesIngresoCortoPlazo.getModel();
    int filas = TablaPlanesIngresoCortoPlazo.getRowCount();
    JFileChooser GuardarArchivo = new JFileChooser();
    int opcion = GuardarArchivo.showSaveDialog(this);
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String direccion = GuardarArchivo.getSelectedFile().toString();
        XSSFWorkbook libro = new XSSFWorkbook();
        XSSFSheet hoja = libro.createSheet();
        XSSFRow fila = hoja.createRow(0);
        fila.createCell(0).setCellValue("Granja");
        fila.createCell(1).setCellValue("Galera");
        fila.createCell(2).setCellValue("Fecha de Ingreso");
        fila.createCell(3).setCellValue("Cantidad a Ingresar");

        XSSFRow hileras;/* ww  w .  jav a 2s.  c  o m*/
        for (int i = 0; i < filas; i++) {
            hileras = hoja.createRow((i + 1));
            for (int e = 0; e < 4; e++) {
                hileras.createCell(e).setCellValue(model.getValueAt(i, e).toString());
            }
        }
        try {
            libro.write(new FileOutputStream(new File(direccion + ".xlsx")));
            Desktop.getDesktop().open(new File(direccion + ".xlsx"));
            this.dispose();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:VentanaJava.ConsultarIngresoMedianoExportar.java

private void ExportarPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExportarPlanActionPerformed
    DefaultTableModel model = (DefaultTableModel) TablaConsultaIngresoLargo.getModel();
    int filas = TablaConsultaIngresoLargo.getRowCount();
    JFileChooser GuardarArchivo = new JFileChooser();
    int opcion = GuardarArchivo.showSaveDialog(this);
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String direccion = GuardarArchivo.getSelectedFile().toString();
        XSSFWorkbook libro = new XSSFWorkbook();
        XSSFSheet hoja = libro.createSheet();
        XSSFRow fila = hoja.createRow(0);
        fila.createCell(0).setCellValue("Granja");
        fila.createCell(1).setCellValue("Galera");
        fila.createCell(2).setCellValue("Fecha de Ingreso");
        fila.createCell(3).setCellValue("Cantidad a Ingresar");
        fila.createCell(4).setCellValue("Rol");

        XSSFRow hileras;//from  w w  w  .  j  ava 2 s  .  co m
        for (int i = 0; i < filas; i++) {
            hileras = hoja.createRow((i + 1));
            for (int e = 0; e < 5; e++) {
                hileras.createCell(e).setCellValue(model.getValueAt(i, e).toString());
            }
        }
        try {
            libro.write(new FileOutputStream(new File(direccion + ".xlsx")));
            Desktop.getDesktop().open(new File(direccion + ".xlsx"));
            this.dispose();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:vistas.MantenedorReportes.java

private void btnExportarGastosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarGastosActionPerformed
    Thread t;/*from  w  ww  . j  a va 2s  . c  o m*/
    t = new Thread() {
        @Override
        public void run() {
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet hoja = workbook.createSheet();

            XSSFRow fila = hoja.createRow(0);
            fila.createCell(0).setCellValue("N");
            fila.createCell(1).setCellValue("Vendedor");
            fila.createCell(2).setCellValue("Fecha (Ao-Mes-Da)");
            fila.createCell(3).setCellValue("Descripcin");
            fila.createCell(4).setCellValue("Valor");

            pbGastosExtras.setMaximum(tbGastosExtras.getRowCount());

            XSSFRow filas;
            Rectangle rect;

            for (int i = 0; i < tbGastosExtras.getRowCount(); i++) {
                rect = tbGastosExtras.getCellRect(i, 0, true);

                tbGastosExtras.scrollRectToVisible(rect);

                tbGastosExtras.setRowSelectionInterval(i, i);

                pbGastosExtras.setValue((i + 1));

                filas = hoja.createRow((i + 1));

                filas.createCell(0).setCellValue(tbGastosExtras.getValueAt(i, 0).toString());
                filas.createCell(1).setCellValue(tbGastosExtras.getValueAt(i, 1).toString());
                filas.createCell(2).setCellValue(tbGastosExtras.getValueAt(i, 2).toString());
                filas.createCell(3).setCellValue(tbGastosExtras.getValueAt(i, 3).toString());
                filas.createCell(4).setCellValue(tbGastosExtras.getValueAt(i, 4).toString());

            }

            pbGastosExtras.setValue(0);

            try {

                workbook.write(new FileOutputStream(new File("Excel.xlsx")));
                Desktop.getDesktop().open(new File("Excel.xlsx"));

            } catch (Exception e) {

            }

        }
    };
    t.start();

}