Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook createSheet

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook createSheet

Introduction

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

Prototype


@Override
public HSSFSheet createSheet() 

Source Link

Document

create an HSSFSheet for this HSSFWorkbook, adds it to the sheets and returns the high level representation.

Usage

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ImportServiceIntegrationTest.java

License:Open Source License

/**
 * Tests if the {@link InformationSystemInterface} can import the {@link TechnicalComponentRelease} with
 * the "Available for Interfaces" flag set to {@code false}.
 *///from w  w  w .  j  a v  a2 s. com
@Test
public void testImportInterfacesWithNotAvailableForInterfacesTCR() {
    testDataHelper.createBusinessObject("Accounting entry", "");

    TechnicalComponent tc = testDataHelper.createTechnicalComponent("TC1", true, true);
    testDataHelper.createTCRelease(tc, "1", true);

    InformationSystem isA = testDataHelper.createInformationSystem(TEST_ISR_NAME);
    testDataHelper.createInformationSystemRelease(isA, "1", TEST_DESCRIPTION, "1.1.2005", "31.12.2005",
            InformationSystemRelease.TypeOfStatus.CURRENT);

    InformationSystem isB = testDataHelper.createInformationSystem("ISR2");
    testDataHelper.createInformationSystemRelease(isB, "1", TEST_DESCRIPTION, "1.1.2006", "31.12.2006",
            InformationSystemRelease.TypeOfStatus.CURRENT);

    InformationSystemInterface informationSystemInterface = BuildingBlockFactory
            .createInformationSystemInterface();

    informationSystemInterface.setName("test_name");
    informationSystemInterface.setDescription("ISI description");

    final HSSFWorkbook workbook = new HSSFWorkbook();
    final HSSFSheet sheet = workbook.createSheet();
    final HSSFRow row = sheet.createRow(0);
    final Cell cell1 = row.createCell(0);
    final Cell cell2 = row.createCell(1);
    final Cell cell3 = row.createCell(2);
    final Cell cell4 = row.createCell(3);

    cell1.setCellValue("ISR1 # 1");
    cell2.setCellValue("ISR2 # 1");
    cell3.setCellValue("TC1 # 1");
    cell4.setCellValue("<-> Accounting entry ");

    final Map<String, Cell> content = Maps.newHashMap();
    content.put("Information System A", cell1);
    content.put("Information System B", cell2);
    content.put("Technical Components", cell3);
    content.put("Transported Business Objects", cell4);

    final Map<String, Cell> emptyMap = Collections.emptyMap();

    LandscapeData landscapeData = new LandscapeData();
    landscapeData.addRelation(informationSystemInterface, content, emptyMap);

    landscapeData.setLocale(Locale.ENGLISH);
    excelImportService.importLandscapeData(landscapeData);

    InformationSystemInterface isiLoaded = isiService
            .loadObjectByIdIfExists(informationSystemInterface.getId());
    assertNotNull(isiLoaded);
    // assertTrue(isiLoaded.getTechnicalComponentReleases().isEmpty());
    // assertFalse("This test will fail after bug fix :)", isiLoaded.getTechnicalComponentReleases().isEmpty());
}

From source file:de.thorstenberger.taskmodel.impl.ReportBuilderImpl.java

License:Open Source License

