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

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

Introduction

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

Prototype

void write(OutputStream stream) throws IOException;

Source Link

Document

Write out this workbook to an Outputstream.

Usage

From source file:math.page.KnapsackTest.java

License:Apache License

/**
 * write(????)//from w  ww .ja v  a2  s  .co  m
 * TODO(???  ?)
 * TODO(???  ?)
 * TODO(??  ?)
 * TODO(???  ?)
 * 
 * @param name
 * @param @return 
 * @return String DOM
 * @Exception 
 * @since CodingExampleVer(?) 1.1
 */
private static void write(List<Total> totals, List<Knapsack> prices) throws FileNotFoundException {
    String path = "d:" + File.separator + "out.xlsx";// excel??
    String worksheet = "List";// excel??
    String[] title = { "amount", "price", "makeup", "num", "bno", "cno" };// excel
    // excel
    Workbook workbook = new XSSFWorkbook();
    OutputStream os = new FileOutputStream(path);

    try {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }

        // sheet?? new sheet
        Sheet sheet = workbook.createSheet(worksheet);
        Row row = sheet.createRow((short) 0);
        for (int i = 0; i < title.length; i++) {
            // Label(?,? , )
            row.createCell(i).setCellValue(title[i]);
            // row1
            // sheet.addCell(label);
        }
        int num = 1;
        int total = 0;
        for (int i = 0; i < totals.size(); i++) {
            ArrayList<Knapsack> list2 = test1(totals.get(i).getTotal(), prices);
            for (int j = 0; j < list2.size(); j++) {
                Knapsack knapsack = list2.get(j);
                total += knapsack.getWeight();
            }
            if (total != totals.get(i).getTotal()) {
                total = 0;
                continue;
            } else {
                total = 0;
            }

            if (list2 != null && !list2.isEmpty()) {
                prices.removeAll(list2);
            }
            for (int j = 0; j < list2.size(); j++) {
                row = sheet.createRow((short) num);
                Knapsack knapsack = list2.get(j);
                row.createCell(0).setCellValue(totals.get(i).getTotal());
                // label = new jxl.write.Label(0, num + 1, totals.get(i)
                // .getTotal()
                // + ""); // put
                // the
                // title
                // in
                // row1
                row.createCell(1).setCellValue(totals.get(i).getTotal());
                // sheet.addCell(label);
                // label = new jxl.write.Label(1, num + 1, totals.get(i)
                // .getTotal()
                // + "");
                // sheet.addCell(label);
                row.createCell(2).setCellValue(knapsack.getWeight());
                // label = new jxl.write.Label(2, num + 1, list2.get(i)
                // .toString()
                // + "");
                //               
                // sheet.addCell(label);
                row.createCell(3).setCellValue(list2.size());
                // label = new jxl.write.Label(3, num + 1, list2.size() + "");
                //               
                // sheet.addCell(label);
                row.createCell(4).setCellValue(totals.get(i).getNo());
                // label = new jxl.write.Label(4, num + 1, totals.get(i)
                // .getNo()
                // + "");
                //               
                // sheet.addCell(label);
                row.createCell(5).setCellValue(knapsack.getNo());
                // label = new jxl.write.Label(5, num + 1, knapsack.getNo()
                // + "");
                //               
                // sheet.addCell(label);
                num++;
            }

        }

        workbook.write(os);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (os != null) {

            try {
                os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
}

From source file:misuExcel.excelWrite.java

License:Open Source License

private void createWB(Workbook workbook, String name) {

    try {/*w w w.ja  va 2 s.  c om*/
        FileOutputStream out = null;
        String inString = ".xlsx";
        if (_index.equals("xls")) {
            inString = ".xls";
        } else if (_index.equals("xlsx") || _index.equals("")) {
            inString = ".xlsx";
        }
        if (prolevel == 1) {
            out = new FileOutputStream(savePath + "/ExcelTool/" + name + inString);
        } else if (prolevel == 2) {
            out = new FileOutputStream(savePath + "\\ExcelTool\\" + name + inString);
        }
        Log.info("excel is write?");
        workbook.write(out);
        out.flush();
        out.close();
    } catch (IOException e) {
        Log.warm(e.getCause().getMessage());
    }

}

From source file:mn.tsagaangeruud.TimesheetDemo.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;

    if (args.length > 0 && args[0].equals("-xls")) {
        wb = new HSSFWorkbook();
    } else {/*ww w.  j  a v  a  2  s . com*/
        wb = new XSSFWorkbook();
    }

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("Timesheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    //title row
    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue("Weekly Timesheet");
    titleCell.setCellStyle(styles.get("title"));
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));

    //header row
    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);
    Cell headerCell;
    for (int i = 0; i < titles.length; i++) {
        headerCell = headerRow.createCell(i);
        headerCell.setCellValue(titles[i]);
        headerCell.setCellStyle(styles.get("header"));
    }

    int rownum = 2;
    for (int i = 0; i < 10; i++) {
        Row row = sheet.createRow(rownum++);
        for (int j = 0; j < titles.length; j++) {
            Cell cell = row.createCell(j);
            if (j == 9) {
                //the 10th cell contains sum over week days, e.g. SUM(C3:I3)
                String ref = "C" + rownum + ":I" + rownum;
                cell.setCellFormula("SUM(" + ref + ")");
                cell.setCellStyle(styles.get("formula"));
            } else if (j == 11) {
                cell.setCellFormula("J" + rownum + "-K" + rownum);
                cell.setCellStyle(styles.get("formula"));
            } else {
                cell.setCellStyle(styles.get("cell"));
            }
        }
    }

    //row with totals below
    Row sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(35);
    Cell cell;
    cell = sumRow.createCell(0);
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellValue("Total Hrs:");
    cell.setCellStyle(styles.get("formula"));

    for (int j = 2; j < 12; j++) {
        cell = sumRow.createCell(j);
        String ref = (char) ('A' + j) + "3:" + (char) ('A' + j) + "12";
        cell.setCellFormula("SUM(" + ref + ")");
        if (j >= 9)
            cell.setCellStyle(styles.get("formula_2"));
        else
            cell.setCellStyle(styles.get("formula"));
    }
    rownum++;
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Regular Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("L13");
    cell.setCellStyle(styles.get("formula_2"));
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Overtime Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("K13");
    cell.setCellStyle(styles.get("formula_2"));

    //set sample data
    for (int i = 0; i < sample_data.length; i++) {
        Row row = sheet.getRow(2 + i);
        for (int j = 0; j < sample_data[i].length; j++) {
            if (sample_data[i][j] == null)
                continue;

            if (sample_data[i][j] instanceof String) {
                row.getCell(j).setCellValue((String) sample_data[i][j]);
            } else {
                row.getCell(j).setCellValue((Double) sample_data[i][j]);
            }
        }
    }

    //finally set column widths, the width is measured in units of 1/256th of a character width
    sheet.setColumnWidth(0, 30 * 256); //30 characters wide
    for (int i = 2; i < 9; i++) {
        sheet.setColumnWidth(i, 6 * 256); //6 characters wide
    }
    sheet.setColumnWidth(10, 10 * 256); //10 characters wide

    // Write the output to a file
    String file = "timesheet.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:modelo.Excel.java

