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

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

Introduction

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

Prototype

@SuppressWarnings("resource")
public final void write(OutputStream stream) throws IOException 

Source Link

Document

Write out this document to an Outputstream.

Usage

From source file:ru.inkontext.poi.CreatePivotTableSimple.java

License:Apache License

public static void main(String[] args) throws IOException, InvalidFormatException {

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();/* w w  w .  java2  s.  c  o  m*/

    //Create some data to build the pivot table on
    setCellData(sheet);

    XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("A1:C6", SpreadsheetVersion.EXCEL2007),
            new CellReference("E3"));

    pivotTable.addRowLabel(1); // set second column as 1-th level of rows
    setFormatPivotField(pivotTable, 1, 9); //set format numFmtId=9 0%
    pivotTable.addRowLabel(0); // set first column as 2-th level of rows
    pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2); // Sum up the second column
    setFormatDataField(pivotTable, 2, 3); //numFmtId=3 # ##0

    FileOutputStream fileOut = new FileOutputStream("stackoverflow-pivottable.xlsx");
    wb.write(fileOut);
    fileOut.close();
    wb.close();
}

From source file:ru.jeene.zapretparser.controller.XLSXReportController.java

public void WriteReport(FullReport rep, String timestamp_csv) {
    try (FileInputStream inp = new FileInputStream(shab_name)) {
        XSSFWorkbook wb = new XSSFWorkbook(inp); // Declare XSSF WorkBook
        XSSFSheet sheet = wb.getSheet(" ");
        XSSFCellStyle cs1 = wb.createCellStyle();
        //cs1.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        cs1.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cs1.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cs1.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cs1.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cs1.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        cs1.setWrapText(true);// w  w w .j av  a2 s . c o  m
        cs1.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        XSSFFont f = wb.createFont();
        f.setBold(false);
        f.setFontName("Times New Roman");
        f.setFontHeightInPoints((short) 14);
        cs1.setFont(f);
        int cnt = 0;
        XSSFRow row;
        XSSFCell cell;
        for (Model_FullReport m : rep.getList()) {
            int cnt_cell = 0;

            row = sheet.getRow(t1_start - 1 + cnt);
            if (row == null) {
                row = sheet.createRow(t1_start - 1 + cnt);
            }
            //? URL
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(m.getElement().getUrl());
            cell.setCellStyle(cs1);
            cnt_cell++;

            //
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(m.getElement().getOrg());
            cell.setCellStyle(cs1);
            cnt_cell++;

            //? 
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(m.getElement().getDoc());
            cell.setCellStyle(cs1);
            cnt_cell++;
            //
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(m.getElement().getDate());
            cell.setCellStyle(cs1);
            cnt_cell++;

            //
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(m.getResult().name());
            cell.setCellStyle(cs1);
            cnt_cell++;

            // (?)
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(m.getResult().getDesc());
            cell.setCellStyle(cs1);
            cnt_cell++;

            // ()
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
            cell.setCellValue(m.getResult().getCode());
            cell.setCellStyle(cs1);
            cnt_cell++;
            cnt++;
        }
        // 
        row = sheet.getRow(0);
        cell = row.getCell(0);
        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(MAIN_ZAG_TEMPL + timestamp_csv);

        //   
        HashMap<ResponseResult, Model_NumberReport> map = rep.reportCountBytype();

        //  ?
        sheet = wb.getSheet("");

        //  
        cnt = 0;
        for (Map.Entry<ResponseResult, Model_NumberReport> entry : map.entrySet()) {
            ResponseResult key = entry.getKey();
            Model_NumberReport value = entry.getValue();

            int cnt_cell = 0;
            row = sheet.getRow(t0_start - 1 + cnt);
            if (row == null) {
                row = sheet.createRow(t0_start - 1 + cnt);
            }
            /*//
             cell = row.getCell(cnt_cell);
             if (cell == null) {
             cell = row.createCell(cnt_cell);
             }
             cell.setCellType(XSSFCell.CELL_TYPE_STRING);
             cell.setCellValue(key.name());
             cell.setCellStyle(cs1);
             cnt_cell++;*/

            // (?)
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(key.getDesc());
            cell.setCellStyle(cs1);
            cnt_cell++;

            /*// ()
             cell = row.getCell(cnt_cell);
             if (cell == null) {
             cell = row.createCell(cnt_cell);
             }
             cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
             cell.setCellValue(key.getCode());
             cell.setCellStyle(cs1);
             cnt_cell++;*/
            // (?)
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
            cell.setCellValue(value.getNumber());
            cell.setCellStyle(cs1);
            cnt_cell++;
            // ()
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(FormatUtils.FormatDoubleD(value.getPercent()));
            cell.setCellStyle(cs1);
            cnt_cell++;
            cnt++;
        }

        // 
        row = sheet.getRow(0);
        cell = row.getCell(0);
        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(MAIN_ZAG_TEMPL + timestamp_csv);

        //    HTTP
        map = rep.reportCountBytypeHTTP();
        //  ?
        sheet = wb.getSheet(" HTTP");

        //  
        cnt = 0;
        for (Map.Entry<ResponseResult, Model_NumberReport> entry : map.entrySet()) {
            ResponseResult key = entry.getKey();
            Model_NumberReport value = entry.getValue();

            int cnt_cell = 0;
            row = sheet.getRow(t0_start - 1 + cnt);
            if (row == null) {
                row = sheet.createRow(t0_start - 1 + cnt);
            }
            /*//
             cell = row.getCell(cnt_cell);
             if (cell == null) {
             cell = row.createCell(cnt_cell);
             }
             cell.setCellType(XSSFCell.CELL_TYPE_STRING);
             cell.setCellValue(key.name());
             cell.setCellStyle(cs1);
             cnt_cell++;*/

            // (?)
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(key.getDesc());
            cell.setCellStyle(cs1);
            cnt_cell++;

            /*// ()
             cell = row.getCell(cnt_cell);
             if (cell == null) {
             cell = row.createCell(cnt_cell);
             }
             cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
             cell.setCellValue(key.getCode());
             cell.setCellStyle(cs1);
             cnt_cell++;*/
            // (?)
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
            cell.setCellValue(value.getNumber());
            cell.setCellStyle(cs1);
            cnt_cell++;
            // ()
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(FormatUtils.FormatDoubleD(value.getPercent()));
            cell.setCellStyle(cs1);
            cnt_cell++;
            cnt++;
        }

        // 
        row = sheet.getRow(0);
        cell = row.getCell(0);
        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(MAIN_ZAG_TEMPL + timestamp_csv);

        //    HTTPS
        map = rep.reportCountBytypeHTTPS();
        //  ?
        sheet = wb.getSheet(" HTTPS");

        //  
        cnt = 0;
        for (Map.Entry<ResponseResult, Model_NumberReport> entry : map.entrySet()) {
            ResponseResult key = entry.getKey();
            Model_NumberReport value = entry.getValue();

            int cnt_cell = 0;
            row = sheet.getRow(t0_start - 1 + cnt);
            if (row == null) {
                row = sheet.createRow(t0_start - 1 + cnt);
            }
            /*//
             cell = row.getCell(cnt_cell);
             if (cell == null) {
             cell = row.createCell(cnt_cell);
             }
             cell.setCellType(XSSFCell.CELL_TYPE_STRING);
             cell.setCellValue(key.name());
             cell.setCellStyle(cs1);
             cnt_cell++;*/

            // (?)
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(key.getDesc());
            cell.setCellStyle(cs1);
            cnt_cell++;

            /*// ()
             cell = row.getCell(cnt_cell);
             if (cell == null) {
             cell = row.createCell(cnt_cell);
             }
             cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
             cell.setCellValue(key.getCode());
             cell.setCellStyle(cs1);
             cnt_cell++;*/
            // (?)
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
            cell.setCellValue(value.getNumber());
            cell.setCellStyle(cs1);
            cnt_cell++;
            // ()
            cell = row.getCell(cnt_cell);
            if (cell == null) {
                cell = row.createCell(cnt_cell);
            }
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(FormatUtils.FormatDoubleD(value.getPercent()));
            cell.setCellStyle(cs1);
            cnt_cell++;
            cnt++;
        }

        // 
        row = sheet.getRow(0);
        cell = row.getCell(0);
        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(MAIN_ZAG_TEMPL + timestamp_csv);

        //? 
        String tmp_out = StringUtils.replaceAll(report_name, "!dt!",
                DateUtils.DateToString(new Date(System.currentTimeMillis()), "ddMMyyyy_Hms"));
        try (FileOutputStream out = new FileOutputStream(tmp_out)) {
            wb.write(out);
            logger.info("Report file " + tmp_out + " created");
        }

    } catch (Exception ex) {
        logger.error(ex);
    }
}

