Search in sources :

Example 61 with CellReference

use of org.apache.poi.ss.util.CellReference in project jgnash by ccavanaugh.

the class BudgetResultsExport method exportBudgetResultsModel.

/**
     * Exports a {@code BudgetResultsModel} to a spreadsheet.
     * 
     * @param file File to save to
     * @param model Results model to export
     * @return Error message
     */
public static String exportBudgetResultsModel(final Path file, final BudgetResultsModel model) {
    String message = null;
    final ResourceBundle rb = ResourceUtils.getBundle();
    final String extension = FileUtils.getFileExtension(file.toString());
    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(model.getBudget().getName());
        // create header cell styles
        final CellStyle headerStyle = wb.createCellStyle();
        // create 2 fonts objects
        final Font amountFont = wb.createFont();
        final 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);
        // 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);
        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.Actual")));
                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());
        accounts.sort(Comparators.getAccountByTreePosition(Comparators.getAccountByCode()));
        // create account rows
        for (final Account account : accounts) {
            final DataFormat df = wb.createDataFormat();
            final DecimalFormat format = (DecimalFormat) CommodityFormat.getFullNumberFormat(account.getCurrencyNode());
            final String pattern = format.toLocalizedPattern().replace("¤", account.getCurrencyNode().getPrefix());
            final CellStyle amountStyle = wb.createCellStyle();
            amountStyle.setFont(amountFont);
            amountStyle.setDataFormat(df.getFormat(pattern));
            // Sets cell indentation, only impacts display if users changes the cell formatting to be left aligned.
            amountStyle.setIndention((short) (model.getDepth(account) * 2));
            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 (final AccountGroup group : model.getAccountGroupList()) {
            final DataFormat df = wb.createDataFormat();
            final 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);
            final DecimalFormat format = (DecimalFormat) CommodityFormat.getFullNumberFormat(model.getBaseCurrency());
            final 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);
        }
        Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.INFO, "{0} cell styles were used", wb.getNumCellStyles());
        // Save
        String filename = file.toString();
        if (wb instanceof XSSFWorkbook) {
            filename = FileUtils.stripFileExtension(filename) + ".xlsx";
        } else {
            filename = FileUtils.stripFileExtension(filename) + ".xls";
        }
        try (final OutputStream out = Files.newOutputStream(Paths.get(filename))) {
            wb.write(out);
        } catch (final Exception e) {
            Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
            message = e.getLocalizedMessage();
        }
    } catch (IOException e) {
        Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
    return message;
}
Also used : Account(jgnash.engine.Account) DecimalFormat(java.text.DecimalFormat) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) CellReference(org.apache.poi.ss.util.CellReference) Font(org.apache.poi.ss.usermodel.Font) DataFormat(org.apache.poi.ss.usermodel.DataFormat) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Cell(org.apache.poi.ss.usermodel.Cell) CreationHelper(org.apache.poi.ss.usermodel.CreationHelper) IOException(java.io.IOException) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Workbook(org.apache.poi.ss.usermodel.Workbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) IOException(java.io.IOException) AccountGroup(jgnash.engine.AccountGroup) ResourceBundle(java.util.ResourceBundle) CellStyle(org.apache.poi.ss.usermodel.CellStyle) Row(org.apache.poi.ss.usermodel.Row) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress) Sheet(org.apache.poi.ss.usermodel.Sheet) FormulaEvaluator(org.apache.poi.ss.usermodel.FormulaEvaluator)

Example 62 with CellReference

use of org.apache.poi.ss.util.CellReference in project timbuctoo by HuygensING.

the class SheetXmlParser method startElement.

@Override
public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) throws SAXException {
    if (uri != null && !uri.equals(NS_SPREADSHEETML)) {
        return;
    }
    if (isTextTag(localName)) {
        valueIsOpen = true;
        // Clear contents cache
        value.setLength(0);
    } else if ("is".equals(localName)) {
        // Inline string outer tag
        isIsOpen = true;
    } else if ("f".equals(localName)) {
        // Mark us as being a formula if not already
        if (nextDataType == XssfDataType.NUMBER) {
            nextDataType = XssfDataType.FORMULA;
        }
    } else if ("row".equals(localName)) {
        String rowNumStr = attributes.getValue("r");
        if (rowNumStr != null) {
            rowNum = Integer.parseInt(rowNumStr) - 1;
        } else {
            rowNum = nextRowNum;
        }
        output.startRow(rowNum);
    } else if ("c".equals(localName)) {
        // c => cell
        debug = attributes.getValue("r");
        column = new CellReference(debug).getCol();
        cellStyleStr = attributes.getValue("s");
        String cellType = attributes.getValue("t");
        this.nextDataType = XssfDataType.NUMBER;
        if ("b".equals(cellType)) {
            nextDataType = XssfDataType.BOOLEAN;
        } else if ("e".equals(cellType)) {
            nextDataType = XssfDataType.ERROR;
        } else if ("inlineStr".equals(cellType)) {
            nextDataType = XssfDataType.INLINE_STRING;
        } else if ("s".equals(cellType)) {
            nextDataType = XssfDataType.SST_STRING;
        } else if ("str".equals(cellType)) {
            nextDataType = XssfDataType.FORMULA;
        }
    }
}
Also used : XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) CellReference(org.apache.poi.ss.util.CellReference)

