Example usage for org.apache.poi.ss.usermodel CellStyle setFont

List of usage examples for org.apache.poi.ss.usermodel CellStyle setFont

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel CellStyle setFont.

Prototype

void setFont(Font font);

Source Link

Document

set the font for this style

Usage

From source file:it.eng.spagobi.engines.worksheet.exporter.WorkSheetXLSExporter.java

License:Mozilla Public License

public CellStyle buildMetadataTitleCellStyle(Sheet sheet) {
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    cellStyle.setWrapText(true);/*w ww. ja  va2s .co  m*/
    Font font = sheet.getWorkbook().createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints(METADATA_TITLE_FONT_SIZE);
    font.setFontName(FONT_NAME);
    cellStyle.setFont(font);
    return cellStyle;
}

From source file:it.eng.spagobi.engines.worksheet.exporter.WorkSheetXLSExporter.java

License:Mozilla Public License

public CellStyle buildMetadataNameCellStyle(Sheet sheet) {
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    cellStyle.setWrapText(true);/*from  w w  w . jav a  2 s.c o  m*/
    Font font = sheet.getWorkbook().createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints(METADATA_NAME_FONT_SIZE);
    font.setFontName(FONT_NAME);
    cellStyle.setFont(font);
    return cellStyle;
}

From source file:it.eng.spagobi.engines.worksheet.exporter.WorkSheetXLSExporter.java

License:Mozilla Public License

public CellStyle buildMetadataValueCellStyle(Sheet sheet) {
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    cellStyle.setWrapText(true);/*from   www . j a v  a2s.c om*/
    Font font = sheet.getWorkbook().createFont();
    font.setFontHeightInPoints(METADATA_VALUE_FONT_SIZE);
    font.setFontName(FONT_NAME);
    cellStyle.setFont(font);
    return cellStyle;
}

From source file:it.eng.spagobi.engines.worksheet.exporter.WorkSheetXLSExporter.java

License:Mozilla Public License

public CellStyle buildFiltersTitleCellStyle(Sheet sheet) {
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyle.setWrapText(false);/*w  w w.  j ava2  s  .  c om*/
    Font font = sheet.getWorkbook().createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints(FILTERS_TITLE_FONT_SIZE);
    font.setFontName(FONT_NAME);
    cellStyle.setFont(font);
    return cellStyle;
}

From source file:it.eng.spagobi.engines.worksheet.exporter.WorkSheetXLSExporter.java

License:Mozilla Public License

public CellStyle buildFiltersValuesCellStyle(Sheet sheet) {
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyle.setWrapText(false);/*from  w ww. ja  va  2s  . c o m*/
    Font font = sheet.getWorkbook().createFont();
    font.setFontHeightInPoints(FILTERS_VALUES_FONT_SIZE);
    font.setFontName(FONT_NAME);
    cellStyle.setFont(font);
    return cellStyle;
}

From source file:javaapp.generateAnomolies.java

