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:FormatConvert.exceloperation.ExcelOperation.java

public static void MergeExcel(String sourceDir, String targetexcel) {
    try {//from  w ww .  j a  v a  2s.com
        File[] filelist = FilelistReader.getFileList(sourceDir);
        FileOutputStream fileOut = new FileOutputStream(targetexcel);
        Workbook wb = new XSSFWorkbook();
        for (int i = 0; i < filelist.length; i++) {
            File f = filelist[i];
            if (f.getName().endsWith(".xlsx")) {
                FileInputStream is = (new FileInputStream(f));
                XSSFWorkbook wb2 = new XSSFWorkbook(is);
                XSSFSheet sheet = wb2.getSheetAt(0);
                Sheet sheetnew = wb.createSheet(f.getName());
                //System.out.println(sheet.get);
                Util.copySheets((XSSFSheet) sheetnew, sheet);

            } else if (f.getName().endsWith(".xls")) {
                FileInputStream is = (new FileInputStream(f));
                HSSFWorkbook wb2 = new HSSFWorkbook(is);
                HSSFSheet sheet = wb2.getSheetAt(0);
                Sheet sheetnew = wb.createSheet(f.getName());
                Util.copySheets((HSSFSheet) sheetnew, sheet);
            }
        }
        wb.write(fileOut);

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

From source file:FormatConvert.tab2excel.java

public void tab2excel() throws FileNotFoundException, IOException {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet1 = wb.createSheet("input");

    CellStyle style = wb.createCellStyle();
    style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    int rowIndex = 0;
    BufferedReader br = null;/*w  ww  . j  ava2s.  c o m*/
    try {
        br = new BufferedReader(new FileReader(new File(input)));
        String[] str;
        while (br.ready()) {
            str = br.readLine().split(seperator);

            Row row = sheet1.createRow(rowIndex);
            for (int i = 0; i < str.length; i++) {
                row.createCell(i).setCellValue(str[i]);
            }
            rowIndex++;
        }
        br.close();
    } catch (FileNotFoundException ex) {
        System.out.println(input + " is not found! please check your filepath ");
    } catch (IOException ex) {
        System.out.println("IO error");
    }

    FileOutputStream fileOut = new FileOutputStream(output + ".xlsx");
    wb.write(fileOut);
    fileOut.close();
    System.out.println("Convert finished. The output file is named as " + output + ".xlsx");
}

From source file:forseti.reportes.JReportesDlg.java

License:Open Source License

@SuppressWarnings({ "unused" })
public void CargarReporte(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DocumentException {
    super.doPost(request, response);

    int m_ID_Report = Integer.parseInt(request.getParameter("REPID"));
    int m_LinesNum = 0;

    Boolean m_bFilterL1 = new Boolean(true);
    Boolean m_bSelectL1 = new Boolean(true);
    Boolean m_bSelectL2 = new Boolean(true);
    Boolean m_bSelectL3 = new Boolean(true);
    Boolean m_bComputeL1 = new Boolean(true);
    Boolean m_bComputeL2 = new Boolean(true);
    Boolean m_bComputeL3 = new Boolean(true);

    // Construye las estructuras
    JReportesSet m_RepSet = new JReportesSet(request);
    m_RepSet.m_Where = "ID_Report = " + m_ID_Report;
    m_RepSet.Open();/*www . ja v a  2s. com*/
    boolean m_Graficar = m_RepSet.getAbsRow(0).getGraficar();

    // empieza por el select de primer nivel
    JReportesBind2Set m_selectL1 = new JReportesBind2Set(request);
    m_selectL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '0'";
    m_selectL1.m_OrderBy = "ID_Sentence ASC";
    m_selectL1.Open();
    if (m_selectL1.getNumRows() < 1)
        m_bSelectL1 = Boolean.FALSE;

    JReportesBind3Set m_colL1 = new JReportesBind3Set(request);
    m_colL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '0'";
    m_colL1.m_OrderBy = "ID_Column asc";
    m_colL1.Open();

    // sigue por el select de segundo nivel
    JReportesBind2Set m_selectL2 = new JReportesBind2Set(request);
    m_selectL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '0'";
    m_selectL2.m_OrderBy = "ID_Sentence ASC";
    m_selectL2.Open();
    if (m_selectL2.getNumRows() < 1)
        m_bSelectL2 = Boolean.FALSE;

    JReportesBind3Set m_colL2 = new JReportesBind3Set(request);
    m_colL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '0'";
    m_colL2.m_OrderBy = "ID_Column asc";
    m_colL2.Open();

    // sigue por el select de tercer nivel
    JReportesBind2Set m_selectL3 = new JReportesBind2Set(request);
    m_selectL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '0'";
    m_selectL3.m_OrderBy = "ID_Sentence ASC";
    m_selectL3.Open();
    if (m_selectL3.getNumRows() < 1)
        m_bSelectL3 = Boolean.FALSE;

    JReportesBind3Set m_colL3 = new JReportesBind3Set(request);
    m_colL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '0'";
    m_colL3.m_OrderBy = "ID_Column asc";
    m_colL3.Open();

    // Ahora revisa las sentencias compute
    // empieza por el compute de primer nivel
    JReportesBind2Set m_computeL1 = new JReportesBind2Set(request);
    m_computeL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '1'";
    m_computeL1.m_OrderBy = "ID_Sentence ASC";
    m_computeL1.Open();
    if (m_computeL1.getNumRows() < 1)
        m_bComputeL1 = Boolean.FALSE;

    JReportesBind3Set m_colCL1 = new JReportesBind3Set(request);
    m_colCL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '1'";
    m_colCL1.m_OrderBy = "ID_Column asc";
    m_colCL1.Open();

    // sigue por el compute de segundo nivel
    JReportesBind2Set m_computeL2 = new JReportesBind2Set(request);
    m_computeL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '1'";
    m_computeL2.m_OrderBy = "ID_Sentence ASC";
    m_computeL2.Open();
    if (m_computeL2.getNumRows() < 1)
        m_bComputeL2 = Boolean.FALSE;

    JReportesBind3Set m_colCL2 = new JReportesBind3Set(request);
    m_colCL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '1'";
    m_colCL2.m_OrderBy = "ID_Column asc";
    m_colCL2.Open();

    // sigue por el compute de tercer nivel
    JReportesBind2Set m_computeL3 = new JReportesBind2Set(request);
    m_computeL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '1'";
    m_computeL3.m_OrderBy = "ID_Sentence ASC";
    m_computeL3.Open();
    if (m_computeL3.getNumRows() < 1)
        m_bComputeL3 = Boolean.FALSE;

    JReportesBind3Set m_colCL3 = new JReportesBind3Set(request);
    m_colCL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '1'";
    m_colCL3.m_OrderBy = "ID_Column asc";
    m_colCL3.Open();

    //System.out.println("CARGADAS LAS SENTENCIAS");
    // Ahora carga los datos
    JReportesLevel1 m_setL1 = new JReportesLevel1(request);
    // Carga la sentencia del compute;
    JReportesCompL1Set m_setCL1 = new JReportesCompL1Set(request);

    if (m_bSelectL1.booleanValue()) {

        if (m_bFilterL1.booleanValue()) {
            // si existe un filtro especial lo cargar
            String sqll1 = VerifyFilerClause(new StringBuffer(m_selectL1.getRow(0).getSelect_Clause()),
                    request);
            //System.out.println(sqll1);
            m_setL1.setSQL(sqll1);
        } else {
            //out.println(m_selectL1.getRow(0).getSelect_Clause());
            m_setL1.setSQL(m_selectL1.getRow(0).getSelect_Clause());
        }
        m_setL1.Open();
        m_LinesNum += m_setL1.getNumRows();

        if (m_bComputeL1.booleanValue()) {

            if (m_bFilterL1.booleanValue()) // si existe un filtro especial lo cargar
                m_setCL1.setSQL(
                        VerifyFilerClause(new StringBuffer(m_computeL1.getRow(0).getSelect_Clause()), request));
            else
                m_setCL1.setSQL(m_computeL1.getRow(0).getSelect_Clause());

            //System.out.println(m_setCL1.getSQL());
            m_setCL1.Open();
            m_LinesNum += m_setCL1.getNumRows();
        }

        if (m_bSelectL2.booleanValue()) {
            for (int contL1 = 0; contL1 < m_setL1.getNumRows(); contL1++) {
                REP_LEVEL1 pNodeL1 = (REP_LEVEL1) m_setL1.getAbsRow(contL1);
                pNodeL1.getSetL2().setSQL(VerifyWhereClause(
                        new StringBuffer(m_selectL2.getAbsRow(0).getSelect_Clause()), pNodeL1));
                //System.out.println(pNodeL1.getSetL2().getSQL());
                pNodeL1.getSetL2().Open();
                m_LinesNum += pNodeL1.getSetL2().getNumRows();

                if (m_bComputeL2.booleanValue()) {
                    pNodeL1.getSetCL2().setSQL(VerifyWhereClause(
                            new StringBuffer(m_computeL2.getRow(0).getSelect_Clause()), pNodeL1));
                    //System.out.println(pNodeL1.getSetCL2().getSQL());
                    pNodeL1.getSetCL2().Open();
                    m_LinesNum += pNodeL1.getSetCL2().getNumRows();
                }

                if (m_bSelectL3.booleanValue()) {
                    for (int contL2 = 0; contL2 < pNodeL1.getSetL2().getNumRows(); contL2++) {
                        REP_LEVEL2 pNodeL2 = pNodeL1.getSetL2().getAbsRow(contL2);
                        pNodeL2.getSetL3().setSQL(VerifyWhereClause(
                                new StringBuffer(m_selectL3.getAbsRow(0).getSelect_Clause()), pNodeL2));
                        //System.out.println(pNodeL2.getSetL3().getSQL());
                        pNodeL2.getSetL3().Open();
                        m_LinesNum += pNodeL2.getSetL3().getNumRows();

                        if (m_bComputeL3.booleanValue()) {
                            pNodeL2.getSetCL3().setSQL(VerifyWhereClause(
                                    new StringBuffer(m_computeL3.getAbsRow(0).getSelect_Clause()), pNodeL2));
                            //System.out.println(pNodeL2.getSetCL3().getSQL());
                            pNodeL2.getSetCL3().Open();
                            m_LinesNum += pNodeL2.getSetCL3().getNumRows();
                        }
                    }
                }
            }
        }
    }

    //Verifica a donde irse
    boolean graficar = false;

    if (m_Graficar) // es grfica
        graficar = (request.getParameter("fsi_sino").equals("1") ? true : false);

    if (graficar) // es grfica
    {
        String GRAF = request.getParameter("fsi_graf");
        boolean enCols = (request.getParameter("fsi_encols").equals("1") ? true : false);
        boolean linejes = (request.getParameter("fsi_linejes").equals("1") ? true : false);
        byte tipo = Byte.parseByte(request.getParameter("fsi_tipo"));
        String fsi_filtro = (String) request.getAttribute("fsi_filtro");
        String formato = request.getParameter("formato");

        JFsiGraficas graf;

        if (GRAF.equals("BAR"))
            graf = new JFsiGrafBarras(m_colL1, m_setL1,
                    m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro, enCols, linejes, tipo,
                    m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());
        else if (GRAF.equals("LIN"))
            graf = new JFsiGrafLineas(m_colL1, m_setL1,
                    m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro, enCols, linejes, tipo,
                    m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());
        else if (GRAF.equals("CIRC"))
            graf = new JFsiGrafCirc(m_colL1, m_setL1, m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro,
                    enCols, tipo, m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());
        else
            graf = new JFsiGrafAreas(m_colL1, m_setL1,
                    m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro, enCols, linejes, tipo,
                    m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(graf.getBufferedImage(), formato, baos);
            byte[] imageInByte = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(imageInByte);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, ("image/" + formato),
                    imageInByte.length, ("grafica." + formato));
        } catch (IOException ioe) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.print("Error en el grfico: " + ioe);
            out.flush();
            ioe.printStackTrace(out);
        }
    } else {
        String rep_permitido = "true";
        request.setAttribute("rep_permitido", rep_permitido);

        // Ahora pone los atributos para el jsp
        request.setAttribute("m_RepSet", m_RepSet);
        request.setAttribute("m_setL1", m_setL1);
        request.setAttribute("m_setCL1", m_setCL1);
        request.setAttribute("m_bSelectL1", m_bSelectL1);
        request.setAttribute("m_bSelectL2", m_bSelectL2);
        request.setAttribute("m_bSelectL3", m_bSelectL3);
        request.setAttribute("m_bComputeL1", m_bComputeL1);
        request.setAttribute("m_bComputeL2", m_bComputeL2);
        request.setAttribute("m_bComputeL3", m_bComputeL3);
        request.setAttribute("m_selectL1", m_selectL1);
        request.setAttribute("m_selectL2", m_selectL2);
        request.setAttribute("m_selectL3", m_selectL3);
        request.setAttribute("m_computeL1", m_computeL1);
        request.setAttribute("m_computeL2", m_computeL2);
        request.setAttribute("m_computeL3", m_computeL3);
        request.setAttribute("m_colL1", m_colL1);
        request.setAttribute("m_colL2", m_colL2);
        request.setAttribute("m_colL3", m_colL3);
        request.setAttribute("m_colCL1", m_colCL1);
        request.setAttribute("m_colCL2", m_colCL2);
        request.setAttribute("m_colCL3", m_colCL3);

        if (request.getParameter("exportacion").equals("html")) {
            //Para archivos muy pequeos
            //response.setContentType("text/html");
            //PrintWriter out = response.getWriter();
            //out.print(generarReporteHtml(request, response));
            byte[] byteArray = generarReporteHtml(request, response, true).getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "text/html", byteArray.length,
                    "reporte.html");
        } else if (request.getParameter("exportacion").equals("odt")) {
            //response.setContentType("application/vnd.oasis.opendocument.text");
            //PrintWriter out = response.getWriter();
            //out.print(generarReporteHtml(request, response));
            byte[] byteArray = generarReporteHtml(request, response, false).getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais,
                    "application/vnd.oasis.opendocument.text", byteArray.length, "reporte.odt");
        } else if (request.getParameter("exportacion").equals("doc")) {
            //response.setContentType("application/msword");
            //PrintWriter out = response.getWriter();
            //out.print(generarReporteHtml(request, response));
            byte[] byteArray = generarReporteHtml(request, response, false).getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "application/msword",
                    byteArray.length, "reporte.doc");
        } else if (request.getParameter("exportacion").equals("rtf")) {
            //response.setContentType("application/rtf");
            //PrintWriter out = response.getWriter();
            //out.print(generarReporteHtml(request, response));
            byte[] byteArray = generarReporteHtml(request, response, false).getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "application/rtf",
                    byteArray.length, "reporte.rtf");
        } else if (request.getParameter("exportacion").equals("xls")) {
            //response.setContentType("application/vnd.ms-excel");
            //OutputStream Out = response.getOutputStream();
            //Workbook wb = new HSSFWorkbook();
            //generarArchivoXLS(request, response, wb);
            //wb.write(Out);
            //Out.close();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Workbook wb = new HSSFWorkbook();
            generarArchivoXLS(request, response, wb);
            wb.write(baos);
            byte[] byteArray = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "application/vnd.ms-excel",
                    byteArray.length, "reporte.xls");
        } else if (request.getParameter("exportacion").equals("ods")) {
            //response.setContentType("application/vnd.oasis.opendocument.spreadsheet");
            //OutputStream Out = response.getOutputStream();
            //Workbook wb = new HSSFWorkbook();
            //generarArchivoXLS(request, response, wb);
            //wb.write(Out);
            //Out.close();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Workbook wb = new HSSFWorkbook();
            generarArchivoXLS(request, response, wb);
            wb.write(baos);
            byte[] byteArray = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais,
                    "application/vnd.oasis.opendocument.spreadsheet", byteArray.length, "reporte.ods");
        } else if (request.getParameter("exportacion").equals("csv")) {
            //response.setContentType("text/plain");
            //PrintWriter out = response.getWriter();
            //out.print(generarArchivoCSV(request, response, "|"));
            byte[] byteArray = generarArchivoCSV(request, response, "|").getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "text/plain",
                    byteArray.length, "reporte.csv");
        } else if (request.getParameter("exportacion").equals("xml")) {
            Document document = new Document();
            //response.setContentType("application/xml");
            //PrintWriter out = response.getWriter();
            //out.print(generarArchivoDOM(request, response, document));
            byte[] byteArray = generarArchivoDOM(request, response, document).getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "text/xml", byteArray.length,
                    "reporte.xml");
        } else if (request.getParameter("exportacion").equals("pdf")) {
            //response.setContentType("application/pdf");
            //OutputStream Out = response.getOutputStream();
            //ITextRenderer renderer = new ITextRenderer();
            //renderer.setDocumentFromString(generarReporteHtml(request, response));
            //renderer.layout();
            //renderer.createPDF(Out);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(generarReporteHtml(request, response, true));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            renderer.layout();
            renderer.createPDF(baos);
            byte[] byteArray = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "application/pdf",
                    byteArray.length, "reporte.pdf");
        } else if (request.getParameter("exportacion").equals("sql")) {
            //response.setContentType("text/plain");
            //PrintWriter out = response.getWriter();
            //out.print(generarArchivoSQL(request, response));
            byte[] byteArray = generarArchivoSQL(request, response).getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "text/plain",
                    byteArray.length, "reporte.sql");
        } else //xhtml
        {
            //response.setContentType("text/plain");
            //PrintWriter out = response.getWriter();
            //out.print(generarReporteHtml(request, response));
            byte[] byteArray = generarReporteHtml(request, response, true).getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            JBajarArchivo fd = new JBajarArchivo();
            fd.doDownload(response, getServletConfig().getServletContext(), bais, "text/plain",
                    byteArray.length, "reporte.txt");
        }

        //irApag("/forsetiweb/reportes/rep_reportes_imp.jsp", request, response); 
    }
}

