Example usage for org.apache.poi.hssf.usermodel HSSFCellStyle setDataFormat

List of usage examples for org.apache.poi.hssf.usermodel HSSFCellStyle setDataFormat

Introduction

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

Prototype

@Override
public void setDataFormat(short fmt) 

Source Link

Document

set the data format (must be a valid format)

Usage

From source file:com.softtek.mdm.web.admin.IndexController.java

private void exportExcel(String sheetName, String[] headNames, List<OrganizationModel> lists,
        HttpServletResponse response) {/* w  ww . ja va  2 s.c o m*/

    OutputStream out = null;
    try {
        HSSFWorkbook workbook = new HSSFWorkbook(); //   
        HSSFSheet sheet = workbook.createSheet(sheetName); //   
        //   
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0);
        //sheet??getColumnTopStyle()/getStyle()? - ?  - ?  
        HSSFCellStyle columnTopStyle = CommUtil.getColumnTopStyle(workbook);//??  
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (headNames.length - 1)));
        cellTiltle.setCellStyle(columnTopStyle);
        cellTiltle.setCellValue(sheetName);
        //   
        int columnNum = headNames.length;
        HSSFRow rowRowName = sheet.createRow(2); // 2?()  
        // sheet?  
        for (int n = 0; n < columnNum; n++) {
            HSSFCell cellRowName = rowRowName.createCell(n); //?  
            cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //??  
            HSSFRichTextString text = new HSSFRichTextString(headNames[n]);
            cellRowName.setCellValue(text); //?  
            cellRowName.setCellStyle(columnTopStyle); //??  
        }
        //?sheet?  
        HSSFDataFormat format = workbook.createDataFormat();
        short formatDate = format.getFormat("yyyy-MM-dd hh:mm:ss");
        for (int i = 0; i < lists.size(); i++) {
            HSSFRow row = sheet.createRow(i + 3);//  
            OrganizationModel obj = lists.get(i);//???  
            /*row.createCell(0).setCellValue(obj.getOrgType());*/
            row.createCell(0).setCellValue(obj.getName());
            row.createCell(1).setCellValue(obj.getCreateName());
            row.createCell(2).setCellValue(obj.getTotalUsers() == null ? 0 : obj.getTotalUsers());
            row.createCell(3).setCellValue(obj.getTotalDevices() == null ? 0 : obj.getTotalDevices());
            row.createCell(4).setCellValue(obj.getLicenseCount() == null ? 0 : obj.getLicenseCount());
            row.createCell(5).setCellValue(obj.getUseUsers() == null ? 0 : obj.getUseUsers());
            HSSFCell cell = row.createCell(6);
            cell.setCellValue(obj.getCreateTime());
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setDataFormat(formatDate);
            cell.setCellStyle(cellStyle);
        }
        //??  
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //?  
                currentRow = (sheet.getRow(rowNum) == null) ? sheet.createRow(rowNum) : sheet.getRow(rowNum);
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(colNum, (colNum == 0) ? (columnWidth * 256) : ((columnWidth + 10) * 256));
        }
        if (workbook != null) {
            try {
                String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13)
                        + ".xls";
                String headStr = "attachment; filename=\"" + fileName + "\"";
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", headStr);
                out = response.getOutputStream();
                workbook.write(out);
            } catch (IOException e) {
                logger.error(e.getMessage());
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

From source file:com.ssic.education.provider.controller.ProSupplierController.java

@RequestMapping(value = "/excel")
@ResponseBody/*w  w w .  j a va  2  s .c om*/
public ModelAndView exportExcel(SupplierDto supplierDto, HttpServletRequest request,
        HttpServletResponse response) {
    SessionInfo info = (SessionInfo) request.getSession().getAttribute(ConfigUtil.SESSIONINFONAME);
    if (info == null) {
        return null;
    }
    supplierDto.setReceiverId(info.getSupplierId());
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.M.d");
    Date date = new Date();
    String filename = Tools.date2Str(date, "yyyyMMddHHmmss");
    HSSFSheet sheet;
    HSSFCell cell;
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
    Workbook workbook = new HSSFWorkbook();
    sheet = (HSSFSheet) workbook.createSheet("");
    try {
        List<String> titles = new ArrayList<String>();
        titles.add("????");
        titles.add("???");
        //         titles.add("????");
        //         titles.add("??????");
        titles.add("????");
        titles.add("???");
        //         titles.add("?");
        //         titles.add("???");
        titles.add("?");
        titles.add("?");
        int len = titles.size();
        HSSFCellStyle headerStyle = (HSSFCellStyle) workbook.createCellStyle(); // ?
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont headerFont = (HSSFFont) workbook.createFont(); // 
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerFont.setFontHeightInPoints((short) 11);
        headerStyle.setFont(headerFont);
        short width = 20, height = 25 * 20;
        sheet.setDefaultColumnWidth(width);
        HSSFRow sheetRow = sheet.createRow(0);
        for (int i = 0; i < len; i++) { // 
            String title = titles.get(i);
            cell = sheetRow.createCell(i);
            cell.setCellStyle(headerStyle);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(title);
        }
        sheet.getRow(0).setHeight(height);
        HSSFCellStyle contentStyle = (HSSFCellStyle) workbook.createCellStyle(); // ?
        contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        DataGrid dg = supplierService.findProSupplier(supplierDto, null);
        List<SupplierDto> expList = dg.getRows();
        List<PageData> varList = new ArrayList<PageData>();
        if (!CollectionUtils.isEmpty(expList)) {
            for (int i = 0; i < expList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", expList.get(i).getSupplierName());
                vpd.put("var2", expList.get(i).getAddress());
                //               vpd.put("var3", expList.get(i).getFoodServiceCode());
                //               vpd.put("var4", expList.get(i).getFoodBusinessCode());
                vpd.put("var3", expList.get(i).getFoodCirculationCode());
                vpd.put("var4", expList.get(i).getFoodProduceCode());
                //               vpd.put("var7", expList.get(i).getBusinessLicense());
                //               vpd.put("var8", expList.get(i).getSupplierCode());
                vpd.put("var5", expList.get(i).getCorporation());
                vpd.put("var6", expList.get(i).getContactWay());
                varList.add(vpd);
            }
        }
        for (int i = 0; i < varList.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            PageData vpd = varList.get(i);
            for (int j = 0; j < len; j++) {
                String varstr = vpd.getString("var" + (j + 1)) != null ? vpd.getString("var" + (j + 1)) : "";
                cell = row.createCell(j);
                HSSFCellStyle cellStyle2 = (HSSFCellStyle) workbook.createCellStyle();
                HSSFDataFormat format = (HSSFDataFormat) workbook.createDataFormat();
                cellStyle2.setDataFormat(format.getFormat("@"));
                cell.setCellStyle(cellStyle2);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(varstr);

            }

        }
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();
    } catch (Exception e) {

    }
    return null;
}

From source file:com.ssic.education.provider.controller.WaresController.java

@RequestMapping(value = "/excel")
@ResponseBody/*w w w. j  a  va2  s  .  c o m*/
public ModelAndView exportExcel(ProWaresDto proWaresDto, HttpServletRequest request,
        HttpServletResponse response) {
    SessionInfo info = (SessionInfo) request.getSession().getAttribute(ConfigUtil.SESSIONINFONAME);
    if (info == null) {
        return null;
    }
    proWaresDto.setSupplierId(info.getSupplierId());
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.M.d");
    Date date = new Date();
    String filename = Tools.date2Str(date, "yyyyMMddHHmmss");
    HSSFSheet sheet;
    HSSFCell cell;
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
    Workbook workbook = new HSSFWorkbook();
    sheet = (HSSFSheet) workbook.createSheet("");
    try {
        List<String> titles = new ArrayList<String>();
        titles.add("??");
        titles.add("???");
        titles.add("");
        titles.add("?");
        titles.add("?");
        //         titles.add("??");
        //         titles.add("???");
        //         titles.add("??");
        titles.add("?");
        titles.add("???");
        titles.add("");
        int len = titles.size();
        HSSFCellStyle headerStyle = (HSSFCellStyle) workbook.createCellStyle(); // ?
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont headerFont = (HSSFFont) workbook.createFont(); // 
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerFont.setFontHeightInPoints((short) 11);
        headerStyle.setFont(headerFont);
        short width = 20, height = 25 * 20;
        sheet.setDefaultColumnWidth(width);
        HSSFRow sheetRow = sheet.createRow(0);
        for (int i = 0; i < len; i++) { // 
            String title = titles.get(i);
            cell = sheetRow.createCell(i);
            cell.setCellStyle(headerStyle);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(title);
        }
        sheet.getRow(0).setHeight(height);
        HSSFCellStyle contentStyle = (HSSFCellStyle) workbook.createCellStyle(); // ?
        contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        List<ProWaresDto> expList = waresService.findAllWares(proWaresDto, null);
        List<PageData> varList = new ArrayList<PageData>();
        if (!CollectionUtils.isEmpty(expList)) {
            for (int i = 0; i < expList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", expList.get(i).getWaresName());
                vpd.put("var2", expList.get(i).getAmountUnit());
                vpd.put("var3", expList.get(i).getSpec());
                vpd.put("var4", ProductClass.getName(expList.get(i).getWaresType()));
                vpd.put("var5", expList.get(i).getManufacturer());
                //               vpd.put("var5", expList.get(i).getEnName());
                //               vpd.put("var6", expList.get(i).getBarCode());
                //               vpd.put("var7", expList.get(i).getCustomCode());
                vpd.put("var6", expList.get(i).getShelfLife());
                vpd.put("var7", expList.get(i).getUnit());
                vpd.put("var8", expList.get(i).getPlace());
                varList.add(vpd);
            }
        }
        for (int i = 0; i < varList.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            PageData vpd = varList.get(i);
            for (int j = 0; j < len; j++) {
                String varstr = vpd.getString("var" + (j + 1)) != null ? vpd.getString("var" + (j + 1)) : "";
                cell = row.createCell(j);
                HSSFCellStyle cellStyle2 = (HSSFCellStyle) workbook.createCellStyle();
                HSSFDataFormat format = (HSSFDataFormat) workbook.createDataFormat();
                cellStyle2.setDataFormat(format.getFormat("@"));
                cell.setCellStyle(cellStyle2);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(varstr);

            }

        }
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();
    } catch (Exception e) {

    }
    return null;
}

From source file:com.taobao.itest.dbunit.dataset.excel.XlsDataSetWriter.java

License:Open Source License

protected static HSSFCellStyle createDateCellStyle(HSSFWorkbook workbook) {
    HSSFDataFormat format = workbook.createDataFormat();
    short dateFormatCode = format.getFormat(DATE_FORMAT_AS_NUMBER_DBUNIT);
    HSSFCellStyle dateCellStyle = workbook.createCellStyle();
    dateCellStyle.setDataFormat(dateFormatCode);
    return dateCellStyle;
}

From source file:com.taobao.itest.dbunit.dataset.excel.XlsDataSetWriter.java

License:Open Source License

protected void setNumericCell(HSSFCell cell, BigDecimal value, HSSFWorkbook workbook) {
    if (logger.isDebugEnabled())
        logger.debug("setNumericCell(cell={}, value={}, workbook={}) - start",
                new Object[] { cell, value, workbook });

    cell.setCellValue(((BigDecimal) value).doubleValue());

    HSSFDataFormat df = workbook.createDataFormat();
    int scale = ((BigDecimal) value).scale();
    short format;
    if (scale <= 0) {
        format = df.getFormat("####");
    } else {//from  ww  w .  ja  va2 s. c o  m
        String zeros = createZeros(((BigDecimal) value).scale());
        format = df.getFormat("####." + zeros);
    }
    if (logger.isDebugEnabled())
        logger.debug("Using format '{}' for value '{}'.", String.valueOf(format), value);

    HSSFCellStyle cellStyleNumber = workbook.createCellStyle();
    cellStyleNumber.setDataFormat(format);
    cell.setCellStyle(cellStyleNumber);
}

From source file:com.testmax.util.ExcelSheet.java

License:CDDL license

public void addRowWithFormat(String sheetName, int row, String[] value, String[] format) {
    try {//from   ww  w.  j ava2 s .  co  m
        String formatV = "";
        FileInputStream fileInputStream = new FileInputStream(this.fileName);
        POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
        HSSFWorkbook workbook = new HSSFWorkbook(fsFileSystem);
        HSSFSheet worksheet = workbook.getSheet(sheetName);
        if (worksheet == null) {
            worksheet = workbook.createSheet(sheetName);
        }
        // index from 0,0... cell A1 is cell(0,0)
        HSSFRow row1 = worksheet.createRow(row);

        for (int col = 0; col < value.length; col++) {
            HSSFCell cellA1 = row1.createCell(col);
            cellA1.setCellValue(value[col]);
            if (format.length >= col) {
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(format[col]));
                //cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
                //cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                cellA1.setCellStyle(cellStyle);
            }
        }
        FileOutputStream fileOut = new FileOutputStream(this.fileName);
        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        WmLog.printMessage("ERROR in adding row XLs file =" + this.fileName + "Excel Sheet Index=" + sheetName
                + " with Excel Row =" + row + " " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        WmLog.printMessage("ERROR in adding row XLs file =" + this.fileName + "Excel Sheet Index=" + sheetName
                + " with Excel Row =" + row + " " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:com.toba.bll.admin.ReportsDownloadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*  w  w w .  j av a 2 s. c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("Users Registered in the Past Month");
    Row row = sheet.createRow(0);
    row.createCell(0).setCellValue("User Name");
    row.createCell(1).setCellValue("First Name");
    row.createCell(2).setCellValue("Last Name");
    row.createCell(3).setCellValue("Registration Date");

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MONTH, -1);
    Date oneMonthAgo = calendar.getTime();

    List<User> usersRegisteredInThePastMonth = UserDB.selectUsersRegisteredAfter(oneMonthAgo);

    HSSFCellStyle dateCellStyle = (HSSFCellStyle) workbook.createCellStyle();
    short dateDataFormat = workbook.createDataFormat().getFormat("dd/MM/yyyy");
    dateCellStyle.setDataFormat(dateDataFormat);

    for (int i = 0; i < usersRegisteredInThePastMonth.size(); i++) {
        User user = usersRegisteredInThePastMonth.get(i);

        row = sheet.createRow(1 + i);
        row.createCell(0).setCellValue(user.getUserName());
        row.createCell(1).setCellValue(user.getFirstName());
        row.createCell(2).setCellValue(user.getLastName());
        row.createCell(3).setCellValue(user.getRegistrationDate());
        row.getCell(3).setCellStyle(dateCellStyle);
    }

    workbook.write(response.getOutputStream());
    workbook.close();

    response.setHeader("content-disposition", "attachment; filename=users.xls");
    response.setHeader("cache-control", "no-cache");
}

From source file:de.jwic.ecolib.tableviewer.export.ExcelExportControl.java

License:Apache License

private HSSFWorkbook createWorkBook() {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Sheet");
    HSSFRow row = sheet.createRow(0);/*from w  w  w .  j  av  a2 s.  c om*/

    // Style for title cells
    HSSFFont font = wb.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    font.setColor(HSSFColor.BLUE.index);

    HSSFCellStyle styleTitle = wb.createCellStyle();
    styleTitle.setFont(font);

    // Style for data date cells
    font = wb.createFont();
    HSSFCellStyle styleDate = wb.createCellStyle();
    styleDate.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));

    short col = 0;
    TableModel model = tableViewer.getModel();
    Iterator<TableColumn> it = model.getColumnIterator();

    // create title in the sheet
    while (it.hasNext()) {
        TableColumn column = it.next();
        if (!isColumnVisible(column)) {
            continue;
        }
        sheet.setColumnWidth(col, (short) (column.getWidth() * 40));
        HSSFCell cell = row.createCell(col++);
        cell.setCellValue(column.getTitle());
        cell.setCellStyle(styleTitle);
    }

    // add the datas from the table viewer
    IContentProvider<?> contentProvider = model.getContentProvider();
    Iterator<?> iter = contentProvider.getContentIterator(new Range());

    try {
        renderRows(iter, 0, model, sheet, styleDate);
    } catch (Throwable t) {
        log.error("Error rendering rows", t);
    }

    return wb;
}