public static void generateAnomolyReport() throws IOException {

    XSSFWorkbook workbook = new XSSFWorkbook();

    HashMap<String, List<String>> hmd = new HashMap<String, List<String>>();
    HashMap<String, List<String>> hmc = new HashMap<String, List<String>>();
    HashMap<String, List<String>> uhmd = new HashMap<String, List<String>>();
    HashMap<String, List<String>> uhmc = new HashMap<String, List<String>>();

    hmd = getAnomolies("transrec", "Debtors", 0);
    hmc = getAnomolies("ctransrec", "Creditors", 1);
    uhmd = getAnomoliesUninv("uninv", "Uninv_Debtors", 2);
    uhmc = getAnomoliesUninv("cuninv", "Uninv_Creditors", 3);

    List ls;//from w w w.  jav  a  2  s.  c om
    List ls2, ls3, ls4;

    Font font = workbook.createFont();
    font.setFontHeightInPoints((short) 12);
    font.setFontName("Cambria");

    Font hfont = workbook.createFont();
    hfont.setFontHeightInPoints((short) 12);
    hfont.setFontName("Cambria");

    CellStyle style = workbook.createCellStyle();
    CellStyle hstyle = workbook.createCellStyle();

    style.setFont(font);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    hstyle.setFont(font);
    hstyle.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
    hstyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

    //System.out.println(hm);
    XSSFSheet sheet = workbook.createSheet("Debtors");
    XSSFSheet sheet2 = workbook.createSheet("Creditors");
    XSSFSheet sheet3 = workbook.createSheet("Uninv_Debtors");
    XSSFSheet sheet4 = workbook.createSheet("Uninv_Creditors");

    Iterator iterator = hmd.keySet().iterator();

    int rowCount = 0;
    Row row = sheet.createRow(0);
    Cell hcell = row.createCell(1);
    hcell.setCellValue((String) "RPPS");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(2);
    hcell.setCellValue((String) "SVC");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(3);
    hcell.setCellValue((String) "OPEN");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(4);
    hcell.setCellValue((String) "RINVOICE");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(5);
    hcell.setCellValue((String) "CORRECTION");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(6);
    hcell.setCellValue((String) "ADJUST");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(7);
    hcell.setCellValue((String) "O1C");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(8);
    hcell.setCellValue((String) "SETTLED");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(9);
    hcell.setCellValue((String) "ALLOC");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(10);
    hcell.setCellValue((String) "WRITEOFF");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(11);
    hcell.setCellValue((String) "CLOSE");
    hcell.setCellStyle(hstyle);
    hcell = row.createCell(12);
    hcell.setCellValue((String) "RECDIFF");
    hcell.setCellStyle(hstyle);

    while (iterator.hasNext()) {

        row = sheet.createRow(++rowCount);
        int columnCount = 0;
        String field = "";

        String key = iterator.next().toString();
        field = key;
        Cell cell = row.createCell(++columnCount);

        if (field instanceof String) {
            cell.setCellValue((String) field);
            cell.setCellStyle(style);
        }

        //System.out.println(hm.get(key));
        ls = (List<String>) hmd.get(key);
        System.out.println(ls);
        Iterator<String> ite = ls.iterator();
        while (ite.hasNext()) {
            field = ite.next();
            //System.out.println( ite.next() );
            cell = row.createCell(++columnCount);
            if (field instanceof String) {
                cell.setCellValue((String) field);
            }

            cell.setCellStyle(style);

        }

    }

    Iterator iterator2 = hmc.keySet().iterator();
    rowCount = 0;

    while (iterator2.hasNext()) {

        row = sheet2.createRow(++rowCount);
        int columnCount = 0;
        String field = "";

        String key = iterator2.next().toString();
        field = key;
        Cell cell = row.createCell(++columnCount);
        if (field instanceof String) {
            cell.setCellValue((String) field);
            cell.setCellStyle(style);
        }

        //System.out.println(hm.get(key));
        ls2 = (List<String>) hmc.get(key);
        System.out.println(ls2);
        Iterator<String> ite = ls2.iterator();
        while (ite.hasNext()) {
            field = ite.next();
            //System.out.println( ite.next() );
            cell = row.createCell(++columnCount);
            if (field instanceof String) {
                cell.setCellValue((String) field);
                cell.setCellStyle(style);
            }

        }

    }

    // uninv debtors

    Iterator iterator3 = uhmd.keySet().iterator();
    rowCount = 0;

    while (iterator3.hasNext()) {

        row = sheet3.createRow(++rowCount);
        int columnCount = 0;
        String field = "";

        String key = iterator3.next().toString();
        field = key;
        Cell cell = row.createCell(++columnCount);
        if (field instanceof String) {
            cell.setCellValue((String) field);
            cell.setCellStyle(style);
        }

        //System.out.println(hm.get(key));
        ls3 = (List<String>) hmc.get(key);
        System.out.println(ls3);
        Iterator<String> ite = ls3.iterator();
        while (ite.hasNext()) {
            field = ite.next();
            //System.out.println( ite.next() );
            cell = row.createCell(++columnCount);
            if (field instanceof String) {
                cell.setCellValue((String) field);
                cell.setCellStyle(style);
            }

        }

    }

    // uninv creditors

    Iterator iterator4 = uhmc.keySet().iterator();
    rowCount = 0;

    while (iterator4.hasNext()) {

        row = sheet4.createRow(++rowCount);
        int columnCount = 0;
        String field = "";

        String key = iterator4.next().toString();
        field = key;
        Cell cell = row.createCell(++columnCount);
        if (field instanceof String) {
            cell.setCellValue((String) field);
            cell.setCellStyle(style);
        }

        //System.out.println(hm.get(key));
        ls4 = (List<String>) uhmc.get(key);
        System.out.println(ls4);
        Iterator<String> ite = ls4.iterator();
        while (ite.hasNext()) {
            field = ite.next();
            //System.out.println( ite.next() );
            cell = row.createCell(++columnCount);
            if (field instanceof String) {
                cell.setCellValue((String) field);
                cell.setCellStyle(style);
            }

        }

    }
    /*
    Object[][] bookData = {
        {"Head First Java", "Kathy Serria", 79},
        {"Effective Java", "Joshua Bloch", 36},
        {"Clean Code", "Robert martin", 42},
        {"Thinking in Java", "Bruce Eckel", 35},
    };
            
            
            
            
            
     //int rowCount = 0;
    for (Object[] aBook : bookData) {
    Row row = sheet.createRow(++rowCount);
             
    int columnCount = 0;
             
    for (Object field : aBook) {
        Cell cell = row.createCell(++columnCount);
        if (field instanceof String) {
            cell.setCellValue((String) field);
        } else if (field instanceof Integer) {
            cell.setCellValue((Integer) field);
        }
    }
             
    }
            
    */
    // workbook.setSheetName(n, WorkbookUtil.createSafeSheetName("Debtors"));
    try (FileOutputStream outputStream = new FileOutputStream("anomolies/GBRCN_Anomolies_27April.xlsx")) {
        workbook.write(outputStream);
    }

}