public void generarExcel(String[] archivoRuta, String[][] registros) {
    try {// w w  w  .jav a 2s  .  c o  m
        /*La ruta donde se crear el archivo*/
        String rutaArchivo = archivoRuta[0] + ".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(archivoRuta[1]);

        /*Hacemos un ciclo para inicializar los valores de 10 filas de celdas*/
        int totalFilas = registros.length;
        int totalColumnas = registros[0].length;

        for (int f = 0; f < totalFilas; f++) {
            /*La clase Row nos permitir crear las filas*/
            Row fila = hoja.createRow(f);

            /*Cada fila tendr 5 celdas de datos*/
            for (int c = 0; c < totalColumnas - 1; 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) {

                    celda.setCellValue(registros[f][c + 1]);
                } else {
                    /*Si no es la primera fila establecemos un valor*/

                    celda.setCellValue(registros[f][c + 1]);
                }
            }
        }

        /*Escribimos en el libro*/
        libro.write(archivo);
        /*Cerramos el flujo de datos*/
        archivo.close();
        /*Y abrimos el archivo con la clase Desktop*/
        Desktop.getDesktop().open(archivoXLS);
    } catch (IOException ex) {
        Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

License:Open Source License

private File createExcelTempFile(Map<AbstractEntity, Map<Service, List<ArticleDemande>>> map,
        AbstractEntity abstractEntity, String nomFichierSansExtension) throws IOException {
    Workbook wb = new XSSFWorkbook();
    Map<Service, List<ArticleDemande>> mapServiceListeArticleDemande = map.get(abstractEntity);

    for (Service service : mapServiceListeArticleDemande.keySet()) {
        Sheet sheet = wb/*w w w . j ava 2 s.c o  m*/
                .createSheet(service.getDirection().getLibelleCourt() + "-" + service.getLibelleCourt());
        sheet.protectSheet(configService.getMotDePasseVerrouExcel());

        construitEntete(wb, mapServiceListeArticleDemande, abstractEntity, service, sheet);
        remplitLigneArticle(wb, mapServiceListeArticleDemande.get(service), sheet);

        // Taille automatique des colonnes selon le contenu
        for (int i = 0; i < 20; i++) {
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 768);
        }
    }
    // Ecriture dans le fichier
    File result = File.createTempFile(nomFichierSansExtension, ".xlsx");
    FileOutputStream fileStream = new FileOutputStream(result);
    wb.write(fileStream);
    return result;
}

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