public void createExcelBinary(long taskId, OutputStream out)
        throws TaskApiException, MethodNotSupportedException {

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet();
    TaskDef taskDef = taskManager.getTaskDef(taskId);

    short r = 0;/*  w w w  . j  a va 2s. c om*/
    short c = 0;

    List<Tasklet> tasklets = taskManager.getTaskletContainer().getTasklets(taskId);

    ///////////////////
    // create header
    HSSFRow row = sheet.createRow(r++);
    row.createCell(c++).setCellValue("Login");
    row.createCell(c++).setCellValue("Vorname");
    row.createCell(c++).setCellValue("Name");
    List<UserAttribute> uas = taskManager.availableUserAttributes();
    for (UserAttribute ua : uas) {
        row.createCell(c++).setCellValue(ua.getName(null));
    }
    row.createCell(c++).setCellValue("Status");

    // add header cols for automatic and manual corrections
    row.createCell(c++).setCellValue("autom. Korrektur");
    // determine number of correctors
    int maxManualCorrectors = 0;
    for (Tasklet tasklet : tasklets) {
        List<ManualCorrection> mcs = tasklet.getTaskletCorrection().getManualCorrections();
        if (mcs != null && mcs.size() > maxManualCorrectors) {
            maxManualCorrectors = mcs.size();
        }
    }

    // ok, so add header cols for every corrector, as determined above
    for (int i = 1; i <= maxManualCorrectors; i++) {
        row.createCell(c++).setCellValue("Punkte " + i + ". Korrektor");
    }
    for (int i = 1; i <= maxManualCorrectors; i++) {
        row.createCell(c++).setCellValue("Name " + i + ". Korrektor");
    }

    row.createCell(c++).setCellValue("zugeordneter Korrektor");
    row.createCell(c++).setCellValue("Zuordnungs-History");

    // add some more columns, if complex task; e.g. points per category
    if (taskDef instanceof TaskDef_Complex) {

        row.createCell(c++).setCellValue("Startzeit");

        TaskDef_Complex ctd = (TaskDef_Complex) taskDef;
        List<Category> categories = ctd.getComplexTaskDefRoot().getCategoriesList();
        for (Category category : categories) {
            row.createCell(c++).setCellValue(category.getTitle() + " (" + category.getId() + ")");
        }

    }

    // show tasklet flags
    row.createCell(c++).setCellValue("Flags");

    // end create header
    //////////////////////

    for (Tasklet tasklet : tasklets) {

        if (tasklet.getStatus() == Tasklet.Status.INITIALIZED) {
            continue;
        }

        row = sheet.createRow(r++);
        c = 0;

        c = createUserInfoColumns(tasklet, c, wb, row);
        row.createCell(c++).setCellValue(tasklet.getStatus().toString());

        // auto correction points
        row.createCell(c++)
                .setCellValue(tasklet.getTaskletCorrection().getAutoCorrectionPoints() != null
                        ? "" + tasklet.getTaskletCorrection().getAutoCorrectionPoints()
                        : "-");
        List<ManualCorrection> mcs = tasklet.getTaskletCorrection().getManualCorrections();
        for (int i = 0; i < maxManualCorrectors; i++) {
            if (mcs != null && mcs.size() > i) {
                row.createCell(c++).setCellValue(mcs.get(i).getPoints());
            } else {
                row.createCell(c++).setCellValue("-");
            }
        }
        for (int i = 0; i < maxManualCorrectors; i++) {
            if (mcs != null && mcs.size() > i) {
                row.createCell(c++).setCellValue(mcs.get(i).getCorrector());
            } else {
                row.createCell(c++).setCellValue("-");
            }
        }

        row.createCell(c++)
                .setCellValue(tasklet.getTaskletCorrection().getCorrector() != null
                        ? tasklet.getTaskletCorrection().getCorrector()
                        : "-");
        row.createCell(c++).setCellValue(tasklet.getTaskletCorrection().getCorrectorHistory().toString());

        // add the additional cols for complex tasks
        if (taskDef instanceof TaskDef_Complex) {

            TaskDef_Complex ctd = (TaskDef_Complex) taskDef;
            //            if( ctd.getComplexTaskDefRoot().getCorrectionMode().getType() == ComplexTaskDefRoot.CorrectionModeType.MULTIPLECORRECTORS )
            //               throw new IllegalStateException( "MultiCorrectorMode not supported yet. Stay tuned!" );

            ComplexTasklet ct = (ComplexTasklet) tasklet;
            row.createCell(c++).setCellValue(getStringFromMillis(ct.getSolutionOfLatestTry().getStartTime()));

            List<Category> categories = ctd.getComplexTaskDefRoot().getCategoriesList();

            // points per category
            Map<String, Float> pointsInCatMap = new Hashtable<String, Float>();

            // init every category with 0 points
            for (Category category : categories) {
                pointsInCatMap.put(category.getId(), 0f);
            }

            Try studentsLastTry;

            try {
                studentsLastTry = ct.getSolutionOfLatestTry();
            } catch (IllegalStateException e) {
                log.error("Error generating excel stream: ", e);
                throw new TaskApiException(e);
            }

            List<Page> pages = studentsLastTry.getPages();

            for (Page page : pages) {
                Float points = pointsInCatMap.get(page.getCategoryRefId());

                // continue if marked as uncorrected earlier
                if (points == null) {
                    continue;
                }

                boolean markCategoryAsUncorrected = false;

                List<SubTasklet> subTasklets = page.getSubTasklets();
                for (SubTasklet subTasklet : subTasklets) {
                    if (subTasklet.isCorrected()) {
                        points += subTasklet.isAutoCorrected() ? subTasklet.getAutoCorrection().getPoints()
                                : subTasklet.getManualCorrections().get(0).getPoints();
                    } else {
                        markCategoryAsUncorrected = true;
                        break;
                    }
                }

                if (markCategoryAsUncorrected) {
                    pointsInCatMap.remove(page.getCategoryRefId());
                } else {
                    pointsInCatMap.put(page.getCategoryRefId(), points);
                }

            }

            for (Category category : categories) {
                Float points = pointsInCatMap.get(category.getId());
                row.createCell(c++).setCellValue(points != null ? "" + points : "-");
            }

        }

        row.createCell(c++).setCellValue(tasklet.getFlags().toString());

    }

    try {
        wb.write(out);
        out.flush();
    } catch (IOException e) {
        log.error("Error writing excel stream!", e);
        throw new TaskApiException(e);
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            throw new TaskApiException(e);
        }
    }

}