From source file:fr.amapj.service.engine.generator.excel.AbstractExcelGenerator.java

License:Open Source License

@Override
public InputStream getContent() {

    Workbook workbook = new CoreGeneratorService().getFichierExcel(this);

    ByteArrayOutputStream imagebuffer = new ByteArrayOutputStream();

    try {//from w ww .  j  a  v a2s .  co m
        workbook.write(imagebuffer);
    } catch (IOException e) {
        throw new RuntimeException("Erreur inattendue");
    }
    return new ByteArrayInputStream(imagebuffer.toByteArray());
}

From source file:fr.amapj.service.engine.generator.excel.AbstractExcelGenerator.java

License:Open Source License

public void test() throws IOException {
    TestTools.init();/*  w  w w . j  a va 2 s.  c o m*/

    String filename = "test." + this.getFormat().name().toLowerCase();
    Workbook workbook = new CoreGeneratorService().getFichierExcel(this);

    FileOutputStream fileOut = new FileOutputStream(filename);
    workbook.write(fileOut);
    fileOut.close();
    System.out.println("Your excel file has been generated!");
}

From source file:fr.amapj.service.engine.generator.excel.AbstractExcelGenerator.java

License:Open Source License

/**
 * Pour les tests unitaires /*from  w w w .  j  av a 2 s  .  co m*/
 * 
 */