License:Open Source License

@Override
public void exportCatalogue(Catalogue catalogue) throws IOException {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Feuil1");

    construitEnteteExportCatalogue(wb, sheet);
    int i = 1;//from   ww  w . ja  va  2  s .  c om
    for (Famille famille : catalogue.getListeFamille()) {
        for (SousFamille sousFamille : famille.getListeSousFamille()) {
            for (ArticleCatalogue articleCatalogue : sousFamille.getListeArticleCatalogue()) {
                remplitLigneArticleExportCatalogue(wb, sheet, articleCatalogue, i++);
            }
        }
    }

    // Taille automatique des colonnes selon le contenu
    for (int colonne = 0; colonne <= 12; colonne++) {
        sheet.autoSizeColumn(colonne);
        sheet.setColumnWidth(colonne, sheet.getColumnWidth(colonne) + 768);
    }

    // Ecriture dans le fichier
    File result = File.createTempFile("Export Catalogue", ".xlsx");
    FileOutputStream fileStream = new FileOutputStream(result);
    wb.write(fileStream);

    downloadService.downloadToUser(result,
            "Export Catalogue " + AppockUtil.replaceAllSpecialCharacter(catalogue.getLibelle()) + ".xlsx");
    result.delete();
}

From source file:nc.noumea.mairie.organigramme.utils.ExportExcelUtil.java

License:Open Source License