From source file:jdbreport.model.io.xls.poi.Excel2003Writer.java

License:Apache License

protected CellStyle createStyle(jdbreport.model.CellStyle style, Workbook wb) {

    CellStyle newStyle = wb.createCellStyle();
    newStyle.setAlignment(convertHorizontalAlign(style.getHorizontalAlignment()));
    newStyle.setVerticalAlignment(convertVerticalAlign(style.getVerticalAlignment()));

    Border border = style.getBorders(Border.LINE_BOTTOM);
    if (border != null) {
        newStyle.setBorderBottom(getBorder(border));
        newStyle.setBottomBorderColor(colorToIndex(wb, border.getColor()));
    }//from www  .j  ava 2  s  .co  m
    border = style.getBorders(Border.LINE_TOP);
    if (border != null) {
        newStyle.setBorderTop(getBorder(border));
        newStyle.setTopBorderColor(colorToIndex(wb, border.getColor()));
    }
    border = style.getBorders(Border.LINE_LEFT);
    if (border != null) {
        newStyle.setBorderLeft(getBorder(border));
        newStyle.setLeftBorderColor(colorToIndex(wb, border.getColor()));
    }
    border = style.getBorders(Border.LINE_RIGHT);
    if (border != null) {
        newStyle.setBorderRight(getBorder(border));
        newStyle.setRightBorderColor(colorToIndex(wb, border.getColor()));
    }

    Font font = wb.createFont();
    font.setFontName(style.getFamily());
    if (style.isBold()) {
        font.setBold(true);
    }
    font.setItalic(style.isItalic());
    if (style.isUnderline()) {
        font.setUnderline(Font.U_SINGLE);
    }
    if (style.isStrikethrough()) {
        font.setStrikeout(true);
    }
    font.setFontHeightInPoints((short) style.getSize());
    if (style.getForegroundColor() != null && !style.getForegroundColor().equals(Color.black)) {
        font.setColor(colorToIndex(wb, style.getForegroundColor()));
    }

    newStyle.setFont(font);

    if (style.getBackground() != null && !style.getBackground().equals(Color.white)) {
        short colorIndex = colorToIndex(wb, style.getBackground());
        newStyle.setFillForegroundColor(colorIndex);
        newStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    }

    if (style.getAngle() != 0) {
        int angle = style.getAngle();
        if (angle > 90 && angle <= 180) {
            angle = 90;
        } else if (angle > 180 && angle <= 270) {
            angle = -90;
        } else if (angle > 270) {
            angle = -(360 - angle);
        }
        newStyle.setRotation((short) angle);
    }

    newStyle.setWrapText(style.isWrapLine());

    return newStyle;
}

