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

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

Introduction

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

Prototype

@Override
public void setWrapText(boolean wrapped) 

Source Link

Document

set whether the text should be wrapped

Usage

From source file:egovframework.rte.fdl.excel.EgovExcelSXSSFServiceTest.java

License:Apache License

/**
 * [Flow #-5]    :  ?? ?  ? ?  /*w  w w .j a  va 2  s  .  co  m*/
 */
@Test
public void testGetCellContents() throws Exception {

    try {
        log.debug("testGetCellContents start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testGetCellContents.xls");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            log.debug("Delete file...." + sb.toString());
        }

        HSSFWorkbook wbTmp = new HSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        HSSFWorkbook wb = excelService.loadWorkbook(sb.toString());
        log.debug("testGetCellContents after loadWorkbook....");

        HSSFSheet sheet = wb.createSheet("cell test sheet");

        HSSFCellStyle cs = wb.createCellStyle();
        cs = wb.createCellStyle();
        cs.setWrapText(true);

        for (int i = 0; i < 100; i++) {
            HSSFRow row = sheet.createRow(i);
            for (int j = 0; j < 5; j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(new HSSFRichTextString("row " + i + ", cell " + j));
                cell.setCellStyle(cs);
            }
        }

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //////////////////////////////////////////////////////////////////////////
        // ?
        HSSFWorkbook wbT = excelService.loadWorkbook(sb.toString());
        HSSFSheet sheetT = wbT.getSheet("cell test sheet");

        for (int i = 0; i < 100; i++) {
            HSSFRow row1 = sheetT.getRow(i);
            for (int j = 0; j < 5; j++) {
                HSSFCell cell1 = row1.getCell(j);
                log.debug("row " + i + ", cell " + j + " : " + cell1.getRichStringCellValue());
                assertEquals("row " + i + ", cell " + j, cell1.getRichStringCellValue().toString());
            }
        }

    } catch (Exception e) {
        log.error(e.toString());
        throw new Exception(e);
    } finally {
        log.debug("testGetCellContents end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelSXSSFServiceTest.java

License:Apache License

/**
 * [Flow #-6]  ?  :  ? ?(?, ? )? /*  w  w w .  j  av  a2 s .  c o m*/
 */
@Test
public void testModifyCellAttribute() throws Exception {

    try {
        log.debug("testModifyCellAttribute start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testModifyCellAttribute.xls");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            log.debug("Delete file...." + sb.toString());
        }

        HSSFWorkbook wbTmp = new HSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        HSSFWorkbook wb = excelService.loadWorkbook(sb.toString());
        log.debug("testModifyCellAttribute after loadWorkbook....");

        HSSFSheet sheet = wb.createSheet("cell test sheet2");
        //           sheet.setColumnWidth((short) 3, (short) 200);   // column Width

        HSSFCellStyle cs = wb.createCellStyle();
        HSSFFont font = wb.createFont();
        font.setFontHeight((short) 16);
        font.setBoldweight((short) 3);
        font.setFontName("fixedsys");

        cs.setFont(font);
        cs.setAlignment(HSSFCellStyle.ALIGN_RIGHT); // cell 
        cs.setWrapText(true);

        for (int i = 0; i < 100; i++) {
            HSSFRow row = sheet.createRow(i);
            //              row.setHeight((short)300); // row? height 

            for (int j = 0; j < 5; j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(new HSSFRichTextString("row " + i + ", cell " + j));
                cell.setCellStyle(cs);
            }
        }

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //////////////////////////////////////////////////////////////////////////
        // ?
        HSSFWorkbook wbT = excelService.loadWorkbook(sb.toString());
        HSSFSheet sheetT = wbT.getSheet("cell test sheet2");
        log.debug("getNumCellStyles : " + wbT.getNumCellStyles());

        HSSFCellStyle cs1 = wbT.getCellStyleAt((short) (wbT.getNumCellStyles() - 1));

        HSSFFont fontT = cs1.getFont(wbT);
        log.debug("font getFontHeight : " + fontT.getFontHeight());
        log.debug("font getBoldweight : " + fontT.getBoldweight());
        log.debug("font getFontName : " + fontT.getFontName());
        log.debug("getAlignment : " + cs1.getAlignment());
        log.debug("getWrapText : " + cs1.getWrapText());

        for (int i = 0; i < 100; i++) {
            HSSFRow row1 = sheetT.getRow(i);
            for (int j = 0; j < 5; j++) {
                HSSFCell cell1 = row1.getCell(j);
                log.debug("row " + i + ", cell " + j + " : " + cell1.getRichStringCellValue());
                assertEquals(16, fontT.getFontHeight());
                assertEquals(3, fontT.getBoldweight());
                assertEquals(HSSFCellStyle.ALIGN_RIGHT, cs1.getAlignment());
                assertTrue(cs1.getWrapText());
            }
        }

    } catch (Exception e) {
        log.error(e.toString());
        throw new Exception(e);
    } finally {
        log.debug("testModifyCellAttribute end....");
    }
}

From source file:excel.PoiWriteExcelFile.java

public static int generarReporte() {

    //Calendar cal=Calendar.getInstance();
    Calendar cal = WorkMonitorUI.instante;

    try {/*w  w  w . ja  va 2s  . c  om*/
        FileOutputStream fileOut = new FileOutputStream("HH_"
                + instante.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault())
                        .toUpperCase()
                + "_" + persona.getNombre().toUpperCase().charAt(0) + "." + persona.getApellido().toUpperCase()
                + "_" + instante.get(Calendar.YEAR) + ".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet worksheet = workbook.createSheet(
                cal.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault()).toUpperCase()
                        + "-" + cal.get(Calendar.YEAR));

        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setFontName("Calibri");
        font.setItalic(false);
        font.setBold(true);
        font.setColor(HSSFColor.BLACK.index);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle diasStyle = workbook.createCellStyle();
        diasStyle.setFillForegroundColor(HSSFColor.SEA_GREEN.index);
        diasStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        font.setFontName("Calibri");
        font.setItalic(false);
        font.setBold(true);
        font.setColor(HSSFColor.WHITE.index);
        diasStyle.setFont(font);
        diasStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        diasStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        diasStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle schedStyle = workbook.createCellStyle();
        schedStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        schedStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont font3 = workbook.createFont();
        font3.setFontHeightInPoints((short) 11);
        font3.setFontName("Calibri");
        font3.setItalic(false);
        font3.setColor(HSSFColor.BLACK.index);
        schedStyle.setFont(font3);
        schedStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        schedStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        schedStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle workdayStyle = workbook.createCellStyle();
        //workdayStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);                        
        workdayStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        workdayStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setWrapText(true);
        HSSFFont font2 = workbook.createFont();
        font2.setFontHeightInPoints((short) 8);
        font2.setFontName("Serif");
        font2.setItalic(false);
        //font2.setColor(HSSFColor.YELLOW.index);
        workdayStyle.setFont(font2);
        workdayStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle weekendStyle = workbook.createCellStyle();
        weekendStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        weekendStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        weekendStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        weekendStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle horarioStyle = workbook.createCellStyle();
        horarioStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        horarioStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        horarioStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        horarioStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont font4 = workbook.createFont();
        font4.setFontHeightInPoints((short) 10);
        font4.setFontName("Serif");
        font4.setItalic(false);
        font4.setBold(true);
        //font2.setColor(HSSFColor.YELLOW.index);
        horarioStyle.setFont(font4);

        // index from 0,0... cell A1 is cell(0,0)
        HSSFRow row1 = worksheet.createRow((short) 0);
        row1.setHeight((short) 500);

        //System.out.println("cal.get(Calendar.YEAR)="+cal.get(Calendar.YEAR));

        HSSFCell cellA1 = row1.createCell((short) 0);
        cellA1.setCellValue(
                cal.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault()).toUpperCase()
                        + "-" + cal.get(Calendar.YEAR));
        cellA1.setCellStyle(cellStyle);

        HSSFRow row2 = worksheet.createRow((short) 1);
        HSSFCell cellA4 = row2.createCell((short) 0);
        cellA4.setCellValue("Horario");
        cellA4.setCellStyle(horarioStyle);
        //row2.setHeight((short)500);

        HSSFRow row3 = worksheet.createRow((short) 2);
        HSSFCell cellA3 = row3.createCell((short) 0);
        cellA3.setCellValue("Inicio - Trmino");
        cellA3.setCellStyle(diasStyle);

        Calendar hora = Calendar.getInstance();

        hora.set(Calendar.HOUR_OF_DAY, 9);
        hora.set(Calendar.MINUTE, 0);
        hora.set(Calendar.SECOND, 0);

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

        HSSFCell cellXn;

        for (int i = 0; i < 29; ++i) {
            HSSFRow row = worksheet.createRow((short) i + 3);
            row.setHeight((short) 500);

            cellXn = row.createCell((short) 0);
            String horaIni = sdf.format(hora.getTime());
            hora.add(Calendar.MINUTE, 30);
            String horaFin = sdf.format(hora.getTime());
            cellXn.setCellValue(horaIni + " - " + horaFin);
            cellXn.setCellStyle(schedStyle);
        }

        System.out.println("cal.get(Calendar.MONTH)1=" + cal.get(Calendar.MONTH));

        cal.add(Calendar.DAY_OF_MONTH, -cal.get(Calendar.DAY_OF_MONTH) + 1);

        int diasMes = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        System.out.println("cal.get(Calendar.MONTH)2=" + cal.get(Calendar.MONTH));

        sdf = new SimpleDateFormat("EEEE d");

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)1=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        for (int i = 0; i < diasMes; ++i) {
            cellXn = row2.createCell((short) i + 1);
            String dia = sdf.format(cal.getTime());
            dia = Character.toUpperCase(dia.charAt(0)) + dia.substring(1);
            cellXn.setCellValue(dia);
            cellXn.setCellStyle(horarioStyle);
            //System.out.println("cal.get(Calendar.DAY_OF_MONTH)="+cal.get(Calendar.DAY_OF_MONTH));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }

        for (int i = 0; i < diasMes; ++i) {
            cellXn = row3.createCell((short) i + 1);
            cellXn.setCellValue("Descripcin");
            cellXn.setCellStyle(diasStyle);
        }

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)2=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        // Retroceder mes para que quede como estaba
        cal.add(Calendar.MONTH, -1);
        //cal.add(Calendar.DAY_OF_MONTH, -1);    

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)3=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        HhDao hhDao = new HhDao();
        Object[][] hh = new Object[29][cal.getActualMaximum(Calendar.DAY_OF_MONTH)];

        hh = hhDao.getByMes(WorkMonitorUI.persona.getId(), cal.getTime());

        cal.set(Calendar.DAY_OF_MONTH, 1);

        Sheet sheet = workbook.getSheetAt(0);

        sdf = new SimpleDateFormat("EEEE");

        HSSFPatriarch _drawing = (HSSFPatriarch) sheet.createDrawingPatriarch();
        CreationHelper factory = workbook.getCreationHelper();

        for (int i = 0; i < 29; ++i) {
            Row r = sheet.getRow(i + 3);
            for (int j = 0; j < diasMes; ++j) {
                if (hh[i][j].toString() != "") {
                    cellXn = (HSSFCell) r.createCell((short) j + 1);
                    Hh _hh = (Hh) hh[i][j];
                    cellXn.setCellValue(
                            _hh.getTarea().getNombre().trim() + ": " + _hh.getActividad().getNombre().trim());

                    HSSFAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5);
                    org.apache.poi.ss.usermodel.Comment comment = _drawing.createComment(anchor);
                    String comentario = _hh.getTarea().getComentario().toLowerCase();
                    if (_hh.getComentario() != null)
                        comentario = comentario + _hh.getComentario().toLowerCase();
                    RichTextString str = factory.createRichTextString(comentario);

                    comment.setString(str);

                    cellXn.setCellComment(comment);
                } else {
                    cellXn = (HSSFCell) r.createCell((short) j + 1);
                    cellXn.setCellValue("");
                }
                //System.out.println("sdf.format(cal.getTime())="+sdf.format(cal.getTime()));
                if (Arrays.asList("sbado", "domingo").contains(sdf.format(cal.getTime())))
                    cellXn.setCellStyle(weekendStyle);
                else
                    cellXn.setCellStyle(workdayStyle);
                sheet.setColumnWidth(j, 5000);

                cal.add(Calendar.DAY_OF_MONTH, 1);
                //sheet.autoSizeColumn(j);
            }
            // Retroceder mes para que quede como estaba                
            cal.add(Calendar.MONTH, -1);
            System.out.println("cal.get(Calendar.MONTH)3=" + cal.get(Calendar.MONTH));
            cal.set(Calendar.DAY_OF_MONTH, 1);
        }
        sheet.setColumnWidth(diasMes, 5000);

        WorkMonitorUI.instante = Calendar.getInstance();
        sheet.setColumnWidth(0, 5000);
        sheet.createFreezePane(1, 3);
        // Freeze just one row
        //sheet.createFreezePane( 0, 1, 0, 1 );

        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return -1;
    } catch (IOException e) {
        e.printStackTrace();
        return -2;
    }
    return 1;
}

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