@GlobalCommand
public static void genereExportExcel(EntiteDto entiteDto, boolean afficheFdpInactive,
        ISirhWSConsumer sirhWSConsumer) throws IOException {
    Workbook wb = new HSSFWorkbook();
    Sheet feuillePrincipale = wb.createSheet("Fiches de postes");
    creerEntete(feuillePrincipale);//ww  w. j  a  va  2 s .com

    String listIdStatutFDP = StatutFichePoste.getListIdStatutActif();

    if (afficheFdpInactive) {
        listIdStatutFDP += "," + StatutFichePoste.INACTIVE.getId();
    }

    int numeroLigne = 1;
    for (FichePosteDto fichePosteDto : sirhWSConsumer.getFichePosteByIdEntite(entiteDto.getIdEntite(),
            listIdStatutFDP, true)) {
        Row row = feuillePrincipale.createRow((short) numeroLigne);
        row.createCell(NUM_COL_SIGLE).setCellValue(fichePosteDto.getSigle());
        row.createCell(NUM_COL_NUMERO).setCellValue(fichePosteDto.getNumero());
        row.createCell(NUM_COL_TITRE).setCellValue(fichePosteDto.getTitre());
        row.createCell(NUM_COL_STATUT).setCellValue(fichePosteDto.getStatutFDP());
        row.createCell(NUM_COL_CATEGORIE).setCellValue(fichePosteDto.getLibelleGradeCategorie());
        row.createCell(NUM_COL_AGENT).setCellValue(fichePosteDto.getAgent());
        row.createCell(NUM_COL_REGLEMENTAIRE).setCellValue(fichePosteDto.getReglementaire());
        row.createCell(NUM_COL_COMMENTAIRE).setCellValue(fichePosteDto.getCommentaire());

        numeroLigne++;
    }

    // Aucolumns
    for (int i = NUM_COL_SIGLE; i <= NUM_COL_COMMENTAIRE; i++) {
        feuillePrincipale.autoSizeColumn(i);
    }

    File tempFile = File.createTempFile("tempFile", ".xls");
    FileOutputStream fileStream = new FileOutputStream(tempFile);
    wb.write(fileStream);
    FileInputStream fileInputStream = new FileInputStream(tempFile);

    // Cration et sauvegarde du fichier
    String nomFichier = "Organigramme - Impression Fiche Poste - " + entiteDto.getSigle() + "-"
            + DateUtil.formatDateForFile(new Date()) + ".xls";
    Filedownload.save(IOUtils.toByteArray(fileInputStream), null, nomFichier);
}

From source file:net.ceos.project.poi.annotated.core.Engine.java

License:Apache License

/**
 * Generate file output stream.//from ww  w. ja  v a2 s. c  o m
 * 
 * @param wb
 *            the {@link Workbook}
 * @param name
 *            the name
 * @return the {@link FileOutputStream} generated
 * @throws WorkbookException
 *             given when problem at the generation of the FileOutputStream.
 */
private FileOutputStream workbookFileOutputStream(final Workbook wb, final String name)
        throws WorkbookException {
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(name);
        wb.write(output);
        output.close();
    } catch (IOException e) {
        throw new WorkbookException(e.getMessage(), e);
    }
    return output;
}

From source file:net.ceos.project.poi.annotated.core.Engine.java

License:Apache License

/**
 * Generate the byte array./*  w  ww .  ja v a2  s.  c om*/
 * 
 * @param wb
 *            the {@link Workbook}
 * @return the byte[]
 * @throws WorkbookException
 *             given when problem at the generation of the byte[].
 */
private byte[] workbookToByteAray(final Workbook wb) throws WorkbookException {
    ByteArrayOutputStream bos = null;
    try {
        bos = new ByteArrayOutputStream();

        wb.write(bos);
        bos.close();
    } catch (IOException e) {
        throw new WorkbookException(e.getMessage(), e);
    }
    return bos.toByteArray();
}

From source file:net.pcal.sqlsheet.XlsDriver.java

License:Apache License

private void flushWorkbook(Workbook workbook, File file) throws IOException {
    FileOutputStream fileOut = null;
    try {//from  w  w  w  . j a  v a 2  s. com
        fileOut = new FileOutputStream(file);
        workbook.write(fileOut);
        fileOut.flush();
    } finally {
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (IOException e) {
                logger.log(Level.WARNING, e.getMessage(), e);
            }
        }
    }
}