Example usage for org.apache.poi.hssf.usermodel HSSFSheet setDefaultColumnWidth

List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet setDefaultColumnWidth

Introduction

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

Prototype

@Override
public void setDefaultColumnWidth(int width) 

Source Link

Document

set the default column width for the sheet (if the columns do not define their own width) in characters

Usage

From source file:org.gbif.portal.web.view.ExcelView.java

License:Open Source License

/**
 * @see org.springframework.web.servlet.view.document.AbstractExcelView#buildExcelDocument(java.util.Map, org.apache.poi.hssf.usermodel.HSSFWorkbook, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//* ww  w. ja v  a 2s  . com*/
@SuppressWarnings("unchecked")
protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request,
        HttpServletResponse response) {

    Locale locale = RequestContextUtils.getLocale(request);

    //create results sheet
    String sheetTitle = messageSource.getMessage(resultsSheetTitleI18nKey, null, locale);
    HSSFSheet resultsSheet = workbook.createSheet(sheetTitle);
    resultsSheet.setDefaultColumnWidth((short) (defaultColumnWidth));

    //create a titles style
    HSSFCellStyle titlesStyle = workbook.createCellStyle();
    titlesStyle.setFillPattern((short) HSSFCellStyle.SOLID_FOREGROUND);
    titlesStyle.setFillBackgroundColor(HSSFColor.DARK_GREEN.index);
    HSSFFont font = workbook.createFont();
    font.setColor(HSSFColor.WHITE.index);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    titlesStyle.setFont(font);

    //create a hyperlink style
    HSSFCellStyle hyperlinkStyle = workbook.createCellStyle();
    HSSFFont hyperLinkFont = workbook.createFont();
    hyperLinkFont.setColor(HSSFColor.BLUE.index);
    hyperlinkStyle.setFont(hyperLinkFont);

    //reused cell reference
    HSSFCell cell = null;

    //write results sheet
    List<Field> fields = (List<Field>) request.getAttribute("requestedFields");
    List results = (List) request.getAttribute("results");

    int currentRow = 0;

    //column headings
    for (int i = 0; i < fields.size(); i++) {
        cell = getCell(resultsSheet, currentRow, i);
        cell.setCellStyle(titlesStyle);
        String title = messageSource.getMessage(fields.get(i).getFieldI18nNameKey(), null, locale);
        setText(cell, title);
        short titleLength = (short) (title.length() * charWidth);
        short columnWidth = resultsSheet.getColumnWidth((short) i);
        //update column width for long columns
        if (columnWidth < titleLength) {
            resultsSheet.setColumnWidth((short) i, (short) (titleLength));
        }
    }

    currentRow++;
    //results
    for (int i = 0; i < results.size(); i++) {

        Object result = results.get(i);

        for (int j = 0; j < fields.size(); j++) {

            Field field = fields.get(j);
            cell = getCell(resultsSheet, currentRow, j);

            try {
                short textWidth = defaultColumnWidth;
                String propertyValue = field.getRenderValue(request, messageSource, locale, result);
                if (propertyValue != null)
                    setText(cell, propertyValue);
                if (field instanceof UrlField) {
                    if (propertyValue != null && propertyValue.length() < urlMaxLength) {
                        String linkFormula = "HYPERLINK(\"" + propertyValue + "\")";
                        cell.setCellFormula(linkFormula);
                        cell.setCellStyle(hyperlinkStyle);
                    }
                }
                if (propertyValue != null) {

                    int textWidthInt = propertyValue.length() * charWidth;
                    if (textWidthInt > 32768) {
                        textWidth = Short.MAX_VALUE;
                    } else {
                        textWidth = (short) textWidthInt;
                    }
                }

                //update column width for long columns
                short columnWidth = resultsSheet.getColumnWidth((short) j);

                if (textWidth > columnWidth) {
                    resultsSheet.setColumnWidth((short) j, (short) textWidth);
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
        currentRow++;
    }

    //set up details sheet
    HSSFSheet detailsSheet = workbook
            .createSheet(messageSource.getMessage(detailsSheetTitleI18nKey, null, locale));
    detailsSheet.setColumnWidth((short) 0, (short) 6000);
    detailsSheet.setColumnWidth((short) 1, (short) Short.MAX_VALUE);
    ;
    List<FilterDTO> filters = (List) request.getAttribute("filters");
    CriteriaDTO criteria = (CriteriaDTO) request.getAttribute("criteria");
    String query = FilterUtils.getQueryDescription(filters, criteria, messageSource, locale);
    cell = getCell(detailsSheet, 0, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.description", null, locale));
    cell = getCell(detailsSheet, 0, 1);
    setText(cell, query);
    //add url for search
    cell = getCell(detailsSheet, 1, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.url", null, locale));
    cell = getCell(detailsSheet, 1, 1);
    cell.setCellStyle(hyperlinkStyle);
    String url = "http://" + request.getHeader("host") + request.getContextPath() + "/occurrences/search.htm?"
            + CriteriaUtil.getUrl(criteria);
    setText(cell, url);
    //there is a formula limit in Excel of 255 characters
    if (url != null && url.length() < urlMaxLength) {
        String link = "HYPERLINK(\"" + url + "\")";
        cell.setCellFormula(link);
    }
    //add url for download page
    cell = getCell(detailsSheet, 2, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.download.url", null, locale));
    cell = getCell(detailsSheet, 2, 1);
    cell.setCellStyle(hyperlinkStyle);
    String downloadurl = "http://" + request.getHeader("host") + request.getContextPath()
            + "/occurrences/download.htm?" + CriteriaUtil.getUrl(criteria);
    setText(cell, downloadurl);
    if (downloadurl != null && downloadurl.length() < urlMaxLength) {
        String link = "HYPERLINK(\"" + downloadurl + "\")";
        cell.setCellFormula(link);
    }
    //add date for this download
    cell = getCell(detailsSheet, 3, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.download.date", null, locale));
    cell = getCell(detailsSheet, 3, 1);
    SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
    setText(cell, sdf.format(new Date(System.currentTimeMillis())));
}

From source file:org.jfree.workbook.io.XLWriter.java

License:Open Source License

/**
 * Creates a new sheet in the HSSFWorkbook, based on the supplied worksheet.
 * /*from  w w  w . j a v  a2 s .c om*/
 * @param hssfWorkbook  the workbook.
 * @param worksheet  the worksheet.
 */
private void createHSSFWorksheet(HSSFWorkbook hssfWorkbook, Worksheet worksheet) {

    HSSFSheet hssfSheet = hssfWorkbook.createSheet(worksheet.getName());

    Iterator iterator = worksheet.getCells().getRowsIterator();
    while (iterator.hasNext()) {

        Row row = (Row) iterator.next();
        createHSSFRow(hssfWorkbook, hssfSheet, worksheet, row);

    }

    ColumnAttributesManager attributes = worksheet.getColumnAttributesManager();

    // default column width (pts as double) : convert it to chars as short...
    short w = (short) (attributes.getDefaultColumnWidth() / 4.0);
    hssfSheet.setDefaultColumnWidth(w);

    RowAttributesManager rowAttrs = worksheet.getRowAttributesManager();

    // default row height ...
    hssfSheet.setDefaultRowHeightInPoints((float) rowAttrs.getDefaultRowHeight());

    // now define the individual column widths...
    iterator = attributes.getAttributesIterator();
    while (iterator.hasNext()) {
        ColumnAttributes ca = (ColumnAttributes) iterator.next();
        for (int c = ca.getStartColumn(); c <= ca.getEndColumn(); c++) {

            hssfSheet.setColumnWidth((short) c, (short) (ca.getWidth() * 64));

        }
    }

}

From source file:org.metaeffekt.core.inventory.processor.writer.InventoryWriter.java

License:Apache License

private void writeArtifacts(Inventory inventory, HSSFWorkbook myWorkBook) {
    HSSFSheet mySheet = myWorkBook.createSheet("Artifact Inventory");
    mySheet.createFreezePane(0, 1);/*w ww.  ja  v  a  2 s .c  o  m*/
    mySheet.setDefaultColumnWidth(20);

    HSSFRow myRow = null;
    HSSFCell myCell = null;

    int rowNum = 0;

    myRow = mySheet.createRow(rowNum++);

    HSSFCellStyle headerStyle = createHeaderStyle(myWorkBook);

    int cellNum = 0;
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Id"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Checksum"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Component"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Group Id"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Version"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Latest Version"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("License"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Security Relevance"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Security Category"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Vulnerability"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Classification"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Comment"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("URL"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Projects"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Verified"));

    // create columns for key / value map content
    Set<String> attributes = new HashSet<>();
    for (Artifact artifact : inventory.getArtifacts()) {
        attributes.addAll(artifact.getAttributes());
    }

    List<String> ordered = new ArrayList<>(attributes);
    Collections.sort(ordered);

    for (String key : ordered) {
        myCell = myRow.createCell(cellNum++);
        myCell.setCellStyle(headerStyle);
        myCell.setCellValue(new HSSFRichTextString(key));
    }

    int numCol = cellNum;

    for (Artifact artifact : inventory.getArtifacts()) {
        myRow = mySheet.createRow(rowNum++);

        cellNum = 0;
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getId()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getChecksum()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getComponent()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getGroupId()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getVersion()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getLatestAvailableVersion()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getLicense()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.isSecurityRelevant() ? "X" : ""));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getSecurityCategory()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getVulnerability()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getClassification()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getComment()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.getUrl()));
        myCell = myRow.createCell(cellNum++);
        String projects = artifact.getProjects().toString();
        projects = projects.substring(1, projects.length() - 1);
        myCell.setCellValue(new HSSFRichTextString(projects));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(artifact.isVerified() ? "X" : ""));

        for (String key : ordered) {
            myCell = myRow.createCell(cellNum++);
            myCell.setCellValue(new HSSFRichTextString(artifact.get(key)));
        }
    }

    /** adjust with of cells
    for (int i = 0; i <= numCol; i++) {
    Integer width = (Integer) inventory.getContextMap().get("artifacts.column[" + i + "].width");
    if (width != null) {
        mySheet.setColumnWidth(i, Math.min(width, 255));
    }
    }*/

    mySheet.setAutoFilter(new CellRangeAddress(0, 65000, 0, numCol - 1));
}

From source file:org.metaeffekt.core.inventory.processor.writer.InventoryWriter.java

License:Apache License

private void writeNotices(Inventory inventory, HSSFWorkbook myWorkBook) {
    HSSFSheet mySheet = myWorkBook.createSheet("License Notices");
    mySheet.createFreezePane(0, 1);// ww  w .  ja v a 2  s.c  o  m
    mySheet.setDefaultColumnWidth(80);

    HSSFRow myRow = null;
    HSSFCell myCell = null;

    int rowNum = 0;

    myRow = mySheet.createRow(rowNum++);

    HSSFCellStyle headerStyle = createHeaderStyle(myWorkBook);

    int cellNum = 0;
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Component"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Version"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("License"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("License in Effect"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Source Category"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("License Notice"));
    myCell = myRow.createCell(cellNum++);
    myCell.setCellStyle(headerStyle);
    myCell.setCellValue(new HSSFRichTextString("Comment"));

    // create columns for key / value map content
    Set<String> attributes = new HashSet<>();
    for (LicenseMetaData licenseMetaData : inventory.getLicenseMetaData()) {
        attributes.addAll(licenseMetaData.getAttributes());
    }

    List<String> ordered = new ArrayList<>(attributes);
    Collections.sort(ordered);

    for (String key : ordered) {
        myCell = myRow.createCell(cellNum++);
        myCell.setCellStyle(headerStyle);
        myCell.setCellValue(new HSSFRichTextString(key));
    }

    int numCol = cellNum;

    for (LicenseMetaData licenseMetaData : inventory.getLicenseMetaData()) {
        myRow = mySheet.createRow(rowNum++);

        cellNum = 0;
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(licenseMetaData.getComponent()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(licenseMetaData.getVersion()));
        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(licenseMetaData.getLicense()));
        myCell = myRow.createCell(cellNum++);
        String licenseInEffect = licenseMetaData.getLicenseInEffect();
        if (StringUtils.isEmpty(licenseInEffect)) {
            licenseInEffect = licenseMetaData.getLicense();
        }
        myCell.setCellValue(new HSSFRichTextString(licenseInEffect));

        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(licenseMetaData.getSourceCategory()));

        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(licenseMetaData.getNotice()));

        myCell = myRow.createCell(cellNum++);
        myCell.setCellValue(new HSSFRichTextString(licenseMetaData.getComment()));

        for (String key : ordered) {
            myCell = myRow.createCell(cellNum++);
            myCell.setCellValue(new HSSFRichTextString(licenseMetaData.get(key)));
        }
    }

    /**
    for (int i = 0; i < 6; i++) {
    Integer width = (Integer) inventory.getContextMap().get("obligations.column[" + i + "].width");
    if (width != null) {
        mySheet.setColumnWidth(i, Math.min(width, 255));
    }
    }
     */

    mySheet.setAutoFilter(new CellRangeAddress(0, 65000, 0, numCol - 1));

}

From source file:org.talend.mdm.webapp.browserecords.server.servlet.ExportingServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    org.apache.log4j.Logger.getLogger(this.getClass()).info("SERVLET exporting for excel "); //$NON-NLS-1$

    DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); //$NON-NLS-1$
    response.reset();/*from   w w w  . j  a  v  a  2  s.  c o m*/
    response.setContentType("application/vnd.ms-excel"); //$NON-NLS-1$
    String theReportFile = "Reporting_" + df.format(new Date()) + ".xls"; //$NON-NLS-1$ //$NON-NLS-2$
    response.setHeader("Content-Disposition", "attachment; filename=\"" + theReportFile + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("new sheet"); //$NON-NLS-1$
    sheet.setDefaultColumnWidth((short) 20);

    String parametersValues = request.getParameter("params"); //$NON-NLS-1$
    if (parametersValues == null) {
        parametersValues = ""; //$NON-NLS-1$
    }

    org.apache.log4j.Logger.getLogger(this.getClass()).debug("params =" + parametersValues); //$NON-NLS-1$

    boolean splitEnd = false;
    String tmpSplit = parametersValues;
    Vector<String> paramVector = new Vector<String>();
    while (!splitEnd) {
        int indexMatch = tmpSplit.indexOf("###"); //$NON-NLS-1$
        if (indexMatch == -1) {
            paramVector.add(tmpSplit);
            splitEnd = true;
        } else {
            if (indexMatch > 0) {
                String tmpParam = tmpSplit.substring(0, indexMatch);
                paramVector.add(tmpParam);
            } else {
                paramVector.add(""); //$NON-NLS-1$
            }

            if (indexMatch + 3 >= tmpSplit.length()) {
                tmpSplit = ""; //$NON-NLS-1$
            } else {
                tmpSplit = tmpSplit.substring(indexMatch + 3);
            }
        }
    }

    // String []parameters = parametersValues.split("###");
    String[] parameters = new String[paramVector.size()];
    for (int i = 0; i < paramVector.size(); i++) {
        parameters[i] = paramVector.get(i);
    }

    org.apache.log4j.Logger.getLogger(this.getClass()).debug("nb params =" + parameters.length); //$NON-NLS-1$

    try {
        WSDataClusterPK wsDataClusterPK = new WSDataClusterPK();
        String entity = null;
        String contentWords = null;
        String keys = null;
        Long fromDate = new Long(-1);
        Long toDate = new Long(-1);
        String fkvalue = null;
        String dataObject = null;

        if (parametersValues != null && parametersValues.length() > 0) {
            JSONObject criteria = new JSONObject(parametersValues);

            Configuration configuration = Configuration.getConfiguration();
            wsDataClusterPK.setPk(configuration.getCluster());
            entity = !criteria.isNull("entity") ? (String) criteria.get("entity") : ""; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            keys = !criteria.isNull("key") && !"*".equals(criteria.get("key")) ? (String) criteria.get("key") //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
                    : ""; //$NON-NLS-1$
            fkvalue = !criteria.isNull("fkvalue") && !"*".equals(criteria.get("fkvalue")) //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                    ? (String) criteria.get("fkvalue") //$NON-NLS-1$
                    : ""; //$NON-NLS-1$
            dataObject = !criteria.isNull("dataObject") && !"*".equals(criteria.get("dataObject")) //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                    ? (String) criteria.get("dataObject") //$NON-NLS-1$
                    : ""; //$NON-NLS-1$
            contentWords = !criteria.isNull("keyWords") ? (String) criteria.get("keyWords") : ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

            if (!criteria.isNull("fromDate")) { //$NON-NLS-1$
                String startDate = (String) criteria.get("fromDate"); //$NON-NLS-1$
                SimpleDateFormat dataFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //$NON-NLS-1$
                java.util.Date date = dataFmt.parse(startDate);
                fromDate = date.getTime();
            }

            if (!criteria.isNull("toDate")) { //$NON-NLS-1$
                String endDate = (String) criteria.get("toDate"); //$NON-NLS-1$
                SimpleDateFormat dataFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //$NON-NLS-1$
                java.util.Date date = dataFmt.parse(endDate);
                toDate = date.getTime();
            }
        }

        BusinessConcept businessConcept = SchemaWebAgent.getInstance().getBusinessConcept(entity);
        Map<String, String> foreignKeyMap = businessConcept.getForeignKeyMap();
        Set<String> foreignKeyXpath = foreignKeyMap.keySet();
        Set<String> xpathes = new HashSet<String>();

        for (String path : foreignKeyXpath) {
            String dataObjectPath = foreignKeyMap.get(path);
            if (dataObjectPath.indexOf(dataObject) != -1) {
                xpathes.add(path.substring(1));
            }
        }

        List<String> types = SchemaWebAgent.getInstance().getBindingType(businessConcept.getE());
        for (String type : types) {
            List<ReusableType> subTypes = SchemaWebAgent.getInstance().getMySubtypes(type);
            for (ReusableType reusableType : subTypes) {
                Map<String, String> fks = SchemaWebAgent.getInstance().getReferenceEntities(reusableType,
                        dataObject);
                Collection<String> fkPaths = fks != null ? fks.keySet() : null;
                for (String fkpath : fkPaths) {
                    if (fks.get(fkpath).indexOf(dataObject) != -1) {
                        xpathes.add(fkpath);
                    }
                }
            }
        }

        Map<String, String> inheritanceForeignKeyMap = businessConcept.getInheritanceForeignKeyMap();
        for (Map.Entry<String, String> entry : inheritanceForeignKeyMap.entrySet()) {
            if (entry.getValue().indexOf(dataObject) != -1) {
                xpathes.add(entry.getKey().substring(1));
            }
        }

        StringBuilder keysb = new StringBuilder();
        keysb.append("$"); //$NON-NLS-1$
        keysb.append(joinSet(xpathes, ",")); //$NON-NLS-1$
        keysb.append("$"); //$NON-NLS-1$
        keysb.append(fkvalue);

        WSItemPKsByCriteriaResponse results = Util.getPort().getItemPKsByFullCriteria(
                new WSGetItemPKsByFullCriteria(new WSGetItemPKsByCriteria(wsDataClusterPK, entity, contentWords,
                        keysb.toString(), keys, fromDate, toDate, 0, Integer.MAX_VALUE), false));

        // create a cell style
        HSSFCellStyle cs = wb.createCellStyle();
        HSSFFont f = wb.createFont();
        f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        cs.setFont(f);
        HSSFRow row = sheet.createRow((short) 0);

        if (results.getResults().length > 0) {
            row.createCell((short) 0).setCellValue("date"); //$NON-NLS-1$
            row.createCell((short) 1).setCellValue("entity"); //$NON-NLS-1$
            row.createCell((short) 2).setCellValue("key"); //$NON-NLS-1$
        }

        // set a style for these cells
        for (int i = 0; i < 3; i++) {
            row.getCell((short) i).setCellStyle(cs);
        }

        for (int i = 0; i < results.getResults().length; i++) {
            WSItemPKsByCriteriaResponseResults result = results.getResults()[i];
            if (i == 0) {
                continue;
            }

            row = sheet.createRow((short) i);
            SimpleDateFormat dataFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //$NON-NLS-1$
            String date = dataFmt.format(result.getDate());
            row.createCell((short) 0).setCellValue(date);
            row.createCell((short) 1).setCellValue(result.getWsItemPK().getConceptName());
            String[] ids = result.getWsItemPK().getIds();
            StringBuilder sb = new StringBuilder();

            if (ids != null) {
                for (String id : ids) {
                    sb.append(id);
                }
            }

            row.createCell((short) 2).setCellValue(sb.toString());
        }
    } catch (RemoteException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Write the output
    OutputStream out = response.getOutputStream();
    wb.write(out);
    out.close();
}

From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.organization.OrganizationAction.java

License:Open Source License

public final ActionForward downloadUnitResponsibles(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException, SQLException {

    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=ResponsaveisUnidades.xls");

    final ServletOutputStream outputStream = response.getOutputStream();
    final HSSFWorkbook workbook = new HSSFWorkbook();
    final ExcelStyle excelStyle = new ExcelStyle(workbook);

    final HSSFSheet sheet = workbook.createSheet("Responsaveis");
    sheet.setDefaultColumnWidth(20);

    final HSSFRow row = sheet.createRow(sheet.getLastRowNum());
    createHeaderCell(excelStyle, row, 0, "Centro de Custo");
    createHeaderCell(excelStyle, row, 1, "Unidade");
    createHeaderCell(excelStyle, row, 2, "Responsvel Aprovao");
    createHeaderCell(excelStyle, row, 4, "Responsvel Despesa");

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 3));
    sheet.addMergedRegion(new CellRangeAddress(0, 0, 4, 5));

    for (final Unit unit : ExpenditureTrackingSystem.getInstance().getTopLevelUnitsSet()) {
        writeUnitResponsibleInfo(excelStyle, sheet, unit);
    }/*from   w  ww.ja v a2  s .  c  o  m*/

    workbook.write(outputStream);

    outputStream.flush();
    outputStream.close();

    return null;
}