From source file:se.inera.intyg.rehabstod.service.export.xlsx.XlsxExportServiceImpl.java

License:Open Source License

@Override
public byte[] export(List<SjukfallEnhet> sjukfallList, PrintSjukfallRequest req, RehabstodUser user, int total)
        throws IOException {

    headers = initHeaders(req, user.getUrval(), isSrsFeatureActive(user));
    XSSFWorkbook wb = new XSSFWorkbook();
    setupFonts(wb);//from   w  w w  .  ja va2 s  .  c  o  m
    XSSFSheet sheet = wb.createSheet(SHEET_TITLE_SJUKFALL);

    int rowNumber = 0;

    // CHECKSTYLE:OFF MagicNumber
    // Start with 2 empty rows to make space for filter
    for (; rowNumber < 2; rowNumber++) {
        sheet.createRow(rowNumber);
    }

    addFilterMainHeader(sheet, rowNumber++, VALDA_FILTER);

    addFilterHeader(sheet, rowNumber++, FILTER_TITLE_FRITEXTFILTER, notEmpty(req) ? req.getFritext() : "-");
    addFilterHeader(sheet, rowNumber++, FILTER_TITLE_VISAPATIENTUPPGIFTER,
            req.isShowPatientId() ? " Ja" : " Nej");
    addFilterHeader(sheet, rowNumber++, FILTER_TITLE_VALD_ALDER,
            req.getAldersIntervall().getMin() + " - " + req.getAldersIntervall().getMax() + " r");
    rowNumber = addDiagnosKapitel(sheet, rowNumber++, FILTER_TITLE_VALDA_DIAGNOSER, req.getDiagnosGrupper()); // NOSONAR
    addFilterHeader(sheet, rowNumber++, FILTER_TITLE_VALD_SLUTDATUM,
            getFilterDate(req.getSlutdatumIntervall()));
    addFilterHeader(sheet, rowNumber++, FILTER_TITLE_VALD_SJUKSKRIVNINGSLANGD,
            req.getLangdIntervall().getMin() + " - " + req.getLangdIntervall().getMax() + " dagar");
    rowNumber = addLakareList(sheet, rowNumber++, FILTER_TITLE_VALDA_LAKARE, req.getLakare(), user); // NOSONAR

    // Instllningar
    addFilterMainHeader(sheet, rowNumber++, H2_SJUKFALLSINSTALLNING);
    addFilterHeader(sheet, rowNumber++, MAXANTAL_DAGAR_UPPEHALL_MELLAN_INTYG,
            req.getMaxIntygsGlapp() + " dagar");
    rowNumber += FILTER_SPACING;

    // Sortering
    addFilterMainHeader(sheet, rowNumber++, VALD_SORTERING_PA_TABELLEN);
    addFilterHeader(sheet, rowNumber++, SORTERING_KOLUMN, req.getSortering().getKolumn());
    addFilterHeader(sheet, rowNumber++, SORTERING_RIKTNING, req.getSortering().getOrder());
    rowNumber += FILTER_SPACING;
    addFilterMainHeader(sheet, rowNumber++, ANTAL_VISAR_ANTAL_PAGAENDE_SJUKFALL);
    addFilterHeader(sheet, rowNumber++, ANTAL_EXPORTEN_VISAR, String.valueOf(sjukfallList.size()));
    addFilterHeader(sheet, rowNumber++,
            user.getUrval() == Urval.ISSUED_BY_ME ? ANTAL_TOTALT_MINA : ANTAL_TOTALT_PA_ENHETEN,
            String.valueOf(total));

    rowNumber += 3;
    addTableHeaderRows(sheet, rowNumber++);
    addDataRows(sheet, rowNumber, sjukfallList, user.getUrval(), req.isShowPatientId(),
            isSrsFeatureActive(user));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    wb.write(baos);
    return baos.toByteArray();
}