License:Open Source License

public static void main(String[] args) throws IOException {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Amap");

    // sheet.autoSizeColumn(0);

    HSSFCellStyle style = workbook.createCellStyle();
    style.setWrapText(true);

    addRow(sheet, style, (short) 0);

    addRow(sheet, style, (short) 1);

    addRow(sheet, style, (short) 2);

    FileOutputStream fos = new FileOutputStream("test1.xls");
    workbook.write(fos);/*from ww  w.ja  v a2s .c o m*/
    fos.flush();
    fos.close();

    System.out.println("OK !");

}

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

License:Open Source License

/**
 * Permet la generation d'un fichier basique avec 3 lignes et 3 colonnes
 *//*from   ww  w  .  j a  v a  2s.com*/
private void generateBasicFile() throws IOException {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Amap");

    HSSFCellStyle style = workbook.createCellStyle();
    style.setWrapText(true);

    addRow(sheet, style, (short) 0);
    addRow(sheet, style, (short) 1);
    addRow(sheet, style, (short) 2);

    FileOutputStream fos = new FileOutputStream("test1.xls");
    workbook.write(fos);
    fos.flush();
    fos.close();

    System.out.println("OK !");

}

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

License:Open Source License

/**
 * Permet la generation d'un fichier basique avec 3 lignes et 3 colonnes
 *//*from ww  w  .j a v  a 2s. co m*/