Example 63 with CellReference

use of org.apache.poi.ss.util.CellReference in project Aspose.Cells-for-Java by aspose-cells.

the class ApacheGetCellContent method main.

public static void main(String[] args) throws Exception {
    // The path to the documents directory.
    String dataDir = Utils.getDataDir(ApacheGetCellContent.class);
    InputStream inStream = new FileInputStream(dataDir + "workbook.xls");
    Workbook wb = WorkbookFactory.create(inStream);
    Sheet sheet1 = wb.getSheetAt(0);
    for (Row row : sheet1) {
        for (Cell cell : row) {
            CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
            System.out.print(cellRef.formatAsString());
            System.out.print(" - ");
            switch(cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    System.out.println(cell.getRichStringCellValue().getString());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        System.out.println(cell.getDateCellValue());
                    } else {
                        System.out.println(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.println(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    System.out.println(cell.getCellFormula());
                    break;
                default:
                    System.out.println();
            }
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Row(org.apache.poi.ss.usermodel.Row) CellReference(org.apache.poi.ss.util.CellReference) Sheet(org.apache.poi.ss.usermodel.Sheet) Cell(org.apache.poi.ss.usermodel.Cell) FileInputStream(java.io.FileInputStream) Workbook(org.apache.poi.ss.usermodel.Workbook)

Example 64 with CellReference

use of org.apache.poi.ss.util.CellReference in project SoftUni by kostovhg.

the class p14_ExportToExcel method main.

public static void main(String[] args) throws IOException {
    ArrayList<Object[]> allLines = new ArrayList<>();
    allLines.add(new Object[] { "FN", "First name", "Last Name", "Email", "Age", "Group", "Grade1", "Grade2", "Grade3", "Grade4", "Phones" });
    new BufferedReader(new FileReader("StudentsData.txt")).lines().map(x -> x.split("\\t")).filter(x -> !x[0].equals("FN")).forEach(allLines::add);
    // Create workbook and worksheet object
    int rowStart = 2;
    int columnStart = 0;
    int totalRows = allLines.size();
    int totalCols = allLines.get(0).length;
    int rowEnd = totalRows + rowStart - 1;
    int colEnd = totalCols + columnStart - 1;
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("SoftUniOOPCourseResults");
    CellStyle style1 = workbook.createCellStyle();
    style1.setAlignment(HorizontalAlignment.RIGHT);
    XSSFDataFormat intFormat = workbook.createDataFormat();
    style1.setDataFormat(intFormat.getFormat("0"));
    CellStyle style2 = workbook.createCellStyle();
    XSSFDataFormat strFormat = workbook.createDataFormat();
    style2.setDataFormat(strFormat.getFormat("General"));
    style2.setAlignment(HorizontalAlignment.LEFT);
    XSSFRow row;
    XSSFCell cell;
    // Create an object of type XSSFTable
    XSSFTable myTable = sheet.createTable();
    // Get CTTable object
    CTTable cttable = myTable.getCTTable();
    cttable.setTotalsRowShown(false);
    // Define the required style1 for the table
    CTTableStyleInfo table_style = cttable.addNewTableStyleInfo();
    table_style.setName("TableStyleLight14");
    // Set table style option
    table_style.setShowColumnStripes(false);
    table_style.setShowRowStripes(true);
    // define the data range including headers
    AreaReference my_data_range = new AreaReference(new CellReference(rowStart, columnStart), new CellReference(rowEnd, colEnd));
    // Set range to the table
    cttable.setRef(my_data_range.formatAsString());
    cttable.setDisplayName("Students");
    cttable.setName("Students");
    cttable.setId(1L);
    CTTableColumns columns = cttable.addNewTableColumns();
    CTAutoFilter autoFilter = cttable.addNewAutoFilter();
    columns.setCount(totalCols);
    // Define Header Information for the table
    for (int i = columnStart; i <= colEnd; i++) {
        CTTableColumn column = columns.addNewTableColumn();
        column.setName(allLines.get(0)[i].toString());
        column.setId(i + 1);
    }
    sheet.setAutoFilter(new CellRangeAddress(rowStart, rowStart, columnStart, colEnd));
    // Add remaining Table data
    row = sheet.createRow((short) 0);
    cell = row.createCell((short) 0);
    sheet.addMergedRegion(new CellRangeAddress(0, rowStart - 1, columnStart, colEnd));
    cell.setCellValue("SoftUni OOP Course Results");
    CellStyle bolded = workbook.createCellStyle();
    bolded.setAlignment(HorizontalAlignment.CENTER);
    XSSFFont myFont = workbook.createFont();
    myFont.setBold(true);
    myFont.setFontHeightInPoints((short) 30);
    bolded.setFont(myFont);
    cell.setCellStyle(bolded);
    int rowNum = rowStart;
    for (Object[] datatype : allLines) {
        XSSFRow inRow = sheet.createRow(rowNum++);
        int colNum = columnStart;
        for (Object field : datatype) {
            XSSFCell inCell = inRow.createCell(colNum++);
            if (isInt(field)) {
                inCell.setCellStyle(style1);
                inCell.setCellType(CellType.NUMERIC);
                inCell.setCellValue((Double) field);
            } else {
                inCell.setCellStyle(style2);
                inCell.setCellType(CellType.STRING);
                inCell.setCellValue((String) field);
            }
        }
    }
    for (int i = 1; i <= 11; i++) {
        sheet.autoSizeColumn(i);
    }
    try {
        FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
        workbook.write(outputStream);
        workbook.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Done");
}
Also used : org.apache.poi.ss.usermodel(org.apache.poi.ss.usermodel) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress) org.apache.poi.xssf.usermodel(org.apache.poi.xssf.usermodel) AreaReference(org.apache.poi.ss.util.AreaReference) java.io(java.io) org.openxmlformats.schemas.spreadsheetml.x2006.main(org.openxmlformats.schemas.spreadsheetml.x2006.main) CellReference(org.apache.poi.ss.util.CellReference) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) CellReference(org.apache.poi.ss.util.CellReference) AreaReference(org.apache.poi.ss.util.AreaReference) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress)

Example 65 with CellReference

use of org.apache.poi.ss.util.CellReference in project jgnash by ccavanaugh.

the class BudgetResultsExport method exportBudgetResultsModel.

/**
 * Exports a {@code BudgetResultsModel} to a spreadsheet.
 *
 * @param file File to save to
 * @param model Results model to export
 * @return Error message
 */
public static String exportBudgetResultsModel(final Path file, final BudgetResultsModel model) {
    String message = null;
    final ResourceBundle rb = ResourceUtils.getBundle();
    final String extension = FileUtils.getFileExtension(file.toString());
    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(model.getBudget().getName());
        // create header cell styles, override the defaults
        final CellStyle headerStyle = StyleFactory.createHeaderStyle(wb);
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        final Font headerFont = StyleFactory.createHeaderFont(wb);
        headerFont.setColor(IndexedColors.BLACK.index);
        headerStyle.setFont(headerFont);
        // Set the other cell style and formatting
        final DataFormat df_header = wb.createDataFormat();
        headerStyle.setDataFormat(df_header.getFormat("text"));
        // create fonts objects
        final Font amountFont = StyleFactory.createDefaultFont(wb);
        int row = 0;
        Row r = s.createRow(row);
        // fill the corner
        Cell corner = r.createCell(0);
        corner.setCellStyle(headerStyle);
        // 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.Actual")));
                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());
        accounts.sort(Comparators.getAccountByTreePosition(Comparators.getAccountByCode()));
        // create account rows
        for (final Account account : accounts) {
            final CellStyle amountStyle = StyleFactory.createDefaultAmountStyle(wb, account.getCurrencyNode());
            // Sets cell indentation, only impacts display if users changes the cell formatting to be left aligned.
            amountStyle.setIndention((short) (model.getDepth(account) * 2));
            row++;
            int col = 0;
            r = s.createRow(row);
            CellStyle cs = wb.createCellStyle();
            cs.cloneStyleFrom(headerStyle);
            cs.setAlignment(HorizontalAlignment.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, CellType.NUMERIC);
                c.setCellValue(results.getBudgeted().doubleValue());
                c.setCellStyle(amountStyle);
                CellReference budgetedRef = new CellReference(row, col);
                budgetedRefList.add(budgetedRef);
                c = r.createCell(++col, CellType.NUMERIC);
                c.setCellValue(results.getChange().doubleValue());
                c.setCellStyle(amountStyle);
                CellReference changeRef = new CellReference(row, col);
                changeRefList.add(changeRef);
                c = r.createCell(++col, CellType.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 (final AccountGroup group : model.getAccountGroupList()) {
            final DataFormat df = wb.createDataFormat();
            // reuse the header style but align right
            final CellStyle amountStyle = StyleFactory.createHeaderStyle(wb);
            amountStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            amountStyle.setAlignment(HorizontalAlignment.RIGHT);
            amountStyle.setFont(amountFont);
            final DecimalFormat format = (DecimalFormat) NumericFormats.getFullCommodityFormat(model.getBaseCurrency());
            final 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(HorizontalAlignment.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, CellType.NUMERIC);
                c.setCellValue(results.getBudgeted().doubleValue());
                c.setCellStyle(amountStyle);
                CellReference budgetedRef = new CellReference(row, col);
                budgetedRefList.add(budgetedRef);
                c = r.createCell(++col, CellType.NUMERIC);
                c.setCellValue(results.getChange().doubleValue());
                c.setCellStyle(amountStyle);
                CellReference changeRef = new CellReference(row, col);
                changeRefList.add(changeRef);
                c = r.createCell(++col, CellType.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);
        }
        Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.INFO, "{0} cell styles were used", wb.getNumCellStyles());
        // Save
        String filename = file.toString();
        if (wb instanceof XSSFWorkbook) {
            filename = FileUtils.stripFileExtension(filename) + ".xlsx";
        } else {
            filename = FileUtils.stripFileExtension(filename) + ".xls";
        }
        try (final OutputStream out = Files.newOutputStream(Paths.get(filename))) {
            wb.write(out);
        } catch (final Exception e) {
            Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
            message = e.getLocalizedMessage();
        }
    } catch (IOException e) {
        Logger.getLogger(BudgetResultsExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
    return message;
}
Also used : Account(jgnash.engine.Account) DecimalFormat(java.text.DecimalFormat) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) CellReference(org.apache.poi.ss.util.CellReference) Font(org.apache.poi.ss.usermodel.Font) DataFormat(org.apache.poi.ss.usermodel.DataFormat) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Cell(org.apache.poi.ss.usermodel.Cell) CreationHelper(org.apache.poi.ss.usermodel.CreationHelper) BudgetPeriodResults(jgnash.engine.budget.BudgetPeriodResults) IOException(java.io.IOException) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) Workbook(org.apache.poi.ss.usermodel.Workbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) IOException(java.io.IOException) AccountGroup(jgnash.engine.AccountGroup) ResourceBundle(java.util.ResourceBundle) CellStyle(org.apache.poi.ss.usermodel.CellStyle) Row(org.apache.poi.ss.usermodel.Row) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress) Sheet(org.apache.poi.ss.usermodel.Sheet) FormulaEvaluator(org.apache.poi.ss.usermodel.FormulaEvaluator)

Aggregations

CellReference (org.apache.poi.ss.util.CellReference)125 Test (org.junit.Test)52 Cell (org.apache.poi.ss.usermodel.Cell)28 Row (org.apache.poi.ss.usermodel.Row)27 AreaReference (org.apache.poi.ss.util.AreaReference)20 Sheet (org.apache.poi.ss.usermodel.Sheet)18 Workbook (org.apache.poi.ss.usermodel.Workbook)14 CellRangeAddress (org.apache.poi.ss.util.CellRangeAddress)14 HSSFWorkbook (org.apache.poi.hssf.usermodel.HSSFWorkbook)13 SXSSFWorkbook (org.apache.poi.xssf.streaming.SXSSFWorkbook)12 XSSFWorkbook (org.apache.poi.xssf.usermodel.XSSFWorkbook)11 FormulaEvaluator (org.apache.poi.ss.usermodel.FormulaEvaluator)8 XSSFSheet (org.apache.poi.xssf.usermodel.XSSFSheet)8 CellStyle (org.apache.poi.ss.usermodel.CellStyle)7 ArrayList (java.util.ArrayList)6 IOException (java.io.IOException)5 HSSFSheet (org.apache.poi.hssf.usermodel.HSSFSheet)5 RichTextString (org.apache.poi.ss.usermodel.RichTextString)5 FileOutputStream (java.io.FileOutputStream)4 OutputStream (java.io.OutputStream)4