From source file:se.minstrel.tools.xssfbuilder.XSSFBuilderFactoryTest.java

License:Open Source License

private void write(XSSFWorkbook workbook, String filename) throws IOException {
    try (FileOutputStream os = new FileOutputStream(filename)) {
        workbook.write(os);
        os.flush();// w w  w  .j  a  v  a2  s .  com
    }
}

From source file:se.vgregion.alfresco.repo.scripts.ExportJsonToExcel.java

public File csvToXLSX(File csv) {
    File xlsx = new File(filename + ".xlsx");
    try {//  ww w  .ja v a2s  . c om
        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.createSheet("sheet1");
        String currentLine = null;
        int RowNum = 0;
        BufferedReader br = new BufferedReader(new FileReader(csv));
        while ((currentLine = br.readLine()) != null) {
            String str[] = currentLine.split(";");
            RowNum++;
            XSSFRow currentRow = sheet.createRow(RowNum);
            for (int i = 0; i < str.length; i++) {
                currentRow.createCell(i).setCellValue(str[i]);
            }
        }

        FileOutputStream fileOutputStream = new FileOutputStream(xlsx);
        workBook.write(fileOutputStream);
        fileOutputStream.close();
    } catch (Exception ex) {
        System.out.println(ex.getMessage() + "Exception in try");
    }
    return xlsx;
}