From source file:de.thorstenberger.taskmodel.impl.ReportBuilderImpl.java

License:Open Source License

public void createExcelAnalysisForBlock(long taskId, String categoryId, int blockIndex, OutputStream out)
        throws TaskApiException, MethodNotSupportedException {

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet();
    TaskDef_Complex taskDef;/*from   www .j a va  2s . co m*/
    try {
        taskDef = (TaskDef_Complex) taskManager.getTaskDef(taskId);
    } catch (ClassCastException e) {
        throw new MethodNotSupportedException("Only analysis of complexTasks supported (for now)!");
    }
    Category category = taskDef.getComplexTaskDefRoot().getCategories().get(categoryId);
    Block block = category.getBlock(blockIndex);

    short r = 0;
    short c = 0;

    HSSFRow row = sheet.createRow(r++);
    row.createCell(c++).setCellValue("Login");
    row.createCell(c++).setCellValue("Vorname");
    row.createCell(c++).setCellValue("Name");

    if (!block.getType().equals("mc"))
        throw new MethodNotSupportedException("Only MC analysis supported (for now)!");

    List<SubTaskDefOrChoice> stdocs = block.getSubTaskDefOrChoiceList();
    List<SubTaskDef> stds = new ArrayList<SubTaskDef>();
    // put all SubTaskDefs into stds
    for (SubTaskDefOrChoice stdoc : stdocs) {
        if (stdoc instanceof SubTaskDef) {
            stds.add((SubTaskDef) stdoc);
            row.createCell(c++).setCellValue(((SubTaskDef) stdoc).getId());
        } else {
            Choice choice = (Choice) stdoc;
            for (SubTaskDef std : choice.getSubTaskDefs()) {
                stds.add(std);
                row.createCell(c++).setCellValue(std.getId());
            }
        }
    }

    List<Tasklet> tasklets = taskManager.getTaskletContainer().getTasklets(taskId);

    for (Tasklet tasklet : tasklets) {

        if (tasklet.getStatus() == Tasklet.Status.INITIALIZED) {
            continue;
        }

        if (!(tasklet instanceof ComplexTasklet))
            throw new MethodNotSupportedException("Only analysis of complexTasklets supported (for now)!");

        row = sheet.createRow(r++);
        c = 0;

        ComplexTasklet ct = (ComplexTasklet) tasklet;
        Try actualTry = ct.getSolutionOfLatestTry();

        c = createUserInfoColumns(tasklet, c, wb, row);

        for (SubTaskDef std : stds) {

            SubTasklet_MC mcst = (SubTasklet_MC) actualTry.lookupSubTasklet(std);
            if (mcst == null) {
                row.createCell(c++).setCellValue("[n/a]");
                continue;
            }

            StringBuilder sb = new StringBuilder();
            List<SubTasklet_MC.Answer> answers = mcst.getAnswers();
            boolean first = true;
            for (SubTasklet_MC.Answer answer : answers) {
                if (answer.isSelected()) {
                    if (!first) {
                        sb.append(";");
                    }
                    sb.append(answer.getId());
                    first = false;
                }
            }
            row.createCell(c++).setCellValue(sb.toString());

        }

    }

    try {
        wb.write(out);
        out.flush();
    } catch (IOException e) {
        log.error("Error writing excel stream!", e);
        throw new TaskApiException(e);
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            throw new TaskApiException(e);
        }
    }

}