From source file:jgnash.convert.exportantur.ssf.AccountExport.java

License:Open Source License

public static void exportAccount(final Account account, final String[] columnNames, final LocalDate startDate,
        final LocalDate endDate, final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);
    Objects.requireNonNull(columnNames);

    final String extension = FileUtils.getFileExtension(file.getAbsolutePath());

    try (final Workbook wb = extension.equals("xlsx") ? new XSSFWorkbook() : new HSSFWorkbook()) {
        final CreationHelper createHelper = wb.getCreationHelper();

        // create a new sheet
        final Sheet s = wb.createSheet(account.getName());

        // create 2 fonts objects
        final Font defaultFont = wb.createFont();
        final Font headerFont = wb.createFont();

        defaultFont.setFontHeightInPoints((short) 10);
        defaultFont.setColor(IndexedColors.BLACK.getIndex());

        headerFont.setFontHeightInPoints((short) 11);
        headerFont.setColor(IndexedColors.BLACK.getIndex());
        headerFont.setBold(true);/* w  w  w  .j  av a2s .co  m*/

        // create header cell styles
        final CellStyle headerStyle = wb.createCellStyle();

        // Set the other cell style and formatting
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        DataFormat df_header = wb.createDataFormat();

        headerStyle.setDataFormat(df_header.getFormat("text"));
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);

        final CellStyle dateStyle = wb.createCellStyle();
        dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm/dd/yy"));
        dateStyle.setFont(defaultFont);

        final CellStyle timestampStyle = wb.createCellStyle();
        timestampStyle.setDataFormat(createHelper.createDataFormat().getFormat("YYYY-MM-DD HH:MM:SS"));
        timestampStyle.setFont(defaultFont);

        final CellStyle textStyle = wb.createCellStyle();
        textStyle.setFont(defaultFont);

        final CellStyle amountStyle = wb.createCellStyle();
        amountStyle.setFont(defaultFont);
        amountStyle.setAlignment(HorizontalAlignment.RIGHT);

        final DecimalFormat format = (DecimalFormat) NumericFormats
                .getFullCommodityFormat(account.getCurrencyNode());
        final String pattern = format.toLocalizedPattern().replace("", account.getCurrencyNode().getPrefix());
        final DataFormat df = wb.createDataFormat();
        amountStyle.setDataFormat(df.getFormat(pattern));

        // Create headers
        int row = 0;
        Row r = s.createRow(row);
        for (int i = 0; i < columnNames.length; i++) {
            Cell c = r.createCell(i);
            c.setCellValue(createHelper.createRichTextString(columnNames[i]));
            c.setCellStyle(headerStyle);
        }

        // Dump the transactions
        for (final Transaction transaction : account.getTransactions(startDate, endDate)) {
            r = s.createRow(++row);

            int col = 0;

            // date
            Cell c = r.createCell(col, CellType.STRING);
            c.setCellValue(DateUtils.asDate(transaction.getLocalDate()));
            c.setCellStyle(dateStyle);

            // timestamp
            c = r.createCell(++col, CellType.STRING);
            c.setCellValue(DateUtils.asDate(transaction.getTimestamp()));
            c.setCellStyle(timestampStyle);

            // number
            c = r.createCell(++col, CellType.STRING);
            c.setCellValue(transaction.getNumber());
            c.setCellStyle(textStyle);

            // payee
            c = r.createCell(++col, CellType.STRING);
            c.setCellValue(transaction.getPayee());
            c.setCellStyle(textStyle);

            // memo
            c = r.createCell(++col, CellType.STRING);
            c.setCellValue(transaction.getMemo());
            c.setCellStyle(textStyle);

            // account
            c = r.createCell(++col, CellType.STRING);
            c.setCellValue(getAccountColumnValue(transaction, account));
            c.setCellStyle(textStyle);

            // clr, strip any zero width spaces
            c = r.createCell(++col, CellType.STRING);
            c.setCellValue(transaction.getReconciled(account).toString().replaceAll(ZERO_WIDTH_SPACE, ""));
            c.setCellStyle(textStyle);

            final BigDecimal amount = transaction.getAmount(account);

            // increase
            c = r.createCell(++col, CellType.NUMERIC);
            if (amount.signum() >= 0) {
                c.setCellValue(amount.doubleValue());
            }
            c.setCellStyle(amountStyle);

            // decrease
            c = r.createCell(++col, CellType.NUMERIC);
            if (amount.signum() < 0) {
                c.setCellValue(amount.abs().doubleValue());
            }
            c.setCellStyle(amountStyle);

            // balance
            c = r.createCell(++col, CellType.NUMERIC);
            c.setCellValue(account.getBalanceAt(transaction).doubleValue());
            c.setCellStyle(amountStyle);
        }

        // autosize the column widths
        final short columnCount = s.getRow(1).getLastCellNum();

        // autosize all of the columns + 10 pixels
        for (int i = 0; i <= columnCount; i++) {
            s.autoSizeColumn(i);
            s.setColumnWidth(i, s.getColumnWidth(i) + 10);
        }

        Logger.getLogger(AccountExport.class.getName()).log(Level.INFO, "{0} cell styles were used",
                wb.getNumCellStyles());

        // Save
        final String filename;

        if (wb instanceof XSSFWorkbook) {
            filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xlsx";
        } else {
            filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xls";
        }

        try (final OutputStream out = Files.newOutputStream(Paths.get(filename))) {
            wb.write(out);
        } catch (final Exception e) {
            Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
        }

    } catch (final IOException e) {
        Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:jgnash.convert.exports.ssf.AccountExport.java

License:Open Source License

public static void exportAccount(final Account account, final String[] columnNames, final LocalDate startDate,
        final LocalDate endDate, final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);
    Objects.requireNonNull(columnNames);

    final String extension = FileUtils.getFileExtension(file.getAbsolutePath());

    try (final Workbook wb = extension.equals("xlsx") ? new XSSFWorkbook() : new HSSFWorkbook()) {
        final CreationHelper createHelper = wb.getCreationHelper();

        // create a new sheet
        final Sheet s = wb.createSheet(account.getName());

        // create 2 fonts objects
        final Font defaultFont = wb.createFont();
        final Font headerFont = wb.createFont();

        defaultFont.setFontHeightInPoints((short) 10);
        defaultFont.setColor(IndexedColors.BLACK.getIndex());

        headerFont.setFontHeightInPoints((short) 11);
        headerFont.setColor(IndexedColors.BLACK.getIndex());
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

        // create header cell styles
        final CellStyle headerStyle = wb.createCellStyle();

        // Set the other cell style and formatting
        headerStyle.setBorderBottom(CellStyle.BORDER_THIN);
        headerStyle.setBorderTop(CellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(CellStyle.BORDER_THIN);
        headerStyle.setBorderRight(CellStyle.BORDER_THIN);
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

        DataFormat df_header = wb.createDataFormat();

        headerStyle.setDataFormat(df_header.getFormat("text"));
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);

        final CellStyle dateStyle = wb.createCellStyle();
        dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm/dd/yy"));
        dateStyle.setFont(defaultFont);/*from  w  ww.  j  a va  2s.c om*/

        final CellStyle textStyle = wb.createCellStyle();
        textStyle.setFont(defaultFont);

        final CellStyle amountStyle = wb.createCellStyle();
        amountStyle.setFont(defaultFont);
        amountStyle.setAlignment(CellStyle.ALIGN_RIGHT);

        final DecimalFormat format = (DecimalFormat) CommodityFormat
                .getFullNumberFormat(account.getCurrencyNode());
        final String pattern = format.toLocalizedPattern().replace("", account.getCurrencyNode().getPrefix());
        final DataFormat df = wb.createDataFormat();
        amountStyle.setDataFormat(df.getFormat(pattern));

        // Create headers
        int row = 0;
        Row r = s.createRow(row);
        for (int i = 0; i < columnNames.length; i++) {
            Cell c = r.createCell(i);
            c.setCellValue(createHelper.createRichTextString(columnNames[i]));
            c.setCellStyle(headerStyle);
        }

        // Dump the transactions
        for (final Transaction transaction : account.getTransactions(startDate, endDate)) {
            r = s.createRow(++row);

            int col = 0;

            // date
            Cell c = r.createCell(col);
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue(DateUtils.asDate(transaction.getLocalDate()));
            c.setCellStyle(dateStyle);

            // number
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue(transaction.getNumber());
            c.setCellStyle(textStyle);

            // payee
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue(transaction.getPayee());
            c.setCellStyle(textStyle);

            // memo
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue(transaction.getMemo());
            c.setCellStyle(textStyle);

            // account
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue(getAccountColumnValue(transaction, account));
            c.setCellStyle(textStyle);

            // clr
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue(transaction.getReconciled(account).toString());
            c.setCellStyle(textStyle);

            final BigDecimal amount = transaction.getAmount(account);

            // increase
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            if (amount.signum() >= 0) {
                c.setCellValue(amount.doubleValue());
            }
            c.setCellStyle(amountStyle);

            // decrease
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            if (amount.signum() < 0) {
                c.setCellValue(amount.abs().doubleValue());
            }
            c.setCellStyle(amountStyle);

            // balance
            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            c.setCellValue(account.getBalanceAt(transaction).doubleValue());
            c.setCellStyle(amountStyle);
        }

        // autosize the column widths
        final short columnCount = s.getRow(1).getLastCellNum();

        // autosize all of the columns + 10 pixels
        for (int i = 0; i <= columnCount; i++) {
            s.autoSizeColumn(i);
            s.setColumnWidth(i, s.getColumnWidth(i) + 10);
        }

        Logger.getLogger(AccountExport.class.getName()).log(Level.INFO, "{0} cell styles were used",
                wb.getNumCellStyles());

        // Save
        final String filename;

        if (wb instanceof XSSFWorkbook) {
            filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xlsx";
        } else {
            filename = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".xls";
        }

        try (final FileOutputStream out = new FileOutputStream(filename)) {
            wb.write(out);
        } catch (final Exception e) {
            Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
        }

    } catch (IOException e) {
        Logger.getLogger(AccountExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:jgnash.engine.budget.BudgetResultsExport.java

License:Open Source License

public static void exportBudgetResultsModel(final File file, final BudgetResultsModel model) {

    Resource rb = Resource.get();

    Workbook wb;//from www .jav a 2  s. c om

    String extension = FileUtils.getFileExtension(file.getAbsolutePath());

    if (extension.equals("xlsx")) {
        wb = new XSSFWorkbook();
    } else {
        wb = new HSSFWorkbook();
    }

    CreationHelper createHelper = wb.getCreationHelper();

    // create a new sheet
    Sheet s = wb.createSheet(model.getBudget().getName());

    // create header cell styles
    CellStyle headerStyle = wb.createCellStyle();

    // create 2 fonts objects
    Font amountFont = wb.createFont();
    Font headerFont = wb.createFont();

    amountFont.setFontHeightInPoints((short) 10);
    amountFont.setColor(IndexedColors.BLACK.getIndex());

    headerFont.setFontHeightInPoints((short) 11);
    headerFont.setColor(IndexedColors.BLACK.getIndex());
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

    DataFormat df = wb.createDataFormat();

    // Set the other cell style and formatting
    headerStyle.setBorderBottom(CellStyle.BORDER_THIN);
    headerStyle.setBorderTop(CellStyle.BORDER_THIN);
    headerStyle.setBorderLeft(CellStyle.BORDER_THIN);
    headerStyle.setBorderRight(CellStyle.BORDER_THIN);
    headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

    headerStyle.setDataFormat(df.getFormat("text"));
    headerStyle.setFont(headerFont);
    headerStyle.setAlignment(CellStyle.ALIGN_CENTER);

    int row = 0;
    Row r = s.createRow(row);

    // create period headers
    for (int i = 0; i < model.getDescriptorList().size(); i++) {
        Cell c = r.createCell(i * 3 + 1);
        c.setCellValue(
                createHelper.createRichTextString(model.getDescriptorList().get(i).getPeriodDescription()));
        c.setCellStyle(headerStyle);
        s.addMergedRegion(new CellRangeAddress(row, row, i * 3 + 1, i * 3 + 3));
    }

    {
        int col = model.getDescriptorList().size() * 3 + 1;
        Cell c = r.createCell(col);
        c.setCellValue(createHelper.createRichTextString(rb.getString("Title.Summary")));
        c.setCellStyle(headerStyle);
        s.addMergedRegion(new CellRangeAddress(row, row, col, col + 2));
    }

    // create results header columns
    row++;
    r = s.createRow(row);

    {
        Cell c = r.createCell(0);
        c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Account")));
        c.setCellStyle(headerStyle);

        for (int i = 0; i <= model.getDescriptorList().size(); i++) {
            c = r.createCell(i * 3 + 1);
            c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Budgeted")));
            c.setCellStyle(headerStyle);

            c = r.createCell(i * 3 + 2);
            c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Change")));
            c.setCellStyle(headerStyle);

            c = r.createCell(i * 3 + 3);
            c.setCellValue(createHelper.createRichTextString(rb.getString("Column.Remaining")));
            c.setCellStyle(headerStyle);
        }
    }

    // must sort the accounts, otherwise child structure is not correct
    List<Account> accounts = new ArrayList<>(model.getAccounts());
    Collections.sort(accounts);

    // create account rows
    for (Account account : accounts) {

        CellStyle amountStyle = wb.createCellStyle();
        amountStyle.setFont(amountFont);

        DecimalFormat format = (DecimalFormat) CommodityFormat.getFullNumberFormat(account.getCurrencyNode());
        String pattern = format.toLocalizedPattern().replace("", account.getCurrencyNode().getPrefix());
        amountStyle.setDataFormat(df.getFormat(pattern));

        row++;

        int col = 0;

        r = s.createRow(row);

        CellStyle cs = wb.createCellStyle();
        cs.cloneStyleFrom(headerStyle);
        cs.setAlignment(CellStyle.ALIGN_LEFT);
        cs.setIndention((short) (model.getDepth(account) * 2));

        Cell c = r.createCell(col);
        c.setCellValue(createHelper.createRichTextString(account.getName()));
        c.setCellStyle(cs);

        List<CellReference> budgetedRefList = new ArrayList<>();
        List<CellReference> changeRefList = new ArrayList<>();
        List<CellReference> remainingRefList = new ArrayList<>();

        for (int i = 0; i < model.getDescriptorList().size(); i++) {

            BudgetPeriodResults results = model.getResults(model.getDescriptorList().get(i), account);

            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            c.setCellValue(results.getBudgeted().doubleValue());
            c.setCellStyle(amountStyle);

            CellReference budgetedRef = new CellReference(row, col);
            budgetedRefList.add(budgetedRef);

            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            c.setCellValue(results.getChange().doubleValue());
            c.setCellStyle(amountStyle);

            CellReference changeRef = new CellReference(row, col);
            changeRefList.add(changeRef);

            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_FORMULA);
            c.setCellStyle(amountStyle);
            c.setCellFormula(budgetedRef.formatAsString() + "-" + changeRef.formatAsString());

            CellReference remainingRef = new CellReference(row, col);
            remainingRefList.add(remainingRef);
        }

        // add summary columns                               
        addSummaryCell(r, ++col, budgetedRefList, amountStyle);
        addSummaryCell(r, ++col, changeRefList, amountStyle);
        addSummaryCell(r, ++col, remainingRefList, amountStyle);
    }

    // add group summary rows
    for (AccountGroup group : model.getAccountGroupList()) {

        CellStyle amountStyle = wb.createCellStyle();
        amountStyle.setFont(amountFont);
        amountStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        amountStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        amountStyle.setBorderBottom(CellStyle.BORDER_THIN);
        amountStyle.setBorderTop(CellStyle.BORDER_THIN);
        amountStyle.setBorderLeft(CellStyle.BORDER_THIN);
        amountStyle.setBorderRight(CellStyle.BORDER_THIN);

        DecimalFormat format = (DecimalFormat) CommodityFormat.getFullNumberFormat(model.getBaseCurrency());
        String pattern = format.toLocalizedPattern().replace("", model.getBaseCurrency().getPrefix());
        amountStyle.setDataFormat(df.getFormat(pattern));

        row++;

        int col = 0;

        r = s.createRow(row);

        CellStyle cs = wb.createCellStyle();
        cs.cloneStyleFrom(headerStyle);
        cs.setAlignment(CellStyle.ALIGN_LEFT);

        Cell c = r.createCell(col);
        c.setCellValue(createHelper.createRichTextString(group.toString()));
        c.setCellStyle(cs);

        List<CellReference> budgetedRefList = new ArrayList<>();
        List<CellReference> changeRefList = new ArrayList<>();
        List<CellReference> remainingRefList = new ArrayList<>();

        for (int i = 0; i < model.getDescriptorList().size(); i++) {

            BudgetPeriodResults results = model.getResults(model.getDescriptorList().get(i), group);

            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            c.setCellValue(results.getBudgeted().doubleValue());
            c.setCellStyle(amountStyle);

            CellReference budgetedRef = new CellReference(row, col);
            budgetedRefList.add(budgetedRef);

            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            c.setCellValue(results.getChange().doubleValue());
            c.setCellStyle(amountStyle);

            CellReference changeRef = new CellReference(row, col);
            changeRefList.add(changeRef);

            c = r.createCell(++col);
            c.setCellType(Cell.CELL_TYPE_FORMULA);
            c.setCellStyle(amountStyle);
            c.setCellFormula(budgetedRef.formatAsString() + "-" + changeRef.formatAsString());

            CellReference remainingRef = new CellReference(row, col);
            remainingRefList.add(remainingRef);
        }

        // add summary columns                               
        addSummaryCell(r, ++col, budgetedRefList, amountStyle);
        addSummaryCell(r, ++col, changeRefList, amountStyle);
        addSummaryCell(r, ++col, remainingRefList, amountStyle);
    }

    // force evaluation
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
    evaluator.evaluateAll();

    short columnCount = s.getRow(1).getLastCellNum();

    // autosize all of the columns + 10 pixels
    for (int i = 0; i <= columnCount; i++) {
        s.autoSizeColumn(i);
        s.setColumnWidth(i, s.getColumnWidth(i) + 10);
    }

    // Save
    String filename = file.getAbsolutePath();

    if (wb instanceof XSSFWorkbook) {
        filename = FileUtils.stripFileExtension(filename) + ".xlsx";
    } else {
        filename = FileUtils.stripFileExtension(filename) + ".xls";
    }

    try (FileOutputStream out = new FileOutputStream(filename)) {
        wb.write(out);
    } catch (Exception e) {
        Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}