public UnitTestInfo unitTest() throws IOException {
    UnitTestInfo res = new UnitTestInfo();

    res.fileExtension = this.getFormat().name().toLowerCase();
    Workbook workbook = new CoreGeneratorService().getFichierExcel(this);

    res.baos = new ByteArrayOutputStream();
    workbook.write(res.baos);

    return res;
}

From source file:fsi_admin.reportes.JReportesDlg.java

License:Open Source License

@SuppressWarnings({ "unused" })
public void CargarReporte(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DocumentException {
    super.doPost(request, response);

    response.setContentType("text/html");

    int m_ID_Report = Integer.parseInt(request.getParameter("REPID"));
    int m_LinesNum = 0;

    Boolean m_bFilterL1 = new Boolean(true);
    Boolean m_bSelectL1 = new Boolean(true);
    Boolean m_bSelectL2 = new Boolean(true);
    Boolean m_bSelectL3 = new Boolean(true);
    Boolean m_bComputeL1 = new Boolean(true);
    Boolean m_bComputeL2 = new Boolean(true);
    Boolean m_bComputeL3 = new Boolean(true);

    // Construye las estructuras
    JReportesSet m_RepSet = new JReportesSet(request);
    m_RepSet.m_Where = "ID_Report = " + m_ID_Report;
    m_RepSet.ConCat(true);//from   w  ww. j a v a  2  s . c o m
    m_RepSet.Open();
    boolean m_Graficar = m_RepSet.getAbsRow(0).getGraficar();

    // empieza por el select de primer nivel
    JReportesBind2Set m_selectL1 = new JReportesBind2Set(request);
    m_selectL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '0'";
    m_selectL1.m_OrderBy = "ID_Sentence ASC";
    m_selectL1.ConCat(true);
    m_selectL1.Open();
    if (m_selectL1.getNumRows() < 1)
        m_bSelectL1 = Boolean.FALSE;

    JReportesBind3Set m_colL1 = new JReportesBind3Set(request);
    m_colL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '0'";
    m_colL1.m_OrderBy = "ID_Column asc";
    m_colL1.ConCat(true);
    m_colL1.Open();

    // sigue por el select de segundo nivel
    JReportesBind2Set m_selectL2 = new JReportesBind2Set(request);
    m_selectL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '0'";
    m_selectL2.m_OrderBy = "ID_Sentence ASC";
    m_selectL2.ConCat(true);
    m_selectL2.Open();
    if (m_selectL2.getNumRows() < 1)
        m_bSelectL2 = Boolean.FALSE;

    JReportesBind3Set m_colL2 = new JReportesBind3Set(request);
    m_colL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '0'";
    m_colL2.m_OrderBy = "ID_Column asc";
    m_colL2.ConCat(true);
    m_colL2.Open();

    // sigue por el select de tercer nivel
    JReportesBind2Set m_selectL3 = new JReportesBind2Set(request);
    m_selectL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '0'";
    m_selectL3.m_OrderBy = "ID_Sentence ASC";
    m_selectL3.ConCat(true);
    m_selectL3.Open();
    if (m_selectL3.getNumRows() < 1)
        m_bSelectL3 = Boolean.FALSE;

    JReportesBind3Set m_colL3 = new JReportesBind3Set(request);
    m_colL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '0'";
    m_colL3.m_OrderBy = "ID_Column asc";
    m_colL3.ConCat(true);
    m_colL3.Open();

    // Ahora revisa las sentencias compute
    // empieza por el compute de primer nivel
    JReportesBind2Set m_computeL1 = new JReportesBind2Set(request);
    m_computeL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '1'";
    m_computeL1.m_OrderBy = "ID_Sentence ASC";
    m_computeL1.ConCat(true);
    m_computeL1.Open();
    if (m_computeL1.getNumRows() < 1)
        m_bComputeL1 = Boolean.FALSE;

    JReportesBind3Set m_colCL1 = new JReportesBind3Set(request);
    m_colCL1.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '1' and ID_IsCompute = '1'";
    m_colCL1.m_OrderBy = "ID_Column asc";
    m_colCL1.ConCat(true);
    m_colCL1.Open();

    // sigue por el compute de segundo nivel
    JReportesBind2Set m_computeL2 = new JReportesBind2Set(request);
    m_computeL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '1'";
    m_computeL2.m_OrderBy = "ID_Sentence ASC";
    m_computeL2.ConCat(true);
    m_computeL2.Open();
    if (m_computeL2.getNumRows() < 1)
        m_bComputeL2 = Boolean.FALSE;

    JReportesBind3Set m_colCL2 = new JReportesBind3Set(request);
    m_colCL2.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '2' and ID_IsCompute = '1'";
    m_colCL2.m_OrderBy = "ID_Column asc";
    m_colCL2.ConCat(true);
    m_colCL2.Open();

    // sigue por el compute de tercer nivel
    JReportesBind2Set m_computeL3 = new JReportesBind2Set(request);
    m_computeL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '1'";
    m_computeL3.m_OrderBy = "ID_Sentence ASC";
    m_computeL3.ConCat(true);
    m_computeL3.Open();
    if (m_computeL3.getNumRows() < 1)
        m_bComputeL3 = Boolean.FALSE;

    JReportesBind3Set m_colCL3 = new JReportesBind3Set(request);
    m_colCL3.m_Where = "ID_Report = '" + m_ID_Report + "' and ID_Sentence = '3' and ID_IsCompute = '1'";
    m_colCL3.m_OrderBy = "ID_Column asc";
    m_colCL3.ConCat(true);
    m_colCL3.Open();

    //System.out.println("CARGADAS LAS SENTENCIAS");
    // Ahora carga los datos
    JReportesLevel1 m_setL1 = new JReportesLevel1(request);
    // Carga la sentencia del compute;
    JReportesCompL1Set m_setCL1 = new JReportesCompL1Set(request);

    if (m_bSelectL1.booleanValue()) {

        if (m_bFilterL1.booleanValue()) {
            // si existe un filtro especial lo cargar
            String sqll1 = VerifyFilerClause(new StringBuffer(m_selectL1.getRow(0).getSelect_Clause()),
                    request);
            m_setL1.setSQL(sqll1);
        } else {
            //out.println(m_selectL1.getRow(0).getSelect_Clause());
            m_setL1.setSQL(m_selectL1.getRow(0).getSelect_Clause());
        }
        m_setL1.ConCat(true);
        m_setL1.Open();
        m_LinesNum += m_setL1.getNumRows();

        if (m_bComputeL1.booleanValue()) {

            if (m_bFilterL1.booleanValue()) // si existe un filtro especial lo cargar
                m_setCL1.setSQL(
                        VerifyFilerClause(new StringBuffer(m_computeL1.getRow(0).getSelect_Clause()), request));
            else
                m_setCL1.setSQL(m_computeL1.getRow(0).getSelect_Clause());

            //AfxMessageBox(sql);
            m_setCL1.ConCat(true);
            m_setCL1.Open();
            m_LinesNum += m_setCL1.getNumRows();
        }

        if (m_bSelectL2.booleanValue()) {
            for (int contL1 = 0; contL1 < m_setL1.getNumRows(); contL1++) {
                REP_LEVEL1 pNodeL1 = (REP_LEVEL1) m_setL1.getAbsRow(contL1);
                pNodeL1.getSetL2().setSQL(VerifyWhereClause(
                        new StringBuffer(m_selectL2.getAbsRow(0).getSelect_Clause()), pNodeL1));
                pNodeL1.getSetL2().ConCat(true);
                pNodeL1.getSetL2().Open();
                m_LinesNum += pNodeL1.getSetL2().getNumRows();

                if (m_bComputeL2.booleanValue()) {
                    pNodeL1.getSetCL2().setSQL(VerifyWhereClause(
                            new StringBuffer(m_computeL2.getRow(0).getSelect_Clause()), pNodeL1));
                    pNodeL1.getSetCL2().ConCat(true);
                    pNodeL1.getSetCL2().Open();
                    m_LinesNum += pNodeL1.getSetCL2().getNumRows();
                }

                if (m_bSelectL3.booleanValue()) {
                    for (int contL2 = 0; contL2 < pNodeL1.getSetL2().getNumRows(); contL2++) {
                        REP_LEVEL2 pNodeL2 = pNodeL1.getSetL2().getAbsRow(contL2);
                        pNodeL2.getSetL3().setSQL(VerifyWhereClause(
                                new StringBuffer(m_selectL3.getAbsRow(0).getSelect_Clause()), pNodeL2));
                        pNodeL2.getSetL3().ConCat(true);
                        pNodeL2.getSetL3().Open();
                        m_LinesNum += pNodeL2.getSetL3().getNumRows();

                        if (m_bComputeL3.booleanValue()) {
                            pNodeL2.getSetCL3().setSQL(VerifyWhereClause(
                                    new StringBuffer(m_computeL3.getAbsRow(0).getSelect_Clause()), pNodeL2));
                            pNodeL2.getSetCL3().ConCat(true);
                            pNodeL2.getSetCL3().Open();
                            m_LinesNum += pNodeL2.getSetCL3().getNumRows();
                        }
                    }
                }
            }
        }
    }

    //  Verifica a donde irse
    boolean graficar = false;

    if (m_Graficar) // es grfica
        graficar = (request.getParameter("fsi_sino").equals("1") ? true : false);

    if (graficar) // es grfica
    {
        String GRAF = request.getParameter("fsi_graf");
        boolean enCols = (request.getParameter("fsi_encols").equals("1") ? true : false);
        boolean linejes = (request.getParameter("fsi_linejes").equals("1") ? true : false);
        byte tipo = Byte.parseByte(request.getParameter("fsi_tipo"));
        String fsi_filtro = (String) request.getAttribute("fsi_filtro");

        response.setContentType("image/gif");
        OutputStream Out = response.getOutputStream();

        JFsiGraficas graf;

        if (GRAF.equals("BAR"))
            graf = new JFsiGrafBarras(m_colL1, m_setL1,
                    m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro, enCols, linejes, tipo,
                    m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());
        else if (GRAF.equals("LIN"))
            graf = new JFsiGrafLineas(m_colL1, m_setL1,
                    m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro, enCols, linejes, tipo,
                    m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());
        else if (GRAF.equals("CIRC"))
            graf = new JFsiGrafCirc(m_colL1, m_setL1, m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro,
                    enCols, tipo, m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());
        else
            graf = new JFsiGrafAreas(m_colL1, m_setL1,
                    m_RepSet.getAbsRow(0).getDescription() + " " + fsi_filtro, enCols, linejes, tipo,
                    m_RepSet.getAbsRow(0).getHW(), m_RepSet.getAbsRow(0).getVW());

        try {
            new GifEncoder(graf.getGrafica(), Out).encode();
        } catch (IOException ioe) {
            System.out.println("Error en el GIF: " + ioe);
        }
    } else {
        String rep_permitido = "true";
        request.setAttribute("rep_permitido", rep_permitido);

        // Ahora pone los atributos para el jsp
        request.setAttribute("m_RepSet", m_RepSet);
        request.setAttribute("m_setL1", m_setL1);
        request.setAttribute("m_setCL1", m_setCL1);
        request.setAttribute("m_bSelectL1", m_bSelectL1);
        request.setAttribute("m_bSelectL2", m_bSelectL2);
        request.setAttribute("m_bSelectL3", m_bSelectL3);
        request.setAttribute("m_bComputeL1", m_bComputeL1);
        request.setAttribute("m_bComputeL2", m_bComputeL2);
        request.setAttribute("m_bComputeL3", m_bComputeL3);
        request.setAttribute("m_selectL1", m_selectL1);
        request.setAttribute("m_selectL2", m_selectL2);
        request.setAttribute("m_selectL3", m_selectL3);
        request.setAttribute("m_computeL1", m_computeL1);
        request.setAttribute("m_computeL2", m_computeL2);
        request.setAttribute("m_computeL3", m_computeL3);
        request.setAttribute("m_colL1", m_colL1);
        request.setAttribute("m_colL2", m_colL2);
        request.setAttribute("m_colL3", m_colL3);
        request.setAttribute("m_colCL1", m_colCL1);
        request.setAttribute("m_colCL2", m_colCL2);
        request.setAttribute("m_colCL3", m_colCL3);

        if (request.getParameter("exportacion").equals("html")) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.print(generarReporteHtml(request, response));
        } else if (request.getParameter("exportacion").equals("odt")) {
            response.setContentType("application/vnd.oasis.opendocument.text");
            PrintWriter out = response.getWriter();
            out.print(generarReporteHtml(request, response));
        } else if (request.getParameter("exportacion").equals("doc")) {
            response.setContentType("application/msword");
            PrintWriter out = response.getWriter();
            out.print(generarReporteHtml(request, response));
        } else if (request.getParameter("exportacion").equals("rtf")) {
            response.setContentType("application/rtf");
            PrintWriter out = response.getWriter();
            out.print(generarReporteHtml(request, response));
        } else if (request.getParameter("exportacion").equals("xls")) {
            response.setContentType("application/vnd.ms-excel");
            OutputStream Out = response.getOutputStream();
            Workbook wb = new HSSFWorkbook();
            generarArchivoXLS(request, response, wb);
            wb.write(Out);
            Out.close();
        } else if (request.getParameter("exportacion").equals("ods")) {
            response.setContentType("application/vnd.oasis.opendocument.spreadsheet");
            OutputStream Out = response.getOutputStream();
            Workbook wb = new HSSFWorkbook();
            generarArchivoXLS(request, response, wb);
            wb.write(Out);
            Out.close();
        } else if (request.getParameter("exportacion").equals("csv")) {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.print(generarArchivoCSV(request, response, "|"));
        } else if (request.getParameter("exportacion").equals("xml")) {
            Document document = new Document();
            response.setContentType("application/xml");
            PrintWriter out = response.getWriter();
            out.print(generarArchivoDOM(request, response, document));
        } else if (request.getParameter("exportacion").equals("pdf")) {
            response.setContentType("application/pdf");
            OutputStream Out = response.getOutputStream();
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(generarReporteHtml(request, response));
            renderer.layout();
            renderer.createPDF(Out);
        } else if (request.getParameter("exportacion").equals("sql")) {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.print(generarArchivoSQL(request, response));
        } else {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.print(generarReporteHtml(request, response));
        }

        //irApag("/forsetiadmin/reportes/rep_reportes_imp.jsp", request, response); 
    }
}