From source file:de.maklerpoint.office.Schnittstellen.Excel.ExportExcelXLS.java

License:Open Source License

/**
 * create a library of cell styles/*from w w  w .  ja v  a2 s  . co  m*/
 */
private static Map<String, HSSFCellStyle> createStyles(HSSFWorkbook wb) {
    Map<String, HSSFCellStyle> styles = new HashMap<String, HSSFCellStyle>();
    HSSFDataFormat df = wb.createDataFormat();

    HSSFCellStyle style;
    HSSFFont headerFont = wb.createFont();
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(headerFont);
    styles.put("header", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(headerFont);
    style.setDataFormat(df.getFormat("dd.MM.yyyy"));
    styles.put("header_date", style);

    HSSFFont font1 = wb.createFont();
    font1.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font1);
    styles.put("cell_b", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font1);
    styles.put("cell_b_centered", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font1);
    style.setDataFormat(df.getFormat("dd.MM.yyyy"));
    styles.put("cell_b_date", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font1);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setDataFormat(df.getFormat("dd.MM.yyyy"));
    styles.put("cell_g", style);

    HSSFFont font2 = wb.createFont();
    font2.setColor(IndexedColors.BLUE.getIndex());
    font2.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font2);
    styles.put("cell_bb", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font1);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setDataFormat(df.getFormat("dd.MM.yyyy"));
    styles.put("cell_bg", style);

    HSSFFont font3 = wb.createFont();
    font3.setFontHeightInPoints((short) 14);
    font3.setColor(IndexedColors.DARK_BLUE.getIndex());
    font3.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font3);
    style.setWrapText(true);
    styles.put("cell_h", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setWrapText(true);
    styles.put("cell_normal", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setWrapText(true);
    styles.put("cell_normal_centered", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setWrapText(true);
    style.setDataFormat(df.getFormat("dd.MM.yyyy"));
    styles.put("cell_normal_date", style);

    style = createBorderedStyle(wb);
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setIndention((short) 1);
    style.setWrapText(true);
    styles.put("cell_indented", style);

    style = createBorderedStyle(wb);
    style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    styles.put("cell_blue", style);

    return styles;
}

From source file:de.powerstaff.web.backingbean.profile.ProfileBackingBean.java

License:Open Source License

public void commandSearchExportExcel() {
    try {//from   w  w w .  j  a va2 s .  c  o  m
        FacesContext theContext = FacesContext.getCurrentInstance();

        ExternalContext externalContext = theContext.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=\"ExportSuche.xls\"");

        HSSFWorkbook theWorkbook = new HSSFWorkbook();
        HSSFSheet theWorkSheet = theWorkbook.createSheet("ExportSuche");

        HSSFCellStyle theDateStyle = theWorkbook.createCellStyle();
        theDateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("d/m/jj"));

        int aRow = 0;
        // Header
        HSSFRow theRow = theWorkSheet.createRow(aRow++);
        ExcelUtils.addCellToRow(theRow, 0, "Anrede");
        ExcelUtils.addCellToRow(theRow, 1, "Name1");
        ExcelUtils.addCellToRow(theRow, 2, "Name2");
        ExcelUtils.addCellToRow(theRow, 3, "eMail");
        ExcelUtils.addCellToRow(theRow, 4, "Code");
        ExcelUtils.addCellToRow(theRow, 5, "Verfgbarkeit");
        ExcelUtils.addCellToRow(theRow, 6, "Satz");
        ExcelUtils.addCellToRow(theRow, 7, "Plz");
        ExcelUtils.addCellToRow(theRow, 8, "Letzter Kontakt");
        ExcelUtils.addCellToRow(theRow, 9, "Skills");
        ExcelUtils.addCellToRow(theRow, 10, "Tags");

        // Rows
        PagedListDataModel<ProfileSearchEntry> theData = getData().getSearchResult();
        for (int i = 0; i < theData.getRowCount() && i < profileSearchService.getPageSize(); i++) {
            theData.setRowIndex(i);

            ProfileSearchEntry theDataRow = (ProfileSearchEntry) theData.getRowData();

            Freelancer theFreelancer = freelancerService.findByPrimaryKey(theDataRow.getFreelancer().getId());

            String theSkills = ExcelUtils.saveObject(
                    theFreelancer.getSkills().replace("\f", "").replace("\n", "").replace("\t", ""));

            StringBuilder theTagList = new StringBuilder();
            for (FreelancerToTag theTagAssignment : theFreelancer.getTags()) {
                if (theTagList.length() > 0) {
                    theTagList.append(" ");
                }
                theTagList.append(theTagAssignment.getTag().getName());
            }

            HSSFRow theFreelancerRow = theWorkSheet.createRow(aRow++);
            ExcelUtils.addCellToRow(theFreelancerRow, 0, ExcelUtils.saveObject(theFreelancer.getTitel()));
            ExcelUtils.addCellToRow(theFreelancerRow, 1, ExcelUtils.saveObject(theFreelancer.getName1()));
            ExcelUtils.addCellToRow(theFreelancerRow, 2, ExcelUtils.saveObject(theFreelancer.getName2()));
            ExcelUtils.addCellToRow(theFreelancerRow, 3,
                    ExcelUtils.saveObject(theFreelancer.getFirstContactEMail())); // eMail
            ExcelUtils.addCellToRow(theFreelancerRow, 4, ExcelUtils.saveObject(theFreelancer.getCode()));
            ExcelUtils.addCellToRow(theFreelancerRow, 5,
                    ExcelUtils.saveObject(theFreelancer.getAvailabilityAsDate()), theDateStyle);
            ExcelUtils.addCellToRow(theFreelancerRow, 6, ExcelUtils.saveObject(theFreelancer.getSallaryLong()));
            ExcelUtils.addCellToRow(theFreelancerRow, 7, ExcelUtils.saveObject(theFreelancer.getPlz()));
            ExcelUtils.addCellToRow(theFreelancerRow, 8,
                    ExcelUtils.saveObject(theFreelancer.getLastContactDate()), theDateStyle);
            ExcelUtils.addCellToRow(theFreelancerRow, 9, ExcelUtils.saveObject(theSkills));
            ExcelUtils.addCellToRow(theFreelancerRow, 10, theTagList.toString());
        }

        theWorkbook.write(response.getOutputStream());

        theContext.responseComplete(); // Important!

    } catch (Exception e) {
        JSFMessageUtils.addGlobalErrorMessage(MSG_FEHLERBEIDERPROFILSUCHE, e.getMessage());
        LOGGER.error("Fehler bei Profilsuche", e);
    }
}