private void generateFileWithDiagonal() throws Exception {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Amap");

    HSSFCellStyle style = workbook.createCellStyle();
    style.setWrapText(true);

    Field f = HSSFCellStyle.class.getDeclaredField("_format");
    f.setAccessible(true);

    ExtendedFormatRecord efr = (ExtendedFormatRecord) f.get(style);

    efr.setIndentNotParentBorder(true);
    efr.setDiag((short) 3);

    // 8 et 64 semble marcher de facon identique  
    efr.setAdtlDiag((short) 64);
    efr.setAdtlDiagLineStyle((short) 1);

    addRow(sheet, style, (short) 0);
    addRow(sheet, style, (short) 1);
    addRow(sheet, style, (short) 2);

    FileOutputStream fos = new FileOutputStream("test2.xls");
    workbook.write(fos);
    fos.flush();
    fos.close();

    System.out.println("OK !");

}

From source file:gov.nih.nci.evs.reportwriter.formatter.AsciiToExcelFormatter.java

License:BSD License

public Boolean convert(String textfile, String delimiter, String outfile) throws Exception {

    Vector<String> headings = getColumnHeadings(textfile, delimiter);
    Vector<Integer> maxChars = getColumnMaxChars(textfile, delimiter);

    // Note: Special Case for CDISC STDM Terminology report.
    int extensible_col = -1;
    if (_specialCases_CDISC)
        extensible_col = findColumnIndicator(headings, "Extensible");

    int heading_height_multiplier = 1;
    for (int i = 0; i < maxChars.size(); i++) {
        String heading = (String) headings.elementAt(i);
        int maxCellLen = maxChars.elementAt(i);
        int maxTokenLen = getMaxTokenLength(heading);
        if (maxTokenLen > maxCellLen) {
            maxCellLen = maxTokenLen;/*  w ww  . j a  v a 2s . c o m*/
            maxChars.setElementAt(new Integer(maxCellLen), i);
        }
        if (maxCellLen < MAX_CODE_WIDTH) {
            Vector<String> tokens = parseData(heading, " ");
            if (tokens.size() > heading_height_multiplier)
                heading_height_multiplier = tokens.size();
        }
    }

    Boolean[] a = findWrappedColumns(textfile, delimiter, MAX_WIDTH);
    // Note: The max column number allowed in an Excel spreadsheet is 256
    int[] b = new int[255];
    for (int i = 0; i < 255; i++) {
        b[i] = 0;
    }

    File file = new File(textfile);
    String absolutePath = file.getAbsolutePath();
    _logger.debug("Absolute Path: " + absolutePath);
    String filename = file.getName();
    _logger.debug("filename: " + filename);

    int m = filename.indexOf(".");
    String workSheetLabel = filename.substring(0, m);
    int n = workSheetLabel.indexOf("__");
    workSheetLabel = workSheetLabel.substring(0, n);
    _logger.debug("workSheetLabel: " + workSheetLabel);

    if (workSheetLabel.compareTo("") == 0)
        return Boolean.FALSE;

    String pathName = file.getPath();
    _logger.debug("Path: " + pathName);

    BufferedReader br = getBufferReader(textfile);
    FileOutputStream fout = new FileOutputStream(outfile);
    HSSFWorkbook wb = new HSSFWorkbook();

    HSSFSheet ws = wb.createSheet(workSheetLabel);
    HSSFCellStyle toprow = wb.createCellStyle();
    HSSFCellStyle highlightedrow = wb.createCellStyle();

    HSSFCellStyle cs = wb.createCellStyle();

    // Note: GF20673 shade top row
    HSSFFont font = wb.createFont();
    font.setColor(HSSFColor.BLACK.index);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    toprow.setFont(font);

    if (extensible_col == -1) {
        toprow.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    } else {
        //toprow.setFillForegroundColor(HSSFColor.YELLOW.index);
        toprow.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
    }

    toprow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    toprow.setAlignment(HSSFCellStyle.VERTICAL_CENTER);
    toprow.setWrapText(true);

    highlightedrow.setFont(font);
    //highlightedrow.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
    //highlightedrow.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
    highlightedrow.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);

    highlightedrow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    highlightedrow.setAlignment(HSSFCellStyle.VERTICAL_CENTER);
    // highlightedrow.setWrapText(true);

    cs.setWrapText(true);
    // cs.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
    cs.setAlignment(HSSFCellStyle.VERTICAL_TOP);

    HSSFRow wr = null;
    int rownum = 0;
    // int baseline_height = 15;
    int baseline_height = 12;
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        // line = line.trim(); Note: 090512 first value could be empty
        if (line.length() <= 0)
            continue;

        Vector<String> v = parseData(line, delimiter);
        wr = ws.createRow(rownum);
        // wr.setHeightInPoints(60);
        if (rownum == 0) {
            wr.setHeightInPoints(baseline_height * heading_height_multiplier);
        } else {
            wr.setHeightInPoints(baseline_height);
            if (ADJUST_HEIGHT) {
                int num_lines = getHeightInPoints(v, ADJUST_HEIGHT, MAX_CELL_WIDTH);
                wr.setHeightInPoints(baseline_height * num_lines);
            }
        }

        // Note: Special Case for CDISC STDM Terminology report.
        boolean highlight_row = false;
        if (_specialCases_CDISC)
            highlight_row = extensible_col != -1 && v.elementAt(extensible_col).trim().length() > 0;

        for (int i = 0; i < v.size(); i++) {
            HSSFCell wc = wr.createCell(i);
            if (rownum == 0) {
                wc.setCellStyle(toprow);
            } else if (a[i].equals(Boolean.TRUE)) {

                wc.setCellStyle(cs);
                wc.setCellType(HSSFCell.CELL_TYPE_STRING);

                if (highlight_row)
                    wc.setCellStyle(highlightedrow);

            } else {
                if (highlight_row)
                    wc.setCellStyle(highlightedrow);
            }

            String s = (String) v.elementAt(i);
            s = s.trim();

            if (s.length() > b[i]) {
                b[i] = s.length();
            }
            if (s.equals("")) {
                s = null;
            }

            wc.setCellValue(s);
            if (_ncitCodeColumns.contains(i) && rownum > 0 && s != null && s.length() > 0) {
                try {
                    wc.setCellFormula("HYPERLINK(\"" + getNCItCodeUrl(s) + "\", \"" + s + "\")");
                } catch (Exception e) {
                    ExceptionUtils.print(_logger, e, "The following string is too large to be a "
                            + "valid NCIt code (" + filename + "): " + s);
                }
            }
        }
        rownum++;
    }

    br.close();
    for (int i = 0; i < 255; i++) {
        if (b[i] != 0) {
            int multiplier = b[i];
            if (i < headings.size()) {
                Integer int_obj = (Integer) maxChars.elementAt(i);
                multiplier = int_obj.intValue();
            }

            // Note(GF20673): 315 is the magic number for this font and size
            int colWidth = multiplier * 315;

            // Fields like definition run long, some sanity required
            if (colWidth > 20000) {
                colWidth = 20000;
            }
            // _logger.debug("Calculated column width " + i + ": " +
            // colWidth);
            ws.setColumnWidth(i, colWidth);
        }
    }

    // Note(GF20673): Freeze top row
    ws.createFreezePane(0, 1, 0, 1);
    wb.write(fout);
    fout.close();
    return Boolean.TRUE;
}