From source file:demo.poi.BigExample.java

License:Apache License

public static void main(String[] args) throws IOException {
    int rownum;//  ww w  .jav a  2s. c  o m

    // create a new file
    FileOutputStream out = new FileOutputStream("target/bigworkbook.xls");
    // create a new workbook
    HSSFWorkbook wb = new HSSFWorkbook();
    // create a new sheet
    HSSFSheet s = wb.createSheet();
    // declare a row object reference
    HSSFRow r = null;
    // declare a cell object reference
    HSSFCell c = null;
    // create 3 cell styles
    HSSFCellStyle cs = wb.createCellStyle();
    HSSFCellStyle cs2 = wb.createCellStyle();
    HSSFCellStyle cs3 = wb.createCellStyle();
    // create 2 fonts objects
    HSSFFont f = wb.createFont();
    HSSFFont f2 = wb.createFont();

    //set font 1 to 12 point type
    f.setFontHeightInPoints((short) 12);
    //make it red
    f.setColor(HSSFColor.RED.index);
    // make it bold
    //arial is the default font
    f.setBoldweight(Font.BOLDWEIGHT_BOLD);

    //set font 2 to 10 point type
    f2.setFontHeightInPoints((short) 10);
    //make it the color at palette index 0xf (white)
    f2.setColor(HSSFColor.WHITE.index);
    //make it bold
    f2.setBoldweight(Font.BOLDWEIGHT_BOLD);

    //set cell stlye
    cs.setFont(f);
    //set the cell format see HSSFDataFromat for a full list
    cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));

    //set a thin border
    cs2.setBorderBottom(CellStyle.BORDER_THIN);
    //fill w fg fill color
    cs2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    // set foreground fill to red
    cs2.setFillForegroundColor(HSSFColor.RED.index);

    // set the font
    cs2.setFont(f2);

    // set the sheet name to HSSF Test
    wb.setSheetName(0, "HSSF Test");
    // create a sheet with 300 rows (0-299)
    for (rownum = 0; rownum < 300; rownum++) {
        // create a row
        r = s.createRow(rownum);
        // on every other row
        if ((rownum % 2) == 0) {
            // make the row height bigger  (in twips - 1/20 of a point)
            r.setHeight((short) 0x249);
        }

        //r.setRowNum(( short ) rownum);
        // create 50 cells (0-49) (the += 2 becomes apparent later
        for (int cellnum = 0; cellnum < 50; cellnum += 2) {
            // create a numeric cell
            c = r.createCell(cellnum);
            // do some goofy math to demonstrate decimals
            c.setCellValue(rownum * 10000 + cellnum + (((double) rownum / 1000) + ((double) cellnum / 10000)));

            // on every other row
            if ((rownum % 2) == 0) {
                // set this cell to the first cell style we defined
                c.setCellStyle(cs);
            }

            // create a string cell (see why += 2 in the
            c = r.createCell(cellnum + 1);

            // set the cell's string value to "TEST"
            c.setCellValue("TEST");
            // make this column a bit wider
            s.setColumnWidth(cellnum + 1, (int) ((50 * 8) / ((double) 1 / 20)));

            // on every other row
            if ((rownum % 2) == 0) {
                // set this to the white on red cell style
                // we defined above
                c.setCellStyle(cs2);
            }

        }
    }

    //draw a thick black border on the row at the bottom using BLANKS
    // advance 2 rows
    rownum++;
    rownum++;

    r = s.createRow(rownum);

    // define the third style to be the default
    // except with a thick black border at the bottom
    cs3.setBorderBottom(CellStyle.BORDER_THICK);

    //create 50 cells
    for (int cellnum = 0; cellnum < 50; cellnum++) {
        //create a blank type cell (no value)
        c = r.createCell(cellnum);
        // set it to the thick black border style
        c.setCellStyle(cs3);
    }

    //end draw thick black border

    // demonstrate adding/naming and deleting a sheet
    // create a sheet, set its title then delete it
    s = wb.createSheet();
    wb.setSheetName(1, "DeletedSheet");
    wb.removeSheetAt(1);
    //end deleted sheet

    // write the workbook to the output stream
    // close our file (don't blow out our file handles
    wb.write(out);
    out.close();
}

From source file:edu.aplic.escuchadores.EjemploExcel.java

/**
 * Crea una hoja Excel y la guarda./*from   ww w.ja v  a2s. c om*/
 * 
 * @param args
 */