From source file:ga_assignment.GeneticAlgorithm.java

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

    GeneticAlgorithm ga = new GeneticAlgorithm();

    // Reads in training set
    Rule[] rules;//from w  w w .jav  a2  s .  co m
    rules = new Rule[32];
    Scanner inin = new Scanner(new FileReader("data1.txt"));
    for (int x = 0; x < 32; x++) {
        Rule rule = new Rule();
        rule.setCondition(inin.next());
        rule.setOutput(inin.nextInt());
        rules[x] = rule;
    }

    //set up export to excel
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("sheet");
    Row row = sheet.createRow((short) 0);
    row.createCell(0).setCellValue(wb.getCreationHelper().createRichTextString("Generations"));
    row.createCell(1).setCellValue(wb.getCreationHelper().createRichTextString("Best Fitness"));
    row.createCell(2).setCellValue(wb.getCreationHelper().createRichTextString("Mean Fitness"));
    int rowNumber = 1;

    Random rand = new Random();
    Individual in = new Individual();
    FitnessCalculator fit = new FitnessCalculator();

    ArrayList<Individual> population = new ArrayList<>();
    ArrayList<Individual> offspring = new ArrayList<>();

    int i;
    int j;
    int[] gene;
    gene = new int[ga.N];
    int tempFitness = 0;
    int totalFitness = 0;

    int optimalFitness = (ga.N / 6) * ga.P;
    System.out.println("OPTIMAL FITNESS = " + optimalFitness);

    //
    //
    //
    //
    //
    //
    // ======================================= INITIALISATION =======================================
    for (i = 0; i < ga.P; i++) { // for i is less than the population limit
        tempFitness = 0;

        for (j = 0; j < ga.N; j++) { // for j is less than the number of genes in an individual
            gene[j] = rand.nextInt(2) % 2; // population[individual] gets genes (10010) set
        } // repeat until 5 individuals have 5 genes

        // converts gene to string
        String geno = "";
        for (int a : gene) {
            geno += Integer.toString(a);
        }

        // creates a new individual
        Individual ind = new Individual();
        ind.setGene(geno);
        ind.setFitness(tempFitness);
        population.add(ind);
    }

    // gets total fitness of original population
    for (Individual fitt : population) {
        fit.fitnessCalculator(fitt, rules);
        totalFitness = fitt.getFitness() + totalFitness;
        System.out.println("gene = " + fitt.getGene() + " fit = " + fitt.getFitness());
    }
    System.out.println("Initial Total Fitness = " + totalFitness + "\n");

    //
    //
    //
    //
    //
    //
    // ======================================= PARENT SELECTION =======================================
    // 
    for (j = 0; j < ga.G; j++) {
        if (totalFitness < 500000) {
            totalFitness = 0;

            // Loop through Population
            for (i = 0; i < ga.P; i++) {

                Individual winner1;

                // chooses X individuals at random     
                Individual parent1 = population.get(new Random().nextInt(population.size()));
                Individual parent2 = population.get(new Random().nextInt(population.size()));

                // compares parents based on fitness
                if (parent1.getFitness() >= parent2.getFitness()) {
                    winner1 = parent1;
                } else {
                    winner1 = parent2;
                }

                offspring.add(winner1);

            }

            //
            //
            //
            //
            //
            //
            // ======================================= CROSSOVER / MUTATION =======================================
            for (i = 0; i < ga.P; i++) {

                // get random bit from individual
                int pos1 = new Random().nextInt(offspring.size());
                Individual child1 = offspring.get(pos1);

                int pos2 = new Random().nextInt(offspring.size());
                Individual child2 = offspring.get(pos2);

                // Crossover between two individuals
                in.Crossover(child1, child2);

                // Mutation of individual 1
                String ds = child1.getGene();
                Individual c1 = new Individual();
                c1.setGene(ds);
                in.Mutator(c1, pos1);
                offspring.remove(pos1);
                offspring.add(c1);

                // Calculate fitness of both individuals
                fit.fitnessCalculator(c1, rules);

            }

            //
            //
            //
            //
            //
            //
            // ======================================= RESET POPULATION =======================================

            // calculates offspring's total fitness
            for (Individual fitt : offspring) {
                totalFitness = fitt.getFitness() + totalFitness;
            }

            // REMOVE WORST AND ADD BEST
            // finds best fitness from population
            Individual best = in;
            int bestFitness = 0;
            for (Individual ind : population) {
                if (ind.getFitness() > bestFitness) {
                    bestFitness = ind.getFitness();
                    best = ind;
                }
            }

            // finds the worst fitness
            String p = "d";
            int low = 0;
            int worstFitness = 33;
            // find lowest fitness in offspring 
            for (int lo = 0; lo < offspring.size(); lo++) {
                if (offspring.get(lo).getFitness() < worstFitness) {
                    worstFitness = offspring.get(lo).getFitness();
                    p = offspring.get(lo).getGene();
                    low = lo;
                }
            }
            System.out.println("Lowest Fitness " + worstFitness);

            // Replace worst fitness with best from parent population
            offspring.remove(low);
            offspring.add(best);

            // Find the best individual in the offspring
            bestFitness = 0;
            for (Individual ind : offspring) {
                if (ind.getFitness() > bestFitness) {
                    bestFitness = ind.getFitness();
                    p = ind.gene;
                }
            }

            // Calculate the mean fitness
            int meanFitness = 0;
            meanFitness = totalFitness / ga.P;

            System.out.println("Best Individual: " + p + " f: " + bestFitness);
            System.out.println("Total Offspring Fitness: " + totalFitness + " Mean: " + meanFitness + " (Run "
                    + (j + 1) + ")\n");

            //export to excel
            Row row1 = sheet.createRow((short) rowNumber);
            row1.createCell(0).setCellValue((j + 1));
            row1.createCell(1).setCellValue(bestFitness);
            row1.createCell(2).setCellValue(meanFitness);
            rowNumber++;

            population.clear();

            //Move offspring into population
            for (int a = 0; a < offspring.size(); a++) {
                Individual transfer = offspring.get(a);
                population.add(transfer);
            }

            //Clear offspring
            offspring.clear();

        } else {
            for (Individual fitt : population) {

                System.out.println("gene = " + fitt.getGene() + " fit = " + fitt.getFitness());
            }

            //export to excel
            FileOutputStream fileOut = new FileOutputStream("GA_Results.xls");
            wb.write(fileOut);
            fileOut.close();

            System.out.println("\nComplete");
            System.exit(0);
        }
    }

    //export to excel
    FileOutputStream fileOut = new FileOutputStream("GA_Results.xls");
    wb.write(fileOut);
    fileOut.close();

}