From source file:sistemas.Utils.java

public static void writeXLSXFile(JTable table, String path) throws IOException {
    TableModel model = table.getModel(); //Table model

    String excelFileName = path;//name of excel file

    String sheetName = "Sheet1";//name of sheet

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet(sheetName);
    XSSFRow rowH = sheet.createRow(0);//from  w  ww.ja va2 s .  c om
    for (int headings = 0; headings < model.getColumnCount(); headings++) { //For each column
        rowH.createCell(headings).setCellValue(model.getColumnName(headings));//Write column name
    }
    //iterating r number of rows
    for (int r = 1; r <= model.getRowCount(); r++) {
        XSSFRow row = sheet.createRow(r);

        //iterating c number of columns
        for (int c = 0; c < model.getColumnCount(); c++) {
            XSSFCell cell = row.createCell(c);

            cell.setCellValue("" + model.getValueAt(r - 1, c));
        }
    }

    FileOutputStream fileOut = new FileOutputStream(excelFileName);

    //write this workbook to an Outputstream.
    wb.write(fileOut);
    fileOut.flush();
    fileOut.close();
}

From source file:si_piket_smkn3.frm_tampil_piket.java

private void exportexcel(String alamat) {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();/*from  w  w  w .j a va2 s . c  o m*/

    //load data dari tabel ke treemap
    TreeMap<Integer, Object[]> data = new TreeMap<>();
    data.put(0,
            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:som.file.StemmedDataFileReader.java

License:Open Source License

public void writeIntoInputDataSheet(List<String> wordsList) {
    XSSFWorkbook workbook = null;
    try {//w  ww .jav  a  2s  . c om
        System.out.println("Writing into Input File");
        FileInputStream file = new FileInputStream(
                new File(GenericHelper.getAbsolutePath() + REVISED_INPUT_SHEET_NAME));
        //FileInputStream file = new FileInputStream(new File(REVISED_INPUT_SHEET_NAME));
        //File file = new File(REVISED_INPUT_SHEET_NAME);

        //Get the workbook instance for XLS file 
        workbook = new XSSFWorkbook(file);

        //Get first sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (row.getRowNum() == 0) {
                continue;
            }

            Cell cell = row.getCell(IGenericConstants.STEMMED_DATA_COLUMN_NUMBER);
            if (wordsList.size() > row.getRowNum()) {
                cell.setCellValue(wordsList.get(row.getRowNum()));
            }
        }

        file.close();

        System.out.println("Writing to the file on the server");
        FileOutputStream outFile = new FileOutputStream(
                new File(GenericHelper.getAbsolutePath() + REVISED_INPUT_SHEET_NAME));
        workbook.write(outFile);
        System.out.println("File Writing Complete");
        outFile.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:standarapp.algorithm.Lecture.java

private void fixXLSX(String nameIn, String nameOut, int sheet, int columnas[]) {
    XSSFWorkbook xwb = lectureXLSX(nameIn);
    XSSFSheet xsheet = xwb.getSheetAt(sheet);

    for (Row row : xsheet) {
        //xsheet.createRow(row.getRowNum());
        for (Cell cell : row) {
            try {
                if (columnas.length == 0 || containsInColumns(columnas, cell.getColumnIndex())) {
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        String contenido = cell.getStringCellValue();
                        if (!cell.getStringCellValue().equals("")) {
                            contenido = fixWords(contenido);
                            xsheet.getRow(row.getRowNum()).getCell(cell.getColumnIndex())
                                    .setCellValue(contenido);
                        } else {
                            xsheet.getRow(row.getRowNum()).getCell(cell.getColumnIndex()).setCellValue("");
                        }/*from   www .  j  a  v a 2s  .com*/
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        double contenido_Numerico = cell.getNumericCellValue();
                        xsheet.getRow(row.getRowNum()).createCell(cell.getColumnIndex())
                                .setCellValue(contenido_Numerico);
                        break;
                    default:
                        System.err.print(cell + "\t\t");
                        xsheet.getRow(row.getRowNum()).createCell(cell.getColumnIndex())
                                .setCTCell((CTCell) cell);
                        break;
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    try (FileOutputStream outputStream = new FileOutputStream(nameOut)) {
        xwb.write(outputStream);
    } 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);
    }
}

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

public StreamedContent getFilePlantilla() {
    filePlantilla = null;/*  w w w  . j  av  a  2 s.com*/
    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;
}