public static void crearExel(File file) {
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;
    HSSFCell celda = null;

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

    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("hola mundo"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Celada dos"));

    fila = hoja.createRow(1);

    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);

    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texton = new HSSFRichTextString("value");
    celda.setCellValue(new HSSFRichTextString("value"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texton = new HSSFRichTextString("value");
    //celda.setCellValue(new HSSFRichTextString("20040044.822"));
    celda.setCellValue(20040044.82);

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        FileOutputStream elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        elFichero.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXslVentas(File file, Venta[] aVentas, Usuario oUsuario) throws IOException {
    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;//w w w  .j  a va2  s.  co  m
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Ventas"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    ProductoVendido oProductoVendido = new ProductoVendido();
    ProductoVendido[] aProductoVendido = null;
    double nTotal = 0.0D;
    int rows = 1;
    if (aVentas != null && aVentas.length > 0) {

        for (Venta oVentaTemp : aVentas) {
            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);
            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oVentaTemp.getUsuario();    
            aProductoVendido = oVentaTemp.getProductoVendido();

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha())));
            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(aProductoVendido[0].getImporte())));
            nTotal += aProductoVendido[0].getImporte();
        }

        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal)));
        //this.campoTotal1.setText(formato.format(nTotal));           
    }

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de ventas generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXslVentasPorTipoProducto(File file, Venta[] aVentas, Usuario oUsuario)
        throws IOException {
    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;//from  www . j a v a2  s .  c o  m
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Ventas por tipos"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(2);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Tipo"));

    // Style Cell 2B
    HSSFCellStyle cellStyle = libro.createCellStyle();
    cellStyle = libro.createCellStyle();
    cellStyle.setFillForegroundColor(org.apache.poi.hssf.util.HSSFColor.GREY_25_PERCENT.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    cellStyle.setBorderTop((short) 1); // single line border
    cellStyle.setBorderBottom((short) 1); // single line border

    ProductoVendido oProductoVendido = new ProductoVendido();
    ProductoVendido[] aProductoVendido = null;
    double nTotal = 0.0D;
    int rows = 1;
    String sFechaTemp = null;
    boolean bColor = true;
    if (aVentas != null && aVentas.length > 0) {
        boolean bPrimerFecha = true;
        for (Venta oVentaTemp : aVentas) {

            // Contador para inicializar la fecha del primer elemento
            if (bPrimerFecha) {
                sFechaTemp = oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha());
                bPrimerFecha = false;
            } else {
                String sFechaFila = oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha());

                if (!sFechaTemp.equals(sFechaFila)) {
                    bColor = !bColor;
                }

                if (bColor) {
                    cellStyle = libro.createCellStyle();
                    cellStyle.setFillForegroundColor(org.apache.poi.hssf.util.HSSFColor.GREY_25_PERCENT.index);
                    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                    cellStyle.setBorderTop((short) 1); // single line border
                    cellStyle.setBorderBottom((short) 1); // single line border

                } else {
                    cellStyle = libro.createCellStyle();
                    cellStyle.setFillForegroundColor(org.apache.poi.hssf.util.HSSFColor.BLUE_GREY.index);
                    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                    cellStyle.setBorderTop((short) 1); // single line border
                    cellStyle.setBorderBottom((short) 1); // single line border

                }

                sFechaTemp = sFechaFila;

            }

            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);
            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oVentaTemp.getUsuario();    
            aProductoVendido = oVentaTemp.getProductoVendido();

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha())));
            celda.setCellStyle(cellStyle);

            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(aProductoVendido[0].getImporte())));
            celda.setCellStyle(cellStyle);

            // Se crea una celda dentro de la fila
            celda = fila.createCell(2);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(aProductoVendido[0].getProducto().getTipo()));
            celda.setCellStyle(cellStyle);

            nTotal += aProductoVendido[0].getImporte();
        }

        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal)));
        //this.campoTotal1.setText(formato.format(nTotal));           
    }

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de ventas generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXslConsumos(File file, Venta[] aVentas, Usuario oUsuario) throws IOException {
    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;//from w w  w . jav  a 2s  .com
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Consumos"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    ProductoVendido oProductoVendido = new ProductoVendido();
    ProductoVendido[] aProductoVendido = null;
    double nTotal = 0.0D;
    int rows = 1;
    if (aVentas != null && aVentas.length > 0) {

        for (Venta oVentaTemp : aVentas) {
            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);
            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oVentaTemp.getUsuario();    
            aProductoVendido = oVentaTemp.getProductoVendido();

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oVentaTemp.getFecha())));
            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(aProductoVendido[0].getImporte())));
            nTotal += aProductoVendido[0].getImporte();
        }

        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal)));
        //this.campoTotal1.setText(formato.format(nTotal));           
    }

    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de consumos generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXlsCompras(File file, Compra[] aCompras, Usuario oUsuario) throws IOException {

    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;//  ww w .  ja  v a 2  s .co  m
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Compras"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    ProductoComprado oProductoComprado = new ProductoComprado();
    ProductoComprado[] aProductoComprado = null;

    double nTotal3 = 0.0D;
    int rows = 1;
    if (aCompras != null && aCompras.length > 0) {
        for (Compra oCompraTemp : aCompras) {
            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);

            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oCompraTemp.getUsuario();    
            aProductoComprado = oCompraTemp.getProductoComprado();

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oCompraTemp.getFecha())));
            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(aProductoComprado[0].getMonto())));
            nTotal3 += aProductoComprado[0].getMonto();
        }
        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal3)));
        //this.campoTotal1.setText(formato.format(nTotal));   
    }
    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de compras generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}