From source file:GeMSE.IO.Exporter.java

License:Open Source License

private void ExportToExcelWorkbook(File file) {
    Workbook wb = new HSSFWorkbook();

    try {/*w  w w .j  a v a 2s.c  om*/
        try (FileOutputStream fileOut = new FileOutputStream(file)) {
            Sheet sheet = wb.createSheet("GeMSE_sheet");

            //Create 2D Cell Array
            Row[] row = new Row[_data.length];
            Cell[][] cell = new Cell[row.length][];

            for (int i = 0; i < row.length; i++) {
                row[i] = sheet.createRow(i);
                cell[i] = new Cell[_data[i].length];

                for (int j = 0; j < cell[i].length; j++) {
                    cell[i][j] = row[i].createCell(j);
                    cell[i][j].setCellValue(_data[i][j]);
                }
            }

            wb.write(fileOut);
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Exporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Exporter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:generate.XGenerator.java

public static void doCreateBook(Workbook my_workbook, String filename) throws IOException, Exception {
    dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date());
    filename = filename + "_" + dateFormat;
    String filepath = dirpath() + filename + EXCEL_EXT;
    FileOutputStream outputStream = new FileOutputStream(filepath);
    my_workbook.write(outputStream);
    if (!dirExists(filepath)) {
        MyLogging.log(Level.SEVERE, " Excel file " + filepath + " was not built.");
    } else {//from  www.j a v a  2  s.c  o  m
        MyLogging.log(Level.INFO, filepath + " build successfully.");
    }
    outputStream.close();

    PROPERTY_SET.put("filepath", filepath);
    PROPERTY_SET.put("filename", filename);
}