From source file:is.idega.idegaweb.egov.cases.business.CasesWriter.java

License:Open Source License

public MemoryFileBuffer writeXLS(IWContext iwc, Collection<Case> cases) throws Exception {
    MemoryFileBuffer buffer = new MemoryFileBuffer();
    MemoryOutputStream mos = new MemoryOutputStream(buffer);

    HSSFWorkbook workbook = new HSSFWorkbook();

    short cellColumn = 0;
    HSSFSheet sheet = workbook.createSheet(StringHandler
            .shortenToLength(iwrb.getLocalizedString("cases_fetcher.statistics", "Statistics"), 30));
    sheet.setColumnWidth(cellColumn++, (short) (8 * 256));
    sheet.setColumnWidth(cellColumn++, (short) (14 * 256));
    sheet.setColumnWidth(cellColumn++, (short) (30 * 256));
    sheet.setColumnWidth(cellColumn++, (short) (14 * 256));
    sheet.setColumnWidth(cellColumn++, (short) (18 * 256));
    if (getBusiness(iwc).useTypes()) {
        sheet.setColumnWidth(cellColumn++, (short) (14 * 256));
    }//from   w w  w  . j a  v a2  s  .  c om
    sheet.setColumnWidth(cellColumn++, (short) (14 * 256));
    sheet.setColumnWidth(cellColumn++, (short) (30 * 256));
    sheet.setColumnWidth(cellColumn++, (short) (50 * 256));

    HSSFFont font = workbook.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 12);
    HSSFCellStyle style = workbook.createCellStyle();
    style.setFont(font);

    HSSFCellStyle style2 = workbook.createCellStyle();
    style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
    style2.setWrapText(true);

    int cellRow = 0;
    cellColumn = 0;
    HSSFRow row = sheet.createRow(cellRow++);

    HSSFCell cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("cases_fetcher.case_id", "Case ID"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("created_date", "Created date"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("name", "Name"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("personal_id", "Personal ID"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("case_category", "Case category"));
    cell.setCellStyle(style);

    if (getBusiness(iwc).useTypes()) {
        cell = row.createCell(cellColumn++);
        cell.setCellValue(this.iwrb.getLocalizedString("case_type", "Case type"));
        cell.setCellStyle(style);
    }

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("reference", "Reference"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("status", "Status"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("regarding", "Regarding"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("message", "Message"));
    cell.setCellStyle(style);

    cell = row.createCell(cellColumn++);
    cell.setCellValue(this.iwrb.getLocalizedString("reply", "Reply"));
    cell.setCellStyle(style);

    User currentUser = iwc.getCurrentUser();

    for (Iterator<Case> iter = cases.iterator(); iter.hasNext();) {
        Case theCase = iter.next();
        if (!(theCase instanceof GeneralCase)) {
            continue;
        }

        GeneralCase element = (GeneralCase) theCase;
        CaseCategory category = element.getCaseCategory();
        if (category != null) {
            Group handlerGroup = category.getHandlerGroup();
            if (handlerGroup != null && !currentUser.hasRelationTo(handlerGroup)) {
                continue;
            }
        }
        CaseType type = element.getCaseType();
        CaseStatus status = element.getCaseStatus();
        if (status != null && status.equals(getBusiness(iwc).getCaseStatusDeleted())) {
            continue;
        }
        User user = element.getOwner();
        IWTimestamp created = new IWTimestamp(element.getCreated());

        row = sheet.createRow(cellRow++);
        cellColumn = 0;

        cell = row.createCell(cellColumn++);
        cell.setCellValue(element.getPrimaryKey().toString());
        cell.setCellStyle(style2);

        cell = row.createCell(cellColumn++);
        cell.setCellValue(created.getLocaleDateAndTime(locale, IWTimestamp.SHORT, IWTimestamp.SHORT));
        cell.setCellStyle(style2);

        if (user != null) {
            Name name = new Name(user.getFirstName(), user.getMiddleName(), user.getLastName());
            cell = row.createCell(cellColumn++);
            cell.setCellValue(name.getName(locale));
            cell.setCellStyle(style2);

            cell = row.createCell(cellColumn++);
            cell.setCellValue(PersonalIDFormatter.format(user.getPersonalID(), locale));
            cell.setCellStyle(style2);
        } else {
            cell = row.createCell(cellColumn++);
            cell.setCellValue("");
            cell = row.createCell(cellColumn++);
            cell.setCellValue("");
        }

        cell = row.createCell(cellColumn++);
        cell.setCellValue(category == null ? CoreConstants.EMPTY : category.getLocalizedCategoryName(locale));
        cell.setCellStyle(style2);

        if (type != null && getBusiness(iwc).useTypes()) {
            cell = row.createCell(cellColumn++);
            cell.setCellValue(type.getName());
            cell.setCellStyle(style2);
        }

        cell = row.createCell(cellColumn++);
        cell.setCellValue(element.getReference() != null ? element.getReference() : "");
        cell.setCellStyle(style2);

        cell = row.createCell(cellColumn++);
        cell.setCellValue(status == null ? CoreConstants.MINUS
                : getBusiness(iwc).getLocalizedCaseStatusDescription(element, status, locale));
        cell.setCellStyle(style2);

        cell = row.createCell(cellColumn++);
        cell.setCellValue(element.getSubject() != null ? element.getSubject() : "-");
        cell.setCellStyle(style2);

        cell = row.createCell(cellColumn++);
        cell.setCellValue(element.getMessage());
        cell.setCellStyle(style2);

        Collection<CaseLog> logs = getBusiness(iwc).getCaseLogs(element);
        if (!logs.isEmpty()) {
            for (CaseLog log : logs) {
                cell = row.createCell(cellColumn++);
                cell.setCellValue(log.getComment());
                cell.setCellStyle(style2);
            }
        } else if (element.getReply() != null) {
            cell = row.createCell(cellColumn++);
            cell.setCellValue(element.getReply());
            cell.setCellStyle(style2);
        }
    }

    workbook.write(mos);

    buffer.setMimeType(MimeTypeUtil.MIME_TYPE_EXCEL_2);
    return buffer;
}

From source file:is.idega.idegaweb.egov.cases.business.CasesWriterExtended.java

License:Open Source License

@Override
public MemoryFileBuffer writeXLS(IWContext iwc, Collection cases) throws Exception {
    MemoryFileBuffer buffer = new MemoryFileBuffer();
    MemoryOutputStream mos = new MemoryOutputStream(buffer);

    HSSFWorkbook workbook = new HSSFWorkbook();

    HSSFSheet sheet = workbook.createSheet(StringHandler
            .shortenToLength(iwrb.getLocalizedString("cases_fetcher.statistics", "Statistics"), 30));
    sheet.setColumnWidth((short) 0, (short) (38 * 256));
    sheet.setColumnWidth((short) 1, (short) (85 * 256));

    HSSFFont font = workbook.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 12);

    HSSFCellStyle style = workbook.createCellStyle();
    style.setFont(font);/*  www . jav a 2s . c o  m*/
    HSSFCellStyle style2 = workbook.createCellStyle();
    style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
    style2.setWrapText(true);
    HSSFCellStyle style3 = workbook.createCellStyle();
    style3.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style3.setFont(font);

    User currentUser = iwc.getCurrentUser();

    int cellRow = 0;
    Iterator iter = cases.iterator();
    while (iter.hasNext()) {
        GeneralCase element = (GeneralCase) iter.next();
        CaseCategory category = element.getCaseCategory();
        Group handlerGroup = category.getHandlerGroup();
        if (!currentUser.hasRelationTo(handlerGroup)) {
            continue;
        }
        CaseType type = element.getCaseType();
        CaseStatus status = element.getCaseStatus();
        if (status.equals(getBusiness(iwc).getCaseStatusDeleted())) {
            continue;
        }
        User user = element.getOwner();
        IWTimestamp created = new IWTimestamp(element.getCreated());

        HSSFRow row = sheet.createRow(cellRow++);

        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue(this.iwrb.getLocalizedString("cases_fetcher.case_id", "Case ID"));
        cell.setCellStyle(style);

        cell = row.createCell((short) 1);
        cell.setCellValue(element.getPrimaryKey().toString());

        row = sheet.createRow(cellRow++);

        cell = row.createCell((short) 0);
        cell.setCellValue(this.iwrb.getLocalizedString("created_date", "Created date"));
        cell.setCellStyle(style);

        cell = row.createCell((short) 1);
        cell.setCellValue(created.getLocaleDateAndTime(locale, IWTimestamp.SHORT, IWTimestamp.SHORT));

        if (user != null) {
            row = sheet.createRow(cellRow++);

            cell = row.createCell((short) 0);
            cell.setCellValue(this.iwrb.getLocalizedString("name", "Name"));
            cell.setCellStyle(style);

            Name name = new Name(user.getFirstName(), user.getMiddleName(), user.getLastName());
            cell = row.createCell((short) 1);
            cell.setCellValue(name.getName(locale));

            row = sheet.createRow(cellRow++);

            cell = row.createCell((short) 0);
            cell.setCellValue(this.iwrb.getLocalizedString("personal_id", "Personal ID"));
            cell.setCellStyle(style);

            cell = row.createCell((short) 1);
            cell.setCellValue(PersonalIDFormatter.format(user.getPersonalID(), locale));
        }

        row = sheet.createRow(cellRow++);

        cell = row.createCell((short) 0);
        cell.setCellValue(this.iwrb.getLocalizedString("case_category", "Case category"));
        cell.setCellStyle(style);

        cell = row.createCell((short) 1);
        cell.setCellValue(category.getLocalizedCategoryName(locale));

        if (getBusiness(iwc).useTypes()) {
            row = sheet.createRow(cellRow++);

            cell = row.createCell((short) 0);
            cell.setCellValue(this.iwrb.getLocalizedString("case_type", "Case type"));
            cell.setCellStyle(style);

            cell = row.createCell((short) 1);
            cell.setCellValue(type.getName());
        }

        if (element.getReference() != null) {
            row = sheet.createRow(cellRow++);

            cell = row.createCell((short) 0);
            cell.setCellValue(this.iwrb.getLocalizedString("reference", "Reference"));
            cell.setCellStyle(style);

            cell = row.createCell((short) 1);
            cell.setCellValue(element.getReference());
        }

        row = sheet.createRow(cellRow++);

        cell = row.createCell((short) 0);
        cell.setCellValue(this.iwrb.getLocalizedString("status", "Status"));
        cell.setCellStyle(style);

        cell = row.createCell((short) 1);
        cell.setCellValue(getBusiness(iwc).getLocalizedCaseStatusDescription(element, status, locale));

        row = sheet.createRow(cellRow++);

        cell = row.createCell((short) 0);
        cell.setCellValue(this.iwrb.getLocalizedString("regarding", "Regarding"));
        cell.setCellStyle(style);

        cell = row.createCell((short) 1);
        cell.setCellValue(element.getSubject() != null ? element.getSubject() : "-");

        row = sheet.createRow(cellRow++);
        row = sheet.createRow(cellRow++);

        cell = row.createCell((short) 0);
        cell.setCellValue(this.iwrb.getLocalizedString("message", "Message"));
        cell.setCellStyle(style3);

        cell = row.createCell((short) 1);
        cell.setCellValue(element.getMessage());
        cell.setCellStyle(style2);

        if (element.getReply() != null) {
            row = sheet.createRow(cellRow++);

            cell = row.createCell((short) 0);
            cell.setCellValue(this.iwrb.getLocalizedString("reply", "Reply"));
            cell.setCellStyle(style3);

            cell = row.createCell((short) 1);
            cell.setCellValue(element.getReply());
            cell.setCellStyle(style2);
        }
    }

    workbook.write(mos);

    buffer.setMimeType(MimeTypeUtil.MIME_TYPE_EXCEL_2);
    return buffer;
}

From source file:mat.server.service.impl.XLSGenerator.java

/** Adds the disclaimer.
 * /*  w  ww.  j  ava 2 s. c  o m*/
 * @param wkbk - HSSFWorkbook. * */
protected final void addDisclaimer(final HSSFWorkbook wkbk) {
    String disclaimerText = "The codes that you are exporting directly reflect the codes you entered into the "
            + "Measure Authoring Tool.  These codes may be owned by a third party and "
            + "subject to copyright or other intellectual property restrictions.  Use of these "
            + "codes may require permission from the code owner or agreement to a license.  "
            + "It is your responsibility to ensure that your use of any third party code is "
            + "permissible and that you have fulfilled any notice or license requirements "
            + "imposed by the code owner.  Use of the Measure Authoring Tool does not "
            + "confer any rights on you with respect to these codes other than those codes that may "
            + "be available from the code owner.";
    HSSFSheet wkst = wkbk.createSheet("Disclaimer");
    HSSFRow row = wkst.createRow(0);
    row.createCell(0, HSSFCell.CELL_TYPE_STRING).setCellValue(disclaimerText);
    wkst.setColumnWidth(0, (75 * 256));
    HSSFCell cell = row.getCell(0);
    HSSFCellStyle style = wkbk.createCellStyle();
    style.setWrapText(true);
    cell.setCellStyle(style);
}