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

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

Introduction

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

Prototype

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

Source Link

Document

Write out this document to an Outputstream.

Usage

From source file:forme.FrmPocetna.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();/*from  w w  w.  j av  a2s .  c o  m*/

    TreeMap<String, Object[]> data = new TreeMap<>();
    TblModelPrikazUcinaka dtm = (TblModelPrikazUcinaka) jtblUcinci.getModel();

    Object[] array = new Object[dtm.getColumnCount()];
    for (int i = 0; i < dtm.getColumnCount(); i++) {
        array[i] = dtm.getColumnName(i);
    }
    data.put("0", array);

    for (int i = 0; i < dtm.getRowCount(); i++) {
        Object[] niz = new Object[dtm.getColumnCount()];
        for (int j = 0; j < dtm.getColumnCount(); j++) {
            niz[j] = dtm.getValueAt(i, j);
        }
        int rb = i + 1;
        data.put("" + rb, niz);
    }

    Set<String> ids = data.keySet();
    XSSFRow row;
    int rowID = 0;

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

        Object[] values = data.get(key);
        int cellID = 0;
        for (Object o : values) {
            Cell cell = row.createCell(cellID++);
            cell.setCellValue(o.toString());
        }

    }

    try {
        FileOutputStream out = new FileOutputStream(new File("../Export/"
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDomacin().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getGost().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDatumOdigravanja().toString() + ".xlsx"));
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FrmPocetna.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FrmPocetna.class.getName()).log(Level.SEVERE, null, ex);
    }

    JOptionPane.showMessageDialog(this, "Excel fajl uspeno sa?uvan na vaem kompjuteru!",
            "Preuzimanje dovreno", JOptionPane.INFORMATION_MESSAGE);
    try {
        Runtime.getRuntime().exec("cmd.exe /C start ../Export/"
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDomacin().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getGost().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDatumOdigravanja().toString() + ".xlsx");
        System.out.println("Otvorio");
    } catch (IOException ex) {
        Logger.getLogger(FrmPocetna.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fr.paris.lutece.plugins.appointment.service.AppointmentUtilities.java

License:Open Source License

/**
 * Build the excel fil of the list of the appointments found in the manage appointment viw by filter
 * //from  w w  w .j a v a 2 s  .c o m
 * @param strIdForm
 *            the form id
 * @param response
 *            the response
 * @param locale
 *            the local
 * @param listAppointmentsDTO
 *            the list of the appointments to input in the excel file
 * @param stateService
 *            the state service
 */
public static void buildExcelFileWithAppointments(String strIdForm, HttpServletResponse response, Locale locale,
        List<AppointmentDTO> listAppointmentsDTO, StateService stateService) {
    AppointmentFormDTO tmpForm = FormService.buildAppointmentFormLight(Integer.parseInt(strIdForm));
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet(I18nService.getLocalizedString(KEY_RESOURCE_TYPE, locale));
    List<Object[]> tmpObj = new ArrayList<Object[]>();
    EntryFilter entryFilter = new EntryFilter();
    entryFilter.setIdResource(Integer.valueOf(strIdForm));
    List<Entry> listEntry = EntryHome.getEntryList(entryFilter);
    Map<Integer, String> mapDefaultValueGenAttBackOffice = new HashMap<Integer, String>();
    for (Entry e : listEntry) {
        if (e.isOnlyDisplayInBack()) {
            e = EntryHome.findByPrimaryKey(e.getIdEntry());
            if (e.getFields() != null && e.getFields().size() == 1
                    && !StringUtils.isEmpty(e.getFields().get(0).getValue())) {
                mapDefaultValueGenAttBackOffice.put(e.getIdEntry(), e.getFields().get(0).getValue());
            } else if (e.getFields() != null) {
                for (Field field : e.getFields()) {
                    if (field.isDefaultValue()) {
                        mapDefaultValueGenAttBackOffice.put(e.getIdEntry(), field.getValue());
                    }
                }
            }
        }
    }
    int nTaille = 10 + (listEntry.size() + 1);
    if (tmpForm != null) {
        int nIndex = 0;
        Object[] strWriter = new String[1];
        strWriter[0] = tmpForm.getTitle();
        tmpObj.add(strWriter);
        Object[] strInfos = new String[nTaille];
        strInfos[0] = I18nService.getLocalizedString(KEY_COLUMN_LAST_NAME, locale);
        strInfos[1] = I18nService.getLocalizedString(KEY_COLUMN_FISRT_NAME, locale);
        strInfos[2] = I18nService.getLocalizedString(KEY_COLUMN_EMAIL, locale);
        strInfos[3] = I18nService.getLocalizedString(KEY_COLUMN_DATE_APPOINTMENT, locale);
        strInfos[4] = I18nService.getLocalizedString(KEY_TIME_START, locale);
        strInfos[5] = I18nService.getLocalizedString(KEY_TIME_END, locale);
        strInfos[6] = I18nService.getLocalizedString(KEY_COLUMN_ADMIN, locale);
        strInfos[7] = I18nService.getLocalizedString(KEY_COLUMN_STATUS, locale);
        strInfos[8] = I18nService.getLocalizedString(KEY_COLUMN_STATE, locale);
        strInfos[9] = I18nService.getLocalizedString(KEY_COLUMN_NB_BOOKED_SEATS, locale);
        nIndex = 1;
        if (listEntry.size() > 0) {
            for (Entry e : listEntry) {
                strInfos[10 + nIndex] = e.getTitle();
                nIndex++;
            }
        }
        tmpObj.add(strInfos);
    }
    if (listAppointmentsDTO != null) {
        for (AppointmentDTO appointmentDTO : listAppointmentsDTO) {
            int nIndex = 0;
            Object[] strWriter = new String[nTaille];
            strWriter[0] = appointmentDTO.getLastName();
            strWriter[1] = appointmentDTO.getFirstName();
            strWriter[2] = appointmentDTO.getEmail();
            strWriter[3] = appointmentDTO.getDateOfTheAppointment();
            strWriter[4] = appointmentDTO.getStartingTime().toString();
            strWriter[5] = appointmentDTO.getEndingTime().toString();
            strWriter[6] = appointmentDTO.getAdminUser();
            String status = I18nService.getLocalizedString(AppointmentDTO.PROPERTY_APPOINTMENT_STATUS_RESERVED,
                    locale);
            if (appointmentDTO.getIsCancelled()) {
                status = I18nService.getLocalizedString(AppointmentDTO.PROPERTY_APPOINTMENT_STATUS_UNRESERVED,
                        locale);
            }
            strWriter[7] = status;
            State stateAppointment = stateService.findByResource(appointmentDTO.getIdAppointment(),
                    Appointment.APPOINTMENT_RESOURCE_TYPE, tmpForm.getIdWorkflow());
            String strState = StringUtils.EMPTY;
            if (stateAppointment != null) {
                appointmentDTO.setState(stateAppointment);
                strState = stateAppointment.getName();
            }
            strWriter[8] = strState;
            nIndex = 1;
            strWriter[9] = Integer.toString(appointmentDTO.getNbBookedSeats());
            List<Integer> listIdResponse = AppointmentResponseService
                    .findListIdResponse(appointmentDTO.getIdAppointment());
            List<Response> listResponses = new ArrayList<Response>();
            for (int nIdResponse : listIdResponse) {
                Response resp = ResponseHome.findByPrimaryKey(nIdResponse);
                if (resp != null) {
                    listResponses.add(resp);
                }
            }
            for (Entry e : listEntry) {
                Integer key = e.getIdEntry();
                StringBuffer strValue = new StringBuffer(StringUtils.EMPTY);
                String strPrefix = StringUtils.EMPTY;
                for (Response resp : listResponses) {
                    String strRes = StringUtils.EMPTY;
                    if (key.equals(resp.getEntry().getIdEntry())) {
                        Field f = resp.getField();
                        int nfield = 0;
                        if (f != null) {
                            nfield = f.getIdField();
                            Field field = FieldHome.findByPrimaryKey(nfield);
                            if (field != null) {
                                strRes = field.getTitle();
                            }
                        } else {
                            strRes = resp.getResponseValue();
                        }
                    }
                    if ((strRes != null) && !strRes.isEmpty()) {
                        strValue.append(strPrefix + strRes);
                        strPrefix = CONSTANT_COMMA;
                    }
                }
                if (strValue.toString().isEmpty() && mapDefaultValueGenAttBackOffice.containsKey(key)) {
                    strValue.append(mapDefaultValueGenAttBackOffice.get(key));
                }
                if (!strValue.toString().isEmpty()) {
                    strWriter[10 + nIndex] = strValue.toString();
                }
                nIndex++;
            }
            tmpObj.add(strWriter);
        }
    }
    int nRownum = 0;
    for (Object[] myObj : tmpObj) {
        Row row = sheet.createRow(nRownum++);
        int nCellnum = 0;
        for (Object strLine : myObj) {
            Cell cell = row.createCell(nCellnum++);
            if (strLine instanceof String) {
                cell.setCellValue((String) strLine);
            } else if (strLine instanceof Boolean) {
                cell.setCellValue((Boolean) strLine);
            } else if (strLine instanceof Date) {
                cell.setCellValue((Date) strLine);
            } else if (strLine instanceof Double) {
                cell.setCellValue((Double) strLine);
            }
        }
    }
    try {
        String now = new SimpleDateFormat("yyyyMMdd-hhmm")
                .format(GregorianCalendar.getInstance(locale).getTime()) + "_"
                + I18nService.getLocalizedString(KEY_RESOURCE_TYPE, locale) + EXCEL_FILE_EXTENSION;
        response.setContentType(EXCEL_MIME_TYPE);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + now + "\";");
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate,post-check=0,pre-check=0");
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.close();
        workbook.close();
    } catch (IOException e) {
        AppLogService.error(e);
    }
}

From source file:GapAnalysis.gapAnalysis.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //PrintWriter out = response.getWriter();
    try {/*  w  w  w  .ja va2 s. co  m*/

        ArrayList keyal = new ArrayList();
        ArrayList countyal = new ArrayList();
        ArrayList scountyal = new ArrayList();
        ArrayList facilal = new ArrayList();
        ArrayList yearmonthal = new ArrayList();
        ArrayList monthal = new ArrayList();
        ArrayList sectional = new ArrayList();

        XSSFWorkbook wb;

        String periodname = "";
        String allpath = getServletContext().getRealPath("/Gapanalysis.xlsm");

        System.out.println(allpath);

        XSSFWorkbook workbook;
        String mydrive = allpath.substring(0, 1);
        // wb = new XSSFWorkbook( OPCPackage.open(allpath) );

        Date da = new Date();
        String dat2 = da.toString().replace(" ", "_");
        dat2 = dat2.toString().replace(":", "_");

        String np = mydrive + ":\\APHIAPLUS\\InternalSystem\\Gapanalysis" + dat2 + ".xlsm";
        System.out.println("path:: " + np);
        // String desteepath1 = getServletContext().getRealPath("/Females 15to24.xlsm");
        String sr = getServletContext().getRealPath("/Gapanalysis.xlsm");
        //check if file exists

        //first time , it should create those folders that host the macro file
        File f = new File(np);
        if (!f.exists() && !f.isDirectory()) { /* do something */
            copytemplates ct = new copytemplates();
            ct.transfermacros(sr, np);
            //rem np is the destination file name  

            System.out.println("Copying macro template first time ..");

        } else
        //copy the file alone  
        {
            copytemplates ct = new copytemplates();
            //copy the agebased file only
            ct.copymacros(sr, np);

        }
        String filepth = np;

        File allpathfile = new File(filepth);

        OPCPackage pkg = OPCPackage.open(allpathfile);

        pathtodelete = filepth;
        wb = new XSSFWorkbook(pkg);

        dbConn conn = new dbConn();
        HashMap<String, String> rawdatahashmap = new HashMap<String, String>();

        int year = 0;
        String yearval = "";
        int prevyear = 0;

        String quarter = "";

        String yearmonth = "";
        String startyearmonth = "";
        String endyearmonth = "";

        yearval = request.getParameter("year").toString();

        System.out.println("YEARVAL" + yearval);
        year = Integer.parseInt(yearval);
        prevyear = year - 1;
        quarter = request.getParameter("quarter");
        periodname += yearval + "_";
        if (quarter.equals("1")) {
            startyearmonth = prevyear + "10";
            endyearmonth = prevyear + "12";
            periodname = prevyear + "_(Oct_Dec)";
        } else if (quarter.equals("2")) {
            startyearmonth = year + "01";
            endyearmonth = year + "03";
            periodname = yearval + "_(Jan-Mar)";
        } else if (quarter.equals("3")) {
            startyearmonth = year + "04";
            endyearmonth = year + "06";
            periodname = yearval + "_(Apr_Jun)";
        } else if (quarter.equals("4")) {
            startyearmonth = year + "07";
            endyearmonth = year + "09";
            periodname = yearval + "_(Jul_Sep)";
        }

        int colsmerging = 6;
        String Sections[] = { "ART", "HTC", "PMTCT" };
        String headers[] = { "County", "Sub-County", "Facility", "Year", "Month" };
        String headergsn[] = { "County", "Sub-County", "Facility" };
        //if one wants gaps for one service area
        if (request.getParameterValues("gapsection") != null) {

            Sections = request.getParameterValues("gapsection");

        }
        //This is the loop that well use to create worksheets for each 

        String period = " 1=1 and Annee=" + yearval + " and yearmonth between " + startyearmonth + " and "
                + endyearmonth + " ";
        String gsnperiod = " 1=1  ";

        //______________________________________________________________________________________
        //______________________________________________________________________________________

        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("Cambria");
        font.setColor((short) 0000);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font font2 = wb.createFont();
        font2.setFontName("Cambria");
        font2.setColor((short) 0000);
        CellStyle style2 = wb.createCellStyle();
        style2.setFont(font2);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        CellStyle stborder = wb.createCellStyle();
        stborder.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stborder.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        CellStyle stylex = wb.createCellStyle();
        stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        CellStyle stylex1 = wb.createCellStyle();
        stylex1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        stylex1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex1.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        CellStyle stylex2 = wb.createCellStyle();
        stylex2.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        stylex2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        CellStyle stylex3 = wb.createCellStyle();
        stylex3.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        stylex3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        stylex3.setBorderTop(HSSFCellStyle.BORDER_THIN);
        stylex3.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        stylex3.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        stylex3.setBorderRight(HSSFCellStyle.BORDER_THIN);
        stylex3.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        Font fontx = wb.createFont();
        fontx.setColor(HSSFColor.BLACK.index);
        fontx.setFontName("Cambria");
        stylex.setFont(fontx);
        stylex.setWrapText(true);
        stylex1.setFont(fontx);
        stylex1.setWrapText(true);

        stylex2.setFont(fontx);
        stylex2.setWrapText(true);

        //==================================================

        for (int a = 0; a < Sections.length; a++) {
            int column = 0;
            int Row = 3;

            Sheet shet = wb.createSheet(Sections[a]);

            Row rwx = shet.createRow(2);
            Row rw1 = null;
            Row rw2 = null;
            Row rw = shet.createRow(0);
            rw.setHeightInPoints(25);
            Cell cl0 = rw.createCell(0);
            cl0.setCellValue(Sections[a] + " GAP ANALYSIS");
            cl0.setCellStyle(stylex1);

            //this will depend on the length of the number of elements being checked

            for (int b = 1; b <= colsmerging; b++) {
                Cell clx = rw.createCell(b);
                clx.setCellValue("");
                clx.setCellStyle(stylex);
            }

            //now go to the database and do a query for each section
            int determinant = 2;
            String getqueries = " Select * from gap_analysis where active=1 and section='" + Sections[a] + "' ";

            conn.rs = conn.st.executeQuery(getqueries);
            while (conn.rs.next()) {

                //if an excel sheet exists, then get the row number 1

                if (shet.getRow(1) != null) {
                    rw1 = shet.getRow(1);
                } else {
                    rw1 = shet.createRow(1);
                    rw1.setHeightInPoints(25);
                }

                //print blanks before printing real header
                //for gsns, we only print three columns and no period
                if (conn.rs.getString("id").equals("1")) {

                    for (int p = 0; p < headergsn.length; p++) {
                        Cell cl2 = rw1.createCell(column + p);
                        cl2.setCellValue("");
                        cl2.setCellStyle(stylex);
                        shet.setColumnWidth(column + p, 5000);
                    }
                } else {

                    for (int p = 0; p < headers.length; p++) {
                        Cell cl2 = rw1.createCell(column + p);
                        cl2.setCellValue("");
                        cl2.setCellStyle(stylex);
                        shet.setColumnWidth(column + p, 5000);
                    }

                }
                determinant++;
                if (determinant % 2 == 0) {

                    Cell cl1 = rw1.createCell(column);
                    cl1.setCellValue(conn.rs.getString("rule"));
                    cl1.setCellStyle(stylex3);

                } else {

                    Cell cl1 = rw1.createCell(column);
                    cl1.setCellValue(conn.rs.getString("rule"));
                    cl1.setCellStyle(stylex2);

                }

                //Create the column header  

                if (shet.getRow(2) != null) {
                    rw2 = shet.getRow(2);
                } else {
                    rw2 = shet.createRow(2);
                    rw2.setHeightInPoints(25);
                }
                if (conn.rs.getString("id").equals("1")) {

                    for (int p = 0; p < headergsn.length; p++) {
                        Cell cl2 = rw2.createCell(column + p);
                        cl2.setCellValue(headergsn[p]);
                        cl2.setCellStyle(stylex);
                    }
                } else {

                    for (int p = 0; p < headers.length; p++) {
                        Cell cl2 = rw2.createCell(column + p);
                        cl2.setCellValue(headers[p]);
                        cl2.setCellStyle(stylex);
                    }

                }

                String currentqry = conn.rs.getString("query");
                //process each query as you 
                //pass the necessary period parameters from the interface
                //rem each query ends with a 'and'
                if (conn.rs.getString("id").equals("1")) {
                    currentqry += gsnperiod;
                } else {

                    currentqry += period + " and subpartnera." + Sections[a] + "= 1 ";

                }

                System.out.println("" + currentqry);
                Row = 3;
                conn.rs1 = conn.st1.executeQuery(currentqry);

                while (conn.rs1.next()) {

                    if (shet.getRow(Row) != null) {
                        rwx = shet.getRow(Row);
                    } else {
                        rwx = shet.createRow(Row);
                        rwx.setHeightInPoints(25);
                    }
                    Cell cly = rwx.createCell(column);
                    cly.setCellValue(conn.rs1.getString("County"));
                    cly.setCellStyle(style2);

                    Cell cly2 = rwx.createCell(column + 1);
                    cly2.setCellValue(conn.rs1.getString("DistrictNom"));
                    cly2.setCellStyle(style2);//gsn sites do not have a yearmonth

                    Cell cly1 = rwx.createCell(column + 2);
                    cly1.setCellValue(conn.rs1.getString("SubPartnerNom"));
                    cly1.setCellStyle(style2);

                    //if the current list is not inclusive of GSNs

                    if (!conn.rs.getString(1).equals("1")) {

                        Cell cly3 = rwx.createCell(column + 3);
                        cly3.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(0, 4)));
                        cly3.setCellStyle(style2);

                        //the month section

                        Cell cly3x = rwx.createCell(column + 4);
                        cly3x.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(4)));
                        cly3x.setCellStyle(style2);

                        //my key is a 
                        String mykey = Sections[a] + conn.rs1.getString("SubPartnerNom") + "_"
                                + conn.rs1.getString("yearmonth") + "_";
                        //add all the facilities at this point
                        //ignore the sites in ART since they are static
                        if (!keyal.contains(mykey)) {
                            keyal.add(mykey);
                            countyal.add(conn.rs1.getString("County"));
                            scountyal.add(conn.rs1.getString("DistrictNom"));
                            facilal.add(conn.rs1.getString("SubPartnerNom"));
                            sectional.add(Sections[a]);
                            yearmonthal.add(conn.rs1.getString("yearmonth"));
                            monthal.add(conn.rs1.getString("yearmonth").substring(4));

                        }

                    }

                    Row++;

                }

                if (conn.rs.getString(1).equals("1")) {
                    column += 3;
                } else {
                    column += 5;
                }
                if (conn.rs.getString("id").equals("1")) {
                    shet.addMergedRegion(new CellRangeAddress(1, 1, 0, column - 1));
                } else {
                    shet.addMergedRegion(new CellRangeAddress(1, 1, column - 5, column - 1));
                }

            } //end of all queries per section

            shet.addMergedRegion(new CellRangeAddress(0, 0, 0, column - 1));

        } // end of sheets loop   

        //create a new sheet

        //county   subcounty   facility   yearmonth   section

        Sheet shet = wb.getSheet("Sheet1");

        Row rw = shet.createRow(0);
        Cell cl0 = rw.createCell(0);
        cl0.setCellValue("county");
        cl0.setCellStyle(stylex1);

        Cell cl1 = rw.createCell(1);
        cl1.setCellValue("subcounty");
        cl1.setCellStyle(stylex1);

        Cell cl2 = rw.createCell(2);
        cl2.setCellValue("facility");
        cl2.setCellStyle(stylex1);

        Cell cl3 = rw.createCell(3);
        cl3.setCellValue("year");
        cl3.setCellStyle(stylex1);

        Cell cl4 = rw.createCell(4);
        cl4.setCellValue("month");
        cl4.setCellStyle(stylex1);

        Cell cl5 = rw.createCell(5);
        cl5.setCellValue("section");
        cl5.setCellStyle(stylex1);

        for (int q = 0; q < keyal.size(); q++) {

            Row rwx = shet.createRow(q + 1);

            Cell cl01 = rwx.createCell(0);
            cl01.setCellValue(countyal.get(q).toString());
            cl01.setCellStyle(style2);

            Cell cl11 = rwx.createCell(1);
            cl11.setCellValue(scountyal.get(q).toString());
            cl11.setCellStyle(style2);

            Cell cl21 = rwx.createCell(2);
            cl21.setCellValue(facilal.get(q).toString());
            cl21.setCellStyle(style2);

            Cell cl31 = rwx.createCell(3);
            cl31.setCellValue(new Integer(yearmonthal.get(q).toString().substring(0, 4)));
            cl31.setCellStyle(style2);

            Cell cl41 = rwx.createCell(4);
            cl41.setCellValue(new Integer(monthal.get(q).toString()));
            cl41.setCellStyle(style2);

            Cell cl51 = rwx.createCell(5);
            cl51.setCellValue(sectional.get(q).toString());
            cl51.setCellStyle(style2);

        }

        IdGenerator IG = new IdGenerator();
        String createdOn = IG.CreatedOn();

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        wb.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition",
                "attachment; filename=GapAnalysis_For" + periodname + "_Generatted_On_" + createdOn + ".xlsm");
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        outStream.close();
        pkg.close();

        if (conn.rs != null) {
            conn.rs.close();
        }
        if (conn.rs1 != null) {
            conn.rs1.close();
        }
        if (conn.st1 != null) {
            conn.st1.close();
        }
        if (conn.st != null) {
            conn.st.close();
        }

        File file = new File(pathtodelete);
        System.out.println("path: 2" + pathtodelete);

        if (file.delete()) {
            System.out.println(file.getName() + " is deleted!");
        } else {
            System.out.println("Delete operation  failed.");
        }

    } catch (SQLException ex) {
        Logger.getLogger(gapAnalysis.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(gapAnalysis.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

    }
}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixEngine.java

License:Open Source License

/**
 * Write engine file./*  w w  w  .ja  va 2 s  . c  o  m*/
 *
 * @param fileName the file name
 * @return true, if successful
 */
public boolean writeEngineFile(String fileName) {

    // Check for errors.
    try {

        // Create the requested workbook image.
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Create the parameters sheet.
        XSSFSheet sheet = workbook.createSheet("Parameters");

        // Create the rows.
        this.createRowHeader(workbook, sheet, 0, "Parameter", "Value");
        this.createRowInt(sheet, 1, "Random Seed", this.randomSeed);
        this.createRowInt(sheet, 2, "Population Size", this.populationSize);
        this.createRowDouble(sheet, 3, "Kill Fraction", this.killFraction);
        this.createRowDouble(sheet, 4, "Crossover Probability", this.crossoverProbability);
        this.createRowDouble(sheet, 5, "Mutation Probability for Cells", this.mutationProbabilityForCells);

        // Attempt to create the requested file from the workbook image.
        FileOutputStream file = new FileOutputStream(fileName);
        workbook.write(file);
        file.close();

        // Catch errors.
    } catch (Exception e) {

        // Note the error.
        return false;

    }

    // Return the default results.
    return true;

}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java

License:Open Source License

/**
 * Write./*from   w w w  .  j a v  a2  s  . co  m*/
 *
 * @param fileName            the file name
 * @return true, if successful
 */
public boolean write(String fileName) {

    // Check for errors.
    try {

        // Create the requested workbook image.
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Create the needed highlight style.
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        cellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(197, 217, 241)));
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        XSSFFont font = workbook.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        cellStyle.setFont(font);

        // Fill in the fitness sheet.
        this.writeFitnessFunctionInformation(workbook, cellStyle);

        // Fill in the variables.
        this.writeScanVariables(workbook, cellStyle);

        // Attempt to create the requested file from the workbook image.
        FileOutputStream file = new FileOutputStream(fileName);
        workbook.write(file);
        file.close();

        // Catch errors.
    } catch (Exception e) {

        // Note the error.
        return false;

    }

    // Return the default results.
    return true;

}

From source file:gov.nih.nci.evs.app.neopl.CSVtoExcel.java

License:Open Source License

public void runXSSF(String inputfile) {
    int size = checkSpecialCharacters(inputfile);

    int n = inputfile.lastIndexOf(".");
    //String outputfile = inputfile.substring(0, n) + ".xlsx";
    String outputfile = getOutputFile(inputfile, ".xlsx");

    try {//from ww w  . j a  v a  2  s.c o m
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFCreationHelper helper = null;

        XSSFCellStyle cellStyle = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        cellStyle.setFont(font);

        XSSFCellStyle linkCellStyle = wb.createCellStyle();
        XSSFFont linkfont = wb.createFont();

        //XSSFColor color = new XSSFColor(Color.LIGHT_BLUE);
        XSSFColor color = new XSSFColor(Color.BLUE);
        linkfont.setColor(color);

        //linkfont.setColor(XSSFColor.LIGHT_BLUE.index);
        linkCellStyle.setFont(linkfont);
        CSVReader reader = new CSVReader(new FileReader(inputfile));//CSV file
        String[] line;
        int r = 0;
        Cell cell = null;

        XSSFHyperlink url_link = null;
        XSSFSheet sheet = null;

        int page_num = 1;
        Row row = null;
        int lcv = 0;
        int row_count = 0;

        try {

            while ((line = reader.readNext()) != null) {
                if (lcv % PAGE_SIZE == 0) {
                    r = 0;
                    String sheetLabel = SHEET_LABEL;
                    if (size > PAGE_SIZE) {
                        sheetLabel = sheetLabel + " (Page " + page_num + ")";
                    }
                    //System.out.println("Creating " + sheetLabel);
                    sheet = wb.createSheet(sheetLabel);
                    helper = sheet.getWorkbook().getCreationHelper();
                    url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);

                    row = sheet.createRow((short) r);
                    for (int i = 0; i < HEADINGS.length; i++) {
                        String heading = HEADINGS[i];
                        cell = row.createCell(i);
                        cell.setCellValue(heading);
                        cell.setCellStyle(cellStyle);
                    }
                    page_num++;

                } else {
                    String s4 = (String) line[4];
                    s4 = s4.trim();
                    r++;
                    row = sheet.createRow((short) r);
                    row_count++;
                    cell = row.createCell(0);
                    String ncit_code = line[0];
                    cell.setCellValue(ncit_code);
                    if (NCIT_LINK) {
                        url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                        url_link.setAddress(getNCItHyperlink(ncit_code));
                        cell.setHyperlink(url_link);
                        cell.setCellStyle(linkCellStyle);
                    }

                    cell = row.createCell(1);
                    String name = line[1];
                    cell.setCellValue(line[1]);

                    cell = row.createCell(2);
                    cell.setCellValue(line[2]);
                    if (NCIM_LINK) {
                        String s2 = line[2];
                        s2 = s2.trim();
                        if (s2.length() > 0) {
                            url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                            url_link.setAddress(getNCImHyperlink(s2));
                            cell.setHyperlink(url_link);
                            cell.setCellStyle(linkCellStyle);
                        }
                    }

                    cell = row.createCell(3);
                    String ncim_name = line[3];
                    cell.setCellValue(line[3]);

                    cell = row.createCell(4);
                    cell.setCellValue(line[4]);

                    cell = row.createCell(5);
                    String atom_name = (String) line[5];
                    cell.setCellValue(line[5]);

                    cell = row.createCell(6);
                    cell.setCellValue(line[6]);

                    if (SOURCE_LINK) {
                        if (s4.length() > 0) {
                            String s6 = (String) line[6];
                            if (localNameMap.containsKey(s4)) {
                                url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                                s4 = (String) localNameMap.get(s4);
                                url_link.setAddress(getSourceHyperlink(s4, s6));
                                cell.setHyperlink(url_link);
                                cell.setCellStyle(linkCellStyle);
                            }
                        }
                    }
                    cell = row.createCell(7);
                    cell.setCellValue(line[7]);
                }
                lcv++;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream(outputfile);
        wb.write(fileOut);
        fileOut.close();
        System.out.println("Output file " + outputfile + " generated.");
        System.out.println("row_count: " + row_count);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Group1.ReportServlet1.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // create the workbook, its worksheet, and its title row
    List<String[]> apppp = new LinkedList<String[]>();

    try {//from   ww w  .j a v a2  s  . c o  m
        // read database rowsgetConnection(
        Connection connection = DatabaseConnection.getConnection("toba", "root", "root");
        Statement statement = connection.createStatement();
        String query = "SELECT * FROM user ORDER BY Username";
        ResultSet results = statement.executeQuery(query);

        // create the spreadsheet rows
        int i = 3;
        while (results.next()) {
            String[] appp = new String[9];
            appp[0] = "" + results.getString("Username");
            appp[1] = "" + (results.getString("Firstname"));
            appp[2] = "" + (results.getString("Lastname"));
            appp[3] = "" + (results.getString("Phone"));
            appp[4] = "" + (results.getString("Address"));
            appp[5] = "" + (results.getString("City"));
            appp[6] = "" + (results.getString("State"));
            appp[7] = "" + (results.getString("Zipcode"));
            appp[8] = "" + (results.getString("Email"));
            apppp.add(appp);
        }
        results.close();
        statement.close();
        DatabaseConnection.closeConnection(connection);
    } catch (SQLException e) {
        e.printStackTrace();
        this.log(e.toString());
    }

    String[][] args = new String[apppp.size()][9];

    for (int i = 0; i < apppp.size(); i++) {
        args[i] = apppp.get(i);
    }

    String[] columnNames = new String[] { "User Name", "First Name", " Last Name", "Phone", "ADdress", "City",
            "State", "Zip Code", "Email" };

    XSSFWorkbook workbook = new XSSFWorkbook();

    //Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Employee Data");

    //This data needs to be written (Object[])
    int rownum = 0;
    Row row;
    Cell cell;
    int j = 0;
    row = sheet.createRow(0);

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

    for (int i = 0; i < args.length; i++) {
        row = sheet.createRow(i + 1);
        for (j = 0; j < args[0].length; j++) {
            cell = row.createCell(j);
            cell.setCellValue(args[i][j]);
        }
    }
    try {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("content-disposition", "attachment; filename=users.xlsx");
        response.setHeader("cache-control", "no-cache");
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.close();
        //Write the workbook in file system
        /*FileOutputStream out = new FileOutputStream(new File(filename));
        workbook.write(out);
        out.close();
        System.out.println(filename+ " written successfully on disk.");*/
    } catch (Exception e) {
        e.printStackTrace();
    }

    // set the response headers

    // get the output stream and send the workbook to the browser

}

From source file:hangargame.xml.AfficherListGamerAdminController.java

@FXML
void ExtraireExcel(ActionEvent event) throws FileNotFoundException, IOException {
    List<Gamer> l = new ArrayList();
    l = s.AfficherListeGamer();//from  ww w .j  ava2  s.co  m
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet spreadsheet = workbook.createSheet("Hangar Game");
    XSSFRow row = spreadsheet.createRow(1);
    XSSFCell cell;
    cell = row.createCell(1);
    cell.setCellValue("Login");
    cell = row.createCell(2);
    cell.setCellValue("Nom");
    cell = row.createCell(3);
    cell.setCellValue("Prenom");
    cell = row.createCell(4);
    cell.setCellValue("E-mail");
    cell = row.createCell(5);
    cell.setCellValue("Adresse");
    cell = row.createCell(6);
    cell.setCellValue("Tlphone");
    cell = row.createCell(7);
    cell.setCellValue("Data d'inscription");
    cell = row.createCell(8);
    cell.setCellValue("Etat");
    for (int i = 1; i < l.size() - 1; i++) {
        row = spreadsheet.createRow(i);
        cell = row.createCell(1);
        cell.setCellValue(l.get(i).getLogin());
        cell = row.createCell(2);
        cell.setCellValue(l.get(i).getNom());
        cell = row.createCell(3);
        cell.setCellValue(l.get(i).getPrenom());
        cell = row.createCell(4);
        cell.setCellValue(l.get(i).getEmail());
        cell = row.createCell(5);
        cell.setCellValue(l.get(i).getAdresse());
        cell = row.createCell(6);
        cell.setCellValue(l.get(i).getTel());
        cell = row.createCell(7);
        cell.setCellValue(l.get(i).getDateInscription());
        cell = row.createCell(8);
        cell.setCellValue(l.get(i).getEtat());

    }
    FileOutputStream out = new FileOutputStream(new File("exceldatabase.xlsx"));
    workbook.write(out);
    out.close();
    tray.notification.TrayNotification tr = new TrayNotification();
    tr.setTitle("Extraction faite avec succes");
    tr.setMessage("Tlechargement sous Document/netbeans/hangargame ");
    tr.setNotificationType(NotificationType.SUCCESS);
    tr.setAnimationType(AnimationType.SLIDE);
    tr.showAndDismiss(Duration.seconds(5));
}

From source file:hedicim.HEDICIM.java

static void exportResults(Set<Patient> patients) {
    SummaryReportWriter srw = new SummaryReportWriter(Const.OUTPUT_FOLDER + execution_label + " Summary.txt");
    srw.write("## Summary report for HEDICIM labeled: \"" + execution_label + "\" ##");
    srw.write("# LAB_TIME_WINDOW: " + Const.LAB_TIME_WINDOW);
    srw.write("# EARLY_DEATH_TIME_WINDOW: " + Const.EARLY_DEATH_TIME_WINDOW);
    srw.write("# IGNORE_DIC_IF_NEAR_DEATH: " + Const.IGNORE_DIC_IF_NEAR_DEATH);
    srw.write("# IGNORE_MEDICATION_IF_FAR_FROM_DIC: " + Const.IGNORE_MEDICATION_IF_FAR_FROM_DIC);
    srw.write("# debug_patient_number_limiter: " + Const.debug_patient_number_limiter);
    srw.write("# origin_ids_chunk_size: " + Const.processing_chunk_size);
    if (Const.do_MIMICII) {
        srw.write("# ICD9_queries.length: " + Const.ICD9_queries.length);
        for (int i = 0; i < Const.ICD9_queries.length; i++)
            srw.write("# > ICD9_queries[" + i + "]: " + Const.ICD9_queries[i]);
    }/*from  www.  ja  v a 2s . c o  m*/
    if (Const.do_BTRIS)
        srw.write("# BTRIS table queried: " + Const.BTRIS_TABLE);
    srw.write("Total patients processed: " + count_of_all_patients_processed);
    srw.write("Total non-neonates processed: " + count_of_non_neonates_processed);
    srw.write("Total eligible patients found: " + eligible_count);
    int eligible_dic_count = 0;
    for (Patient patient : patients)
        if (patient.eligible && patient.has_dic)
            eligible_dic_count++;
    srw.write("Total eligible patients with DIC found: " + eligible_dic_count);
    /*
    srw.write("LABEVENTS exceptions: " + msc.LABEVENTS_exceptions);
    srw.write("ADMISSIONS exceptions: " + msc.ADMISSIONS_exceptions);
    srw.write("ICUSTAY_DETAIL exceptions: " + msc.ICUSTAY_DETAIL_exceptions);
    srw.write("D_PATIENTS exceptions: " + msc.D_PATIENTS_exceptions);
    srw.write("POE_ORDER exceptions: " + msc.POE_ORDER_exceptions);
    srw.write("CHARTEVENTS exceptions: " + msc.CHARTEVENTS_exceptions);
    */
    srw.close();

    EnumMap<DICSS, EnumMap<DICSS, Long[]>> scorers_comparison_table_time = compareDICSSOverlappingTime(
            patients);
    EnumMap<DICSS, EnumMap<DICSS, Long[]>> scorers_comparison_table_cases = compareDICSSOverlappingCases(
            patients);
    EnumMap<DICSS, DICScore> score_structures = buildScoreStructures(patients);

    try (FileOutputStream file = new FileOutputStream(
            new File(Const.OUTPUT_FOLDER + execution_label + " DICSS comparison.xlsx"))) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("DIC SS Overlapping Periods of Time");
        int r = 0;
        Row row = sheet.createRow(r++);
        int c = 0;
        row.createCell(c++).setCellValue("Reference\\Comparison");
        for (DICSS dicss_reference : DICSS.values())
            row.createCell(c++).setCellValue(dicss_reference.name());
        row.createCell(c++).setCellValue("Total reference time (weeks)");
        for (DICSS dicss_reference : DICSS.values()) {
            row = sheet.createRow(r++);
            c = 0;
            row.createCell(c++).setCellValue(dicss_reference.name());
            for (DICSS dicss_comparison : DICSS.values())
                row.createCell(c++)
                        .setCellValue(String.format("%.1f",
                                100d * ((double) (scorers_comparison_table_time.get(dicss_reference)
                                        .get(dicss_comparison)[0]))
                                        / ((double) (scorers_comparison_table_time.get(dicss_reference)
                                                .get(dicss_comparison)[1])))
                                + "%");
            row.createCell(c++).setCellValue(String.format("%.1f", 100d
                    * ((double) (scorers_comparison_table_time.get(dicss_reference).get(dicss_reference)[1]))
                    / (1000d * 60d * 60d * 24d * 7d)));
        }

        sheet = workbook.createSheet("DIC SS Overlapping Cases");
        r = 0;
        row = sheet.createRow(r++);
        c = 0;
        row.createCell(c++).setCellValue("Reference\\Comparison");
        for (DICSS dicss_reference : DICSS.values())
            row.createCell(c++).setCellValue(dicss_reference.name());
        for (DICSS dicss_reference : DICSS.values()) {
            row = sheet.createRow(r++);
            c = 0;
            row.createCell(c++).setCellValue(dicss_reference.name());
            for (DICSS dicss_comparison : DICSS.values())
                row.createCell(c++)
                        .setCellValue(String.format("%.1f",
                                100d * ((double) (scorers_comparison_table_cases.get(dicss_reference)
                                        .get(dicss_comparison)[0]))
                                        / ((double) (scorers_comparison_table_cases.get(dicss_reference)
                                                .get(dicss_comparison)[1])))
                                + "%");
        }

        for (DICSS dicss : DICSS.values()) {
            sheet = workbook.createSheet(dicss.name() + " score structure");
            r = 0;
            row = sheet.createRow(r++);
            c = 0;
            DICScore dic_score = score_structures.get(dicss);
            if (dic_score.itemids.isEmpty()) {
                row.createCell(c++).setCellValue("Empty.");
                continue;
            }
            row.createCell(c++).setCellValue("ITEMID");
            row.createCell(c++).setCellValue("Contribution to score (%)");
            for (ITEMID itemid : dic_score.itemids.keySet()) {
                row = sheet.createRow(r++);
                c = 0;
                row.createCell(c++).setCellValue(itemid.name());
                row.createCell(c++).setCellValue(100d * dic_score.itemids.get(itemid));
            }
            row = sheet.createRow(r++);
            c = 0;
            row.createCell(c++).setCellValue("Average score");
            row.createCell(c++).setCellValue(dic_score.score);
        }

        workbook.write(file);
        file.close();
    } catch (Exception ex) {
        System.out.print("Unable to open " + Const.OUTPUT_FOLDER + execution_label + " DICSS comparison.xlsx"
                + " for writing:\n" + ex.getMessage());
    }

}

From source file:ik1004labb5.DAOHundExcel.java

private void saveToExcel(XSSFWorkbook workbook) {
    try {/*from www.ja va 2 s. c o m*/
        //Skriv ver innehllet till filen och stng strmmen
        FileOutputStream outputstr = new FileOutputStream(new File("hundar.xlsx"));
        workbook.write(outputstr);
        outputstr.close();

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