Oracle Planning and FCCS
Export every EPM dimension to one Excel workbook
Need to see which FCCS accounts are intercompany, which plug accounts they use, or where a shared member sits? A single read-only Groovy rule collects the dimensions and member properties exposed by your application and automatically formats them in Excel, with one worksheet per dimension.
What users can see with their existing access
Oracle reserves the full, native Export Metadata and administrative dimension editing for Service Administrators. Business users can still review the members and hierarchy branches available to them through their application access.
Consider an Account hierarchy. The hierarchy can show that a receivable account sits under a balance-sheet rollup. To confirm whether FCCS treats it as an intercompany account, which plug account is configured, and which exchange rate type is assigned, users need the member properties.
Export Metadata roles Dimension Editor prerequisites Smart View Zoom In Planning user variables User variables on forms FCCS member properties
One Excel workbook, formatted by Groovy
Oracle’s native export packages individual CSV or text files in a ZIP. To turn those files into a single reference workbook, someone has to unpack the files, create the tabs, format the headers, and put the hierarchies into a readable layout. The Groovy rule builds and styles the finished .xlsx in a single run.
Planning native export FCCS native export Groovy Member API
Level n column.Illustrative FCCS Account tab with fictional member names and values. Only selected columns are shown.
Run the same rule in FCCS and Planning
- In Calculation Manager, create a Groovy business rule and paste the complete script below. The default configuration discovers the dimensions across the current application’s cubes.
- Validate, deploy, and run the rule. The job log prints the workbook name starting with
Metadata_. - Open Application → Overview → Actions → Inbox/Outbox Explorer and download the generated
.xlsxfrom the Outbox.
The rule reads members, hierarchies, and their properties. The Excel workbook is its only output. A Service Administrator can run the export and distribute the workbook to authorized users. Rule launch and Outbox download are separate permissions.
Oracle Groovy business rules Groovy Outbox API FCCS Inbox/Outbox Planning Inbox/Outbox
Metadata_…xlsx filename printed in the job log. Oracle tutorial Open screenshotThe complete Groovy rule
Use onlyDimensions if you want to export a smaller set of dimensions. Leave it empty for the full cube-visible inventory. The same script is designed for FCCS and Planning (PBCS).
Validation. The screenshots show a completed Planning run and its workbook. The FCCS version was checked locally with sample metadata. Validate the rule and run a test export in your own Calculation Manager environment before deploying it to production.
/*RTPS: */
// Calculation Manager Groovy rule for Planning and Financial Consolidation and Close.
// Discover metadata in the current application and write an XLSX to the Outbox.
import oracle.epm.api.model.Application
import oracle.epm.api.model.AttributeDimension
import oracle.epm.api.model.AttributeMember
import oracle.epm.api.model.Cube
import oracle.epm.api.model.Dimension
import oracle.epm.api.model.Member
import java.text.SimpleDateFormat
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
List<String> onlyDimensions = [] // Empty exports all discovered dimensions.
List<String> compactDimensions = [] // Optional dimensions to display under a merged Hierarchy header.
boolean includeAttributeTabs = true
boolean expandSharedBranches = true
Application app = operation.application
List<Cube> cubes = app.getCubes()
if (cubes.isEmpty()) {
throwVetoException('No cubes were returned for ' + app.getName() + '.')
}
Map<Integer, Dimension> dimensions = [:]
Map<Integer, List<Cube>> cubeScope = [:]
for (Cube cube : cubes) {
for (Dimension dimension : app.getDimensions(cube)) {
if (dimension.isAttributeDimension() && !includeAttributeTabs) {
continue
}
int id = dimension.getId()
if (!dimensions.containsKey(id)) {
dimensions.put(id, dimension)
cubeScope.put(id, new ArrayList<Cube>())
}
cubeScope.get(id).add(cube)
}
}
List<Dimension> selected = dimensions.values().findAll { Dimension dimension ->
onlyDimensions.isEmpty() || matchesDimension(onlyDimensions, dimension.getName())
} as List<Dimension>
for (String requested : onlyDimensions + compactDimensions) {
if (!selected.any { Dimension dimension -> dimension.getName().equalsIgnoreCase(requested) }) {
throwVetoException('Dimension not in the export: ' + requested)
}
}
if (selected.isEmpty()) {
throwVetoException('No cube-visible dimensions were found for export.')
}
List<String> aliasTables = app.getAliasTableNames()
List<Map<String, Object>> sheets = []
Set<String> sheetNames = new LinkedHashSet<String>()
println('Metadata export for ' + app.getName() + ' | cubes: ' + cubes.collect { Cube cube -> cube.getName() }.join(', '))
for (Dimension dimension : app.getDimensions()) {
if ((!dimension.isAttributeDimension() || includeAttributeTabs) && !cubeScope.containsKey(dimension.getId())) {
println('Dimension without a visible cube, skipped: ' + dimension.getName())
}
}
for (Dimension dimension : selected) {
String name = dimension.getName()
String tab = uniqueSheetName(name, sheetNames)
List<Cube> scope = cubeScope.get(dimension.getId())
try {
List<AttributeDimension> attributes = dimension.isAttributeDimension() ?
new ArrayList<AttributeDimension>() : dimension.getAttributeDimensions(false)
Map<List<String>, Map<String, Object>> placements = readPlacements(dimension, scope, attributes, aliasTables)
List<Map<String, Object>> outline = orderOutline(name, placements, expandSharedBranches)
sheets.add(buildSheet(tab, scope, outline, aliasTables, attributes, matchesDimension(compactDimensions, name)))
println(name + ': ' + placements.size() + ' outline placements, ' + outline.size() + ' workbook rows')
} catch (Exception ex) {
throwVetoException('Could not export dimension ' + name + ': ' + ex.getMessage())
}
}
String safeApp = app.getName().replaceAll('[^A-Za-z0-9_-]', '_')
String output = 'Metadata_' + safeApp + '_' + new SimpleDateFormat('yyyyMMdd_HHmmss_SSS').format(new Date()) +
'_' + UUID.randomUUID().toString().substring(0, 8) + '.xlsx'
writeStyledWorkbook(output, sheets)
println('Outbox workbook: ' + output)
return null
boolean matchesDimension(List<String> requested, String name) {
return requested.any { String candidate -> candidate.equalsIgnoreCase(name) }
}
String dimensionKey(String value) {
return value.toLowerCase(Locale.ROOT)
}
String uniqueSheetName(String name, Set<String> used) {
String cleaned = name.replaceAll('[\\\\/:?*\\[\\]]', '_').replaceAll("^'+|'+\$", '')
if (cleaned.isEmpty()) {
cleaned = 'Dimension'
}
if (cleaned.equalsIgnoreCase('History')) {
cleaned = 'History_'
}
String candidate = cleaned.take(31)
int serial = 2
while (!used.add(dimensionKey(candidate))) {
String suffix = '_' + serial
candidate = cleaned.take(31 - suffix.length()) + suffix
serial++
}
return candidate
}
String propertyText(Object value) {
if (value == null) {
return ''
}
String text = value.toString()
return text.equalsIgnoreCase('<none>') || text.equalsIgnoreCase('<null>') ? '' : text
}
String outlineName(String name) {
int separator = name.lastIndexOf('].[')
if (separator >= 0 && name.startsWith('[') && name.endsWith(']')) {
return name.substring(separator + 3, name.length() - 1)
}
return name
}
Map<List<String>, Map<String, Object>> readPlacements(Dimension dimension, List<Cube> cubes,
List<AttributeDimension> attributes, List<String> aliasTables) {
Map<List<String>, Map<String, Object>> placements = [:]
for (Cube cube : cubes) {
Member root = dimension.getRootMember(cube)
if (root == null) {
throw new IllegalStateException('Oracle returned no dimension root for cube ' + cube.getName())
}
String rootName = outlineName(root.getName())
String selection = 'IDescendants(' + cscParams(rootName) + ')'
for (Member member : dimension.getEvaluatedMembers(selection, cube)) {
if (member.getId() == root.getId()) {
continue
}
Map<String, Object> props = member.toMap()
String name = outlineName(propertyText(props.get('Member')) ?: member.getName())
String parent = outlineName(propertyText(props.get('Parent')))
if (parent.equalsIgnoreCase(rootName)) {
parent = ''
}
List<String> key = [dimensionKey(parent), dimensionKey(name)]
Map<String, Object> record = placements.get(key)
if (record == null) {
record = [
name: name,
parent: parent,
props: new LinkedHashMap<String, Object>(props),
shared: isShared(props, cube),
seenCubes: new LinkedHashSet<String>()
] as Map<String, Object>
placements.put(key, record)
Map<String, Object> stored = (Map<String, Object>) record.get('props')
completeProperties(stored, member, attributes, aliasTables)
}
Map<String, Object> stored = (Map<String, Object>) record.get('props')
for (Map.Entry<String, Object> property : props.entrySet()) {
String label = property.getKey()
if (!stored.containsKey(label) || propertyText(stored.get(label)).isEmpty()) {
stored.put(label, property.getValue())
}
}
for (String field : ['Plan Type', 'Formula', 'Data Storage', 'Aggregation']) {
String sourceKey = cubePropertyKey(props, field, cube)
if (sourceKey != null) {
stored.put(field + ' (' + cube.getName() + ')', props.get(sourceKey))
}
}
Set<String> seenCubes = (Set<String>) record.get('seenCubes')
seenCubes.add(cube.getName())
}
}
for (Map<String, Object> record : placements.values()) {
Map<String, Object> props = (Map<String, Object>) record.get('props')
for (Cube cube : cubes) {
for (String field : ['Plan Type', 'Formula', 'Data Storage', 'Aggregation']) {
String canonical = field + ' (' + cube.getName() + ')'
if (!props.containsKey(canonical)) {
String sourceKey = cubePropertyKey(props, field, cube)
if (sourceKey != null) {
props.put(canonical, props.get(sourceKey))
}
}
}
}
}
return placements
}
void completeProperties(Map<String, Object> props, Member member, List<AttributeDimension> attributes,
List<String> aliasTables) {
for (String table : aliasTables) {
String label = 'Alias: ' + table
if (!props.containsKey(label)) {
props.put(label, member.getAlias(table))
}
}
if (!props.containsKey('Description')) {
props.put('Description', member.getDescription())
}
if (!props.containsKey('UDA')) {
List<String> udas = member.getUdas()
if (udas != null && !udas.isEmpty()) {
props.put('UDA', udas.join(','))
}
}
for (AttributeDimension attr : attributes) {
String label = 'Attribute Dim - ' + attr.getName()
if (propertyText(props.get(label)).isEmpty()) {
AttributeMember assigned = member.getAttributeValue(attr)
props.put(label, assigned == null ? null : outlineName(assigned.getName()))
}
}
}
String cubePropertyKey(Map<String, Object> props, String name, Cube cube) {
String logical = cube.getName()
String physical = cube.getEssbaseName()
for (String label : [name + ' (' + logical + ')', name + ' (' + physical + ')',
logical + ' ' + name, physical + ' ' + name]) {
if (props.containsKey(label)) {
return label
}
}
return null
}
boolean isShared(Map<String, Object> props, Cube cube) {
String scopeKey = cubePropertyKey(props, 'Data Storage', cube)
String storage = propertyText(scopeKey == null ? null : props.get(scopeKey)) ?:
propertyText(props.get('Data Storage')) ?: propertyText(props.get('Default Data Storage'))
return storage.equalsIgnoreCase('shared') || storage.equalsIgnoreCase('shared member')
}
List<Map<String, Object>> orderOutline(String dimensionName, Map<List<String>, Map<String, Object>> placements,
boolean expandSharedBranches) {
Map<String, List<Map<String, Object>>> children = [:]
Map<String, Map<String, Object>> baseByName = [:]
for (Map<String, Object> record : placements.values()) {
String name = dimensionKey((String) record.get('name'))
String parent = dimensionKey((String) record.get('parent'))
List<Map<String, Object>> siblings = children.get(parent)
if (siblings == null) {
siblings = new ArrayList<Map<String, Object>>()
children.put(parent, siblings)
}
siblings.add(record)
Map<String, Object> existing = baseByName.get(name)
if (existing == null || ((Boolean) existing.get('shared') && !(Boolean) record.get('shared'))) {
baseByName.put(name, record)
}
}
List<Map<String, Object>> ordered = []
Set<List<String>> emitted = new LinkedHashSet<List<String>>()
Set<String> active = new LinkedHashSet<String>()
Set<String> cyclic = new LinkedHashSet<String>()
Set<String> orphaned = new LinkedHashSet<String>()
List<Map<String, Object>> roots = children.get('')
if (roots != null) {
for (Map<String, Object> root : roots) {
addBranch(root, 1, children, baseByName, ordered, emitted, active, cyclic, expandSharedBranches)
}
}
// Start with missing-parent branches, so their children are still displayed below them.
for (Map<String, Object> record : placements.values()) {
String parent = (String) record.get('parent')
if (!parent.isEmpty() && !baseByName.containsKey(dimensionKey(parent))) {
orphaned.add(parent)
addBranch(record, 1, children, baseByName, ordered, emitted, active, cyclic, expandSharedBranches)
}
}
for (Map.Entry<List<String>, Map<String, Object>> entry : placements.entrySet()) {
if (!emitted.contains(entry.getKey())) {
Map<String, Object> record = entry.getValue()
orphaned.add((String) record.get('name'))
addBranch(record, 1, children, baseByName, ordered, emitted, active, cyclic, expandSharedBranches)
}
}
if (!orphaned.isEmpty()) {
println(dimensionName + ': members below an unavailable parent were included at the first visible level. ' +
'Affected parents/branches: ' + orphaned.size())
}
if (!cyclic.isEmpty()) {
println(dimensionName + ': stopped recursion on ' + cyclic.size() + ' cyclic shared branches.')
}
return ordered
}
void addBranch(Map<String, Object> record, int depth, Map<String, List<Map<String, Object>>> children,
Map<String, Map<String, Object>> baseByName, List<Map<String, Object>> ordered,
Set<List<String>> emitted, Set<String> active, Set<String> cyclic, boolean expandSharedBranches) {
String nameKey = dimensionKey((String) record.get('name'))
String parentKey = dimensionKey((String) record.get('parent'))
List<String> placementKey = [parentKey, nameKey]
if (!expandSharedBranches && emitted.contains(placementKey)) {
return
}
if (ordered.size() >= 1048575) {
throw new IllegalStateException('Excel row limit exceeded; narrow onlyDimensions or turn off shared branch expansion.')
}
Map<String, Object> base = baseByName.get(nameKey)
ordered.add([record: record, base: base, depth: depth] as Map<String, Object>)
emitted.add(placementKey)
if (!active.add(nameKey)) {
cyclic.add(nameKey)
return
}
List<Map<String, Object>> descendants = children.get(nameKey)
if (descendants != null && (expandSharedBranches || record.get('parent') == base.get('parent'))) {
for (Map<String, Object> child : descendants) {
addBranch(child, depth + 1, children, baseByName, ordered, emitted, active, cyclic, expandSharedBranches)
}
}
active.remove(nameKey)
}
int enabledInCube(Map<String, Object> props, Set<String> seenCubes, Cube cube) {
String scopeKey = cubePropertyKey(props, 'Plan Type', cube)
String value = propertyText(scopeKey == null ? null : props.get(scopeKey)).trim().toLowerCase(Locale.ROOT)
if (value in ['1', 'true', 'yes']) {
return 1
}
if (value in ['0', 'false', 'no']) {
return 0
}
return seenCubes.contains(cube.getName()) ? 1 : 0
}
void addColumn(List<String> headers, List<Integer> widths, String label, int width) {
headers.add(label)
widths.add(width)
}
boolean inheritsProperty(String label) {
return label == 'Description' || label == 'UDA' || label == 'Formula' ||
label.startsWith('Alias: ') || label.startsWith('Attribute Dim - ') || label.startsWith('Formula (')
}
String metadataValue(Object value) {
if (value instanceof Collection) {
return ((Collection<?>) value).collect { Object item -> propertyText(item) }.join(',')
}
return propertyText(value)
}
Map<String, Object> buildSheet(String tab, List<Cube> cubes, List<Map<String, Object>> outline,
List<String> aliasTables, List<AttributeDimension> attributes, boolean compact) {
Set<String> propertyNames = new LinkedHashSet<String>()
int maxDepth = 1
for (Map<String, Object> occurrence : outline) {
Map<String, Object> record = (Map<String, Object>) occurrence.get('record')
Map<String, Object> props = (Map<String, Object>) record.get('props')
propertyNames.addAll(props.keySet())
maxDepth = Math.max(maxDepth, (Integer) occurrence.get('depth'))
}
List<String> headers = []
List<Integer> widths = []
List<String> aliases = aliasTables.collect { String table -> 'Alias: ' + table }
Set<String> represented = ['Member', 'Name', 'Parent', 'Level', 'New Name', 'Old Name', 'UUID'] as Set<String>
represented.addAll(aliases)
int hierarchyColumns = compact ? Math.max(2, maxDepth) : maxDepth
int mergeEnd = compact ? hierarchyColumns + 1 : 0
if (compact) {
addColumn(headers, widths, 'Member', 27)
} else {
addColumn(headers, widths, 'Name', 23)
addColumn(headers, widths, 'Parent', 23)
for (String alias : aliases) {
addColumn(headers, widths, alias, 40)
}
}
for (int depth = 1; depth <= hierarchyColumns; depth++) {
addColumn(headers, widths, compact ? (depth == 1 ? 'Hierarchy' : '') : 'Level ' + depth, compact ? 23 : 9)
}
if (compact) {
addColumn(headers, widths, 'Parent', 23)
for (String alias : aliases) {
addColumn(headers, widths, alias, 40)
}
}
addColumn(headers, widths, 'Level', 8)
List<String> leadProperties = []
if (propertyNames.contains('UDA')) {
leadProperties.add('UDA')
}
for (AttributeDimension attr : attributes) {
leadProperties.add('Attribute Dim - ' + attr.getName())
}
represented.addAll(leadProperties)
for (String property : leadProperties) {
addColumn(headers, widths, property, Math.max(20, Math.min(45, property.length() + 3)))
}
for (Cube cube : cubes) {
addColumn(headers, widths, 'Plan Type (' + cube.getName() + ')', Math.max(20, Math.min(45, cube.getName().length() + 13)))
}
// Each recognized cube property has one column based on its logical cube name.
List<String> extraProperties = []
for (Cube cube : cubes) {
for (String field : ['Plan Type', 'Formula', 'Data Storage', 'Aggregation']) {
for (String name : [cube.getName(), cube.getEssbaseName()]) {
represented.add(field + ' (' + name + ')')
represented.add(name + ' ' + field)
}
String label = field + ' (' + cube.getName() + ')'
if (field != 'Plan Type' && propertyNames.contains(label)) {
extraProperties.add(label)
addColumn(headers, widths, label, field == 'Formula' ? 40 : 28)
}
}
}
for (String property : propertyNames) {
if (!represented.contains(property) && !property.matches('(?i)Level [0-9]+')) {
extraProperties.add(property)
int width = property == 'Description' ? 55 : property.startsWith('Formula') ? 40 :
Math.max(20, Math.min(45, property.length() + 3))
addColumn(headers, widths, property, width)
}
}
if (headers.size() > 16384) {
throw new IllegalStateException('Excel column limit exceeded.')
}
List<List<Object>> rows = []
Set<Integer> topRows = new LinkedHashSet<Integer>()
for (Map<String, Object> occurrence : outline) {
int level = (Integer) occurrence.get('depth')
Map<String, Object> record = (Map<String, Object>) occurrence.get('record')
Map<String, Object> base = (Map<String, Object>) occurrence.get('base')
Map<String, Object> props = (Map<String, Object>) record.get('props')
Map<String, Object> baseProps = (Map<String, Object>) base.get('props')
Set<String> seenCubes = (Set<String>) record.get('seenCubes')
String name = (String) record.get('name')
List<Object> row = [name]
if (!compact) {
row.add(record.get('parent'))
for (String alias : aliases) {
row.add(metadataValue(props.get(alias)) ?: metadataValue(baseProps.get(alias)))
}
}
for (int depth = 1; depth <= hierarchyColumns; depth++) {
row.add(depth == level ? name : null)
}
if (compact) {
row.add(record.get('parent'))
for (String alias : aliases) {
row.add(metadataValue(props.get(alias)) ?: metadataValue(baseProps.get(alias)))
}
}
row.add(level)
for (String key : leadProperties) {
row.add(metadataValue(props.get(key)) ?: metadataValue(baseProps.get(key)))
}
for (Cube cube : cubes) {
row.add(enabledInCube(props, seenCubes, cube))
}
for (String key : extraProperties) {
String cell = metadataValue(props.get(key))
if (cell.isEmpty() && inheritsProperty(key)) {
cell = metadataValue(baseProps.get(key))
}
row.add(cell)
}
for (Object value : row) {
if (value instanceof String && ((String) value).length() > 32767) {
throw new IllegalStateException('Excel cell length limit exceeded for member ' + name)
}
}
rows.add(row)
if (level == 1) {
topRows.add(rows.size() + 1)
}
}
return [name: tab, headers: headers, widths: widths, rows: rows, topRows: topRows, mergeEnd: mergeEnd] as Map<String, Object>
}
// A styled XLSX is an Open XML ZIP package written directly to the Outbox.
// Excel text is written as inline strings, including Essbase formulas.
void writeStyledWorkbook(String outputName, List<Map<String, Object>> sheets) {
String spreadsheetNs = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'
String packageRelsNs = 'http://schemas.openxmlformats.org/package/2006/relationships'
String officeRelsNs = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
String contentTypesNs = 'http://schemas.openxmlformats.org/package/2006/content-types'
String spreadsheetMime = 'application/vnd.openxmlformats-officedocument.spreadsheetml'
String xmlDeclaration = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
StringBuilder contentTypes = new StringBuilder(xmlDeclaration)
contentTypes.append('<Types xmlns="').append(contentTypesNs).append('">')
.append('<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>')
.append('<Default Extension="xml" ContentType="application/xml"/>')
.append('<Override PartName="/xl/workbook.xml" ContentType="').append(spreadsheetMime).append('.sheet.main+xml"/>')
.append('<Override PartName="/xl/styles.xml" ContentType="').append(spreadsheetMime).append('.styles+xml"/>')
StringBuilder workbookXml = new StringBuilder(xmlDeclaration)
workbookXml.append('<workbook xmlns="').append(spreadsheetNs).append('" xmlns:r="')
.append(officeRelsNs).append('"><sheets>')
StringBuilder workbookRels = new StringBuilder(xmlDeclaration)
workbookRels.append('<Relationships xmlns="').append(packageRelsNs).append('">')
.append('<Relationship Id="rIdStyles" Type="').append(officeRelsNs)
.append('/styles" Target="styles.xml"/>')
for (int i = 0; i < sheets.size(); i++) {
int sheetNumber = i + 1
String sheetName = (String) sheets.get(i).get('name')
contentTypes.append('<Override PartName="/xl/worksheets/sheet').append(sheetNumber)
.append('.xml" ContentType="').append(spreadsheetMime).append('.worksheet+xml"/>')
workbookXml.append('<sheet name="').append(xlsxXmlEscape(sheetName)).append('" sheetId="')
.append(sheetNumber).append('" r:id="rId').append(sheetNumber).append('"/>')
workbookRels.append('<Relationship Id="rId').append(sheetNumber).append('" Type="')
.append(officeRelsNs).append('/worksheet" Target="worksheets/sheet')
.append(sheetNumber).append('.xml"/>')
}
contentTypes.append('</Types>')
workbookXml.append('</sheets></workbook>')
workbookRels.append('</Relationships>')
String packageRels = xmlDeclaration + '<Relationships xmlns="' + packageRelsNs +
'"><Relationship Id="rId1" Type="' + officeRelsNs +
'/officeDocument" Target="xl/workbook.xml"/></Relationships>'
zipOutputStream(outputName).withCloseable { ZipOutputStream zip ->
writeXlsxPart(zip, '[Content_Types].xml', contentTypes.toString())
writeXlsxPart(zip, '_rels/.rels', packageRels)
writeXlsxPart(zip, 'xl/workbook.xml', workbookXml.toString())
writeXlsxPart(zip, 'xl/_rels/workbook.xml.rels', workbookRels.toString())
writeXlsxPart(zip, 'xl/styles.xml', xlsxStyles(xmlDeclaration, spreadsheetNs))
for (int i = 0; i < sheets.size(); i++) {
String path = 'xl/worksheets/sheet' + (i + 1) + '.xml'
writeXlsxSheet(zip, path, sheets.get(i), xmlDeclaration, spreadsheetNs)
}
}
}
void writeXlsxPart(ZipOutputStream zip, String path, String xml) {
zip.putNextEntry(new ZipEntry(path))
writeXlsxUtf8(zip, xml)
zip.closeEntry()
}
void writeXlsxUtf8(ZipOutputStream zip, String text) {
byte[] utf8 = text.getBytes('UTF-8')
zip.write(utf8, 0, utf8.length)
}
void writeXlsxSheet(ZipOutputStream zip, String path, Map<String, Object> sheet,
String xmlDeclaration, String spreadsheetNs) {
List<String> headers = (List<String>) sheet.get('headers')
List<Integer> widths = (List<Integer>) sheet.get('widths')
List<List<Object>> rows = (List<List<Object>>) sheet.get('rows')
Set<Integer> topRows = (Set<Integer>) sheet.get('topRows')
int mergeEnd = (Integer) sheet.get('mergeEnd')
boolean compact = headers.get(0) == 'Member'
int columnCount = headers.size()
StringBuilder xml = new StringBuilder(xmlDeclaration)
List<String> columnNames = new ArrayList<String>()
List<Integer> headerStyles = new ArrayList<Integer>()
List<Integer> dataStyles = new ArrayList<Integer>()
List<Integer> topStyles = new ArrayList<Integer>()
zip.putNextEntry(new ZipEntry(path))
xml.append('<worksheet xmlns="').append(spreadsheetNs)
.append('"><sheetFormatPr defaultRowHeight="14.45"/><cols>')
for (int i = 0; i < columnCount; i++) {
int column = i + 1
columnNames.add(xlsxColumnName(column))
int width = Math.max(1, Math.min(255, widths.get(i)))
xml.append('<col min="').append(column).append('" max="').append(column)
.append('" width="').append(width).append('" customWidth="1"/>')
if (compact) {
headerStyles.add(4)
if (column == 1 || column > mergeEnd) {
dataStyles.add(10)
topStyles.add(13)
} else if (column == 2) {
dataStyles.add(11)
topStyles.add(14)
} else if (column == mergeEnd) {
dataStyles.add(12)
topStyles.add(15)
} else {
dataStyles.add(0)
topStyles.add(16)
}
} else if (column == 1) {
headerStyles.add(2)
dataStyles.add(5)
topStyles.add(8)
} else if (column == 3 || column == columnCount) {
headerStyles.add(3)
dataStyles.add(6)
topStyles.add(9)
} else {
headerStyles.add(1)
dataStyles.add(0)
topStyles.add(7)
}
}
xml.append('</cols><sheetData><row r="1" ht="').append(compact ? '24.95' : '37.5')
.append('" customHeight="1">')
for (int i = 0; i < columnCount; i++) {
appendXlsxCell(xml, columnNames.get(i) + '1', headers.get(i), headerStyles.get(i))
}
xml.append('</row>')
int rowNumber = 1
for (List<Object> row : rows) {
rowNumber++
List<Integer> styles = topRows.contains(rowNumber) ? topStyles : dataStyles
xml.append('<row r="').append(rowNumber).append('">')
for (int i = 0; i < columnCount; i++) {
Object value = row.get(i)
int style = styles.get(i)
if (value != null || style != 0) {
appendXlsxCell(xml, columnNames.get(i) + rowNumber, value, style)
}
}
xml.append('</row>')
if (xml.length() >= 65536) {
writeXlsxUtf8(zip, xml.toString())
xml.setLength(0)
}
}
xml.append('</sheetData>')
if (mergeEnd > 2) {
xml.append('<mergeCells count="1"><mergeCell ref="B1:')
.append(xlsxColumnName(mergeEnd)).append('1"/></mergeCells>')
}
xml.append('</worksheet>')
writeXlsxUtf8(zip, xml.toString())
zip.closeEntry()
}
void appendXlsxCell(StringBuilder xml, String cellRef, Object value, int style) {
xml.append('<c r="').append(cellRef).append('"')
if (style != 0) {
xml.append(' s="').append(style).append('"')
}
if (value instanceof Integer) {
xml.append('><v>').append(value).append('</v></c>')
} else if (value != null && !value.toString().isEmpty()) {
String cellText = value.toString()
if (cellText.length() > 32767) {
throw new IllegalArgumentException('Excel cell ' + cellRef + ' exceeds 32767 characters.')
}
xml.append(' t="inlineStr"><is><t xml:space="preserve">')
.append(xlsxXmlEscape(cellText)).append('</t></is></c>')
} else {
xml.append('/>')
}
}
String xlsxColumnName(int number) {
StringBuilder result = new StringBuilder()
String letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
int remainder = number
while (remainder > 0) {
remainder--
result.insert(0, letters.charAt(remainder % 26))
remainder = remainder.intdiv(26)
}
return result.toString()
}
String xlsxXmlEscape(String value) {
// Protect literal Open XML escape tokens. Keep line breaks and spaces in formulas.
return value.replaceAll('(?i)_(x[0-9a-f]{4}_)', '_x005F_$1')
.replaceAll('[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x{FFFE}\\x{FFFF}]', '')
.replace('&', '&').replace('<', '<').replace('>', '>')
.replace('"', '"').replace('\r', ' ')
}
String xlsxStyles(String xmlDeclaration, String spreadsheetNs) {
String styleDefinitions = '''<fonts count="3">
<font><sz val="11"/><name val="Calibri"/></font>
<font><b/><sz val="11"/><color rgb="FFFFFFFF"/><name val="Calibri"/></font>
<font><b/><sz val="12"/><color rgb="FFFFFFFF"/><name val="Arial"/></font>
</fonts>
<fills count="4">
<fill><patternFill patternType="none"/></fill>
<fill><patternFill patternType="gray125"/></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FF347762"/><bgColor indexed="64"/></patternFill></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFFFDB00"/><bgColor indexed="64"/></patternFill></fill>
</fills>
<borders count="14">
<border><left/><right/><top/><bottom/><diagonal/></border>
<border><left/><right/><top style="thick"/><bottom/><diagonal/></border>
<border><left style="thick"/><right/><top style="thick"/><bottom/><diagonal/></border>
<border><left/><right style="thick"/><top style="thick"/><bottom/><diagonal/></border>
<border><left/><right/><top style="thin"/><bottom/><diagonal/></border>
<border><left style="thick"/><right/><top/><bottom/><diagonal/></border>
<border><left/><right style="thick"/><top/><bottom/><diagonal/></border>
<border><left style="medium"/><right style="medium"/><top/><bottom/><diagonal/></border>
<border><left style="medium"/><right/><top/><bottom/><diagonal/></border>
<border><left/><right style="medium"/><top/><bottom/><diagonal/></border>
<border><left style="medium"/><right style="medium"/><top style="medium"/><bottom/><diagonal/></border>
<border><left style="medium"/><right/><top style="medium"/><bottom/><diagonal/></border>
<border><left/><right style="medium"/><top style="medium"/><bottom/><diagonal/></border>
<border><left/><right/><top style="medium"/><bottom/><diagonal/></border>
</borders>
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
<cellXfs count="17">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="0" fontId="1" fillId="2" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center" wrapText="1"/></xf>
<xf numFmtId="0" fontId="1" fillId="2" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center" wrapText="1"/></xf>
<xf numFmtId="0" fontId="1" fillId="2" borderId="3" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center" wrapText="1"/></xf>
<xf numFmtId="0" fontId="2" fillId="2" borderId="4" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="5" xfId="0" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="0" borderId="6" xfId="0" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="0" xfId="0" applyFill="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="5" xfId="0" applyFill="1" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="6" xfId="0" applyFill="1" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="0" borderId="7" xfId="0" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="0" borderId="8" xfId="0" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="0" borderId="9" xfId="0" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="10" xfId="0" applyFill="1" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="11" xfId="0" applyFill="1" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="12" xfId="0" applyFill="1" applyBorder="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="13" xfId="0" applyFill="1" applyBorder="1"/>
</cellXfs>
<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'''
return xmlDeclaration + '<styleSheet xmlns="' + spreadsheetNs + '">' +
styleDefinitions + '</styleSheet>'
}