From source file:edu.aplic.utilerias.GenerarArchivoXlsUtil.java

public static void crearXlsGastos(File file, Gasto[] aGastos, Usuario oUsuario) throws IOException {

    FileOutputStream elFichero = null;
    // Se crea el libro
    HSSFWorkbook libro = new HSSFWorkbook();

    // Se crea una hoja dentro del libro
    HSSFSheet hoja = libro.createSheet();
    HSSFRow fila = null;//from   ww w  .j  a  va  2  s  .  c  om
    HSSFCell celda = null;

    fila = hoja.createRow(0);
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    celda.setCellValue(new HSSFRichTextString("Reporte Gastos"));

    if (oUsuario != null) {
        celda = fila.createCell(1);
        hoja.autoSizeColumn(0);
        celda.setCellValue(new HSSFRichTextString("Usuario: " + oUsuario.getNombreCompleto()));
    }

    // Se crea una fila dentro de la hoja
    fila = hoja.createRow(1);
    // Se crea una celda dentro de la fila
    celda = fila.createCell(0);
    hoja.autoSizeColumn(0);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Fecha"));

    // Se crea una celda dentro de la fila
    celda = fila.createCell(1);
    // Se crea el contenido de la celda y se mete en ella.
    //HSSFRichTextString texto = new HSSFRichTextString("hola mundo");
    celda.setCellValue(new HSSFRichTextString("Total"));

    double nTotal = 0.0D;
    int rows = 1;
    if (aGastos != null && aGastos.length > 0) {
        for (Gasto oGastoTemp : aGastos) {
            ++rows;
            hoja.autoSizeColumn(0);
            fila = hoja.createRow(rows);

            //                Usuario oUsuario = new Usuario();
            //                oUsuario = oGastoTemp.getUsuario();    

            // Se crea una celda dentro de la fila
            celda = fila.createCell(0);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(oUtil.ordenarDiaMesAnio(oGastoTemp.getFecha())));
            // Se crea una celda dentro de la fila
            celda = fila.createCell(1);
            // Se crea el contenido de la celda y se mete en ella.
            celda.setCellValue(new HSSFRichTextString(formato.format(oGastoTemp.getMonto())));
            nTotal += oGastoTemp.getMonto();
        }
        ++rows;
        fila = hoja.createRow(rows);
        // Se crea una celda dentro de la fila
        celda = fila.createCell(0);
        // Se crea el contenido de la celda y se mete en ella.
        //HSSFRichTextString texton = new HSSFRichTextString("value");
        celda.setCellValue(new HSSFRichTextString("Total"));
        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);
        // Se crea el contenido de la celda y se mete en ella.
        celda.setCellValue(new HSSFRichTextString(formato.format(nTotal)));
        //this.campoTotal1.setText(formato.format(nTotal));   
    }
    // Se salva el libro.
    try {
        //FileOutputStream elFichero = new FileOutputStream("ventas"+new Date().toString()+".xls");
        elFichero = new FileOutputStream(file);

        libro.write(elFichero);
        JOptionPane.showMessageDialog(null, "Reporte de gastos generado correctamente \n " + file.getPath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        elFichero.close();
    }
}