Examples
Seven complete tasks, each done the way LibreOffice Calc would do it: named ranges and array formulas for a summary, cell styles and conditional formats for a table, a protected template for a form, data bars, a picture, and two charts that LibreOffice draws from the cells.
Summarising data with formulas
A table of plant measurements is summarised by species and year with formulas, so that the summary changes when the measurements do. The data are made here, by a fixed rule, so the example gives the same result every time.
using OpenDocumentSpreadsheets
species = repeat(["setosa", "versicolor", "virginica"]; inner = 8)
k = repeat(0:7, 3) # the plant's number within its species
base = Dict("setosa" => (5.0, 3.4, 1.5, 0.2), "versicolor" => (5.9, 2.8, 4.3, 1.3),
"virginica" => (6.6, 3.0, 5.5, 2.0))
measure(j) = [round(base[s][j] + 0.1 * ((3i + j) % 5 - 2); digits = 1) for (s, i) in zip(species, k)]
year = [1993 + i % 3 for i in k]
ods = newods("Plants")
sh = ods["Plants"]
writetable!(sh, [species, measure(1), measure(2), measure(3), measure(4), year],
["Species", "Sepal length", "Sepal width", "Petal length", "Petal width", "Year"];
as_table = true, table_name = "Measurements")
addDefinedName(ods, "Species", "Plants.\$A\$2:\$A\$25")
addDefinedName(ods, "Year", "Plants.\$F\$2:\$F\$25")as_table = true makes the table a database range, so that LibreOffice's Data ▸ Sort and AutoFilter work on it. The two names (Sheet ▸ Named Ranges and Expressions) make the formulas below easier to read.
The summary uses ordinary formulas and array formulas: one formula over a range, whose results fill the range, as LibreOffice's Ctrl+Shift+Enter enters it. An array formula's range is fixed, so it is given the size of its results: three species, three years.
sh["H1"] = "Size"
setFormula(sh, "H2:H25"; val = "=B2:B25+C2:C25+D2:D25+E2:E25", array = true)
sh["J1"] = "Averages by species"
sh["J2:N2"] = ["Species" "Sepal length" "Sepal width" "Petal length" "Petal width"]
setFormula(sh, "J3:J5"; val = "=UNIQUE(Species)", array = true)
for (col, m) in zip('K':'N', 'B':'E'), r in 3:5
setFormula(sh, "$col$r"; val = "=AVERAGEIFS($(m)\$2:$(m)\$25,Species,\$J$r)")
end
sh["J7"] = "Plants by species and year"
setFormula(sh, "K8:M8"; val = "=TRANSPOSE(SORT(UNIQUE(Year)))", array = true)
setFormula(sh, "J9:J11"; val = "=J3:J5", array = true)
for (col, r) in Iterators.product('K':'M', 9:11)
setFormula(sh, "$col$r"; val = "=COUNTIFS(Species,\$J$r,Year,$(col)\$8)")
end
sh["P2"] = "Petal length of"
sh["P3"] = "versicolor"
setFormula(sh, "P4"; val = "=VLOOKUP(P3,J3:N5,4,0)")
sh["J13"] = "Virginica, longest petals first"
setFormula(sh, "J14:M21"; val = "=SORT(FILTER(A2:D25,A2:A25=\"virginica\"),4,-1)", array = true)
setFont(sh, "H1,J1,J7,P2,J13"; bold = true)
setFormat(sh, "K3:N5,P4"; format = "0.00")
setColumnWidth(sh, "A:P"; width = 12)Each array formula's cells show the formula in braces, as LibreOffice's formula bar does:

UNIQUE,SORT,FILTERandTRANSPOSEgive all their results only in an array formula; in an ordinary one, LibreOffice shows the first.J9:J11repeats the species with an array formula of its own,=J3:J5.- The formulas have no values until LibreOffice opens the file and calculates them.
Formatting a table
A table of mixed values, written as it comes:
using OpenDocumentSpreadsheets, Dates
ods = newods("Sheet1")
sh = ods["Sheet1"]
names = ["Integers", "Strings", "Floats", "Booleans", "Dates", "Times", "DateTimes",
"AbstractStrings", "Rational", "Irrationals", "MixedStringNothingMissing"]
data = Any[[1, 2, missing, UInt8(4)],
["Hey", "You", "Out", "There"],
[101.5, 102.5, missing, 104.5],
[true, false, missing, true],
[Date(2018, 2, 1), Date(2018, 3, 1), Date(2018, 5, 20), Date(2018, 6, 2)],
[Time(19, 10), Time(19, 20), Time(19, 30), Time(0, 0)],
[DateTime(2018, 5, 20, 19, 10), DateTime(2018, 5, 20, 19, 20),
DateTime(2018, 5, 20, 19, 30), DateTime(2018, 5, 20, 19, 40)],
SubString.(["Hey", "You", "Out", "There"], 1, 2),
[1 // 2, 1 // 3, missing, 22 // 3],
[pi, sqrt(2), missing, sqrt(5)],
[nothing, "middle", missing, "rotated"]]
writetable!(sh, data, names; anchor_cell = "B2")
writeods("table_plain.ods", ods)
The same table formatted. The header and the body each get a cell style of their own (the Styles deck lists them), so changing a style later changes every cell that uses it. A few cells then get formatting of their own.
addCellStyle(ods, "Table header"; font = (bold = true, color = "FFFFFF"),
fill = (pattern = "solid", fgColor = "444444"),
alignment = (horizontal = "center", vertical = "center", wrapText = true),
border = (bottom = ["style" => "medium", "color" => "000000"],))
addCellStyle(ods, "Table body"; font = (color = "444444",),
border = (top = ["style" => "hair", "color" => "000000"], bottom = ["style" => "hair", "color" => "000000"],
left = ["style" => "thin", "color" => "000000"], right = ["style" => "thin", "color" => "000000"]))
setCellStyle(sh, "B2:L2", "Table header")
setCellStyle(sh, "B3:L6", "Table body")
setBorder(sh, "B6:L6"; top = ["style" => "double", "color" => "000000"])
setBorder(sh, "B2:L6"; outside = ["style" => "thick", "color" => "000000"])
setFont(sh, "C3"; name = "Liberation Serif")
setFont(sh, "C6"; name = "Liberation Mono", color = "2F75B5")
setAlignment(sh, "C4"; indent = 2)
setAlignment(sh, "F4"; vertical = "top")
setAlignment(sh, "G3:G6"; horizontal = "center")
setAlignment(sh, "H3:H6"; shrink = true)
setAlignment(sh, "I4,I6"; horizontal = "right")
setAlignment(sh, "L4"; horizontal = "center", vertical = "center")
setAlignment(sh, "L6"; horizontal = "center", rotation = 90, wrapText = true)
setRowHeight(sh, 4; height = 50)
setColumnWidth(sh, "I"; width = 20.5)
setFormat(sh, "J3"; format = "Percentage")
setFormat(sh, "J4"; format = "Currency")
setFormat(sh, "J6"; format = "Number")
setFormat(sh, "K3"; format = "0.0")
setFormat(sh, "K4"; format = "0.000")
setFormat(sh, "K6"; format = "0.0000")The cells picked out by their values get conditional formats, which LibreOffice applies again whenever the values change. The formats are cell styles: LibreOffice's built-in Good and Bad, and one made here for empty cells, with a grey fill and both diagonals.
addCellStyle(ods, "Blank"; fill = (pattern = "solid", fgColor = "BFBFBF"),
border = (diagonal = ["style" => "thin", "color" => "000000", "direction" => "both"],))
setConditionalFormat(sh, "B3:L6", :containsBlanks; style = "Blank")
setConditionalFormat(sh, "E3:E6", :cellIs; operator = "equal", value = "TRUE",
font = ["color" => "548235", "bold" => "true"])
setConditionalFormat(sh, "E3:E6", :cellIs; operator = "equal", value = "FALSE",
font = ["color" => "C00000", "bold" => "true"])
for col in ("D", "J", "K")
setConditionalFormat(sh, "$(col)3:$(col)6", :top10; operator = "topN", value = "1", style = "Good")
setConditionalFormat(sh, "$(col)3:$(col)6", :top10; operator = "bottomN", value = "1", style = "Bad")
end
writeods("table_formatted.ods", ods)
- Fonts: Liberation Serif and Liberation Mono come with LibreOffice, so the table looks the same on any computer that has it.
- Fills are solid colours: ODF cells have no fill patterns.
- Number formats:
"Percentage","Currency"and"Number"are named formats; the others are format codes, as Format ▸ Cells ▸ Numbers takes them.
A form to fill in
A form, saved as a template (.ots): LibreOffice opens each use of it as a new, untitled document, so the template itself stays blank. Its cells are formatted with four cell styles, its entry boxes are the only cells that can be changed, and two of them accept only a date or a list.
using OpenDocumentSpreadsheets
ods = newods("Entry")
s = ods["Entry"]
addCellStyle(ods, "Form"; fill = (pattern = "solid", fgColor = "D9D9D9"))
addCellStyle(ods, "Form title"; parent = "Form", font = (size = 18, bold = true))
addCellStyle(ods, "Form section"; parent = "Form", font = (size = 14, bold = true))
addCellStyle(ods, "Form box"; fill = (pattern = "solid", fgColor = "FFFFFF"),
border = (allsides = ["style" => "thin", "color" => "000000"],),
alignment = (vertical = "top", wrapText = true))
setCellStyle(s, "A1:K40", "Form")
s["B2"] = "Catalogue Entry Form"
s["B5"] = "User Data"
s[[7, 9, 11, 14, 16], 2] = ["Recipient ID", "Recipient Name", "Address", "Town", "Postcode"]
s[[18, 20], 2] = ["Ward", "Region"]
s[[18, 20], 8] = ["Local Authority", "Constituency"]
s["B22:J22"] = ["Grant ID" "" "Grant Date" "" "Grant Amount" "" "Grant Title" "" "Distributor"]
s["B29"] = "Summary"
s[[31, 33, 35], 2] = ["Summary Name", "Headline", "Description"]
s[31, 8] = "Use for Comms"
setCellStyle(s, "B2", "Form title")
setCellStyle(s, "B5,B29", "Form section")
setCellStyle(s, "D7,D9:H9,D11:G13,D14,D16,D18,D20,J18,J20,B23:J27,D31:F31,J31,D33:J33,D35:J39", "Form box")
mergeCells(s, "D9:H9,D11:G11,D12:G12,D13:G13,D31:F31,D33:J33,D35:J39")
setColumnWidth(s, 1:2:11; width = 1.3)
setColumnWidth(s, 2:2:10; width = 18)
setRowHeight(s, [3, 4, 6, 8, 10, 15, 17, 19, 21, 28, 30, 32, 34]; height = 5.5)
setRowHeight(s, [5, 29]; height = 18)
setRowHeight(s, 2; height = 23)
addDataValidation(s, "D23:D27"; type = :date, operator = :greaterThan, formula1 = "2020-01-01",
error = "A date after 2020")
addDataValidation(s, "J31"; type = :list, values = ["Yes", "No"])
setCellProtection(s, "D7,D9,D11:D13,D14,D16,D18,D20,J18,J20,B23:J27,D31,J31,D33,D35"; locked = false)
protectSheet(s)
writeods("catalogue.ots", ods)
- Lists of cells and lines:
"D9:H9,D11:G11"names several ranges at once, ands[[7, 9, 11], 2] = …and1:2:11several rows or columns. - Protection: Tools ▸ Protect Sheet is on with no password, so only the unlocked boxes take input; Tools ▸ Protect Sheet again turns it off.
- Validity: the grant dates must be after 2020, and Use for Comms has a Yes/No drop-down.
Data bars in several colours
A data bar's length shows its cell's value; its colour is one for the whole range. Three ways to show more, side by side:
using OpenDocumentSpreadsheets
ods = newods("Bars")
s = ods["Bars"]
s["A1:D1"] = ["Value" "Data bar" "Banded" "Gain or loss"]
v = [0.08, 0.15, 0.27, 0.33, 0.48, 0.52, 0.64, 0.71, 0.86, 0.97]
s["A2:A11"] = v
s["B2:B11"] = v
s["C2:C11"] = v
s["D2:D11"] = round.(v .- 0.45; digits = 2)
setConditionalFormat(s, "B2:B11", :dataBar; showVal = "false")
OpenDocumentSpreadsheets.setColoredDataBars(s, "C2:C11"; breaks = [0.2, 0.4, 0.6, 0.8],
colors = ["red", "orange", "gold", "yellowgreen", "green"], min_type = "num", min_val = "0",
max_type = "num", max_val = "1", showVal = "false")
setConditionalFormat(s, "D2:D11", :dataBar; gradient = "false", fill_col = "2E7D32",
neg_fill_col = "C62828", axis_pos = "middle", axis_col = "000000",
minLength = 0, maxLength = 100)
setColumnWidth(s, "A:D"; width = 14)
- Column B is LibreOffice's data bar (Format ▸ Conditional ▸ Data Bar), here without the values.
- Column C is split into bands of value by
setColoredDataBars, each with a solid bar of its colour on a shared scale from 0 to 1. The bands are those of the values when it is called: if a value changes later, its bar's length follows but its colour doesn't. It needs values, so cells whose formulas LibreOffice hasn't yet calculated can't be banded. It is public but not exported. - Column D uses a data bar's own options: a solid colour for gains and another for losses, an axis in the middle of the cell, and bars from 0 to 100% of its width. These follow the values as they change.
A plot as a picture
A plot made in Julia from a sheet's data, added to the sheet as a picture. First the data:
using OpenDocumentSpreadsheets
ods = newods("Sales")
sh = ods["Sales"]
sh["A1:B1"] = ["Month" "Sales"]
sh["A2:A7"] = ["Jan"; "Feb"; "Mar"; "Apr"; "May"; "Jun";;]
sh["B2:B7"] = [120; 135; 128; 160; 172; 190;;]
writeods("sales.ods", ods)Then the plot, made with CairoMakie (installed with Pkg.add), written to an IOBuffer as a PNG and placed over D2:H12:
using CairoMakie, OpenDocumentSpreadsheets
ods = openods("sales.ods"; mode = "rw")
sh = ods["Sales"]
months = string.(vec(sh["A2:A7"]))
sales = Float64.(vec(sh["B2:B7"]))
fig = Figure(size = (600, 360))
ax = Axis(fig[1, 1]; xticks = (1:6, months), ylabel = "Sales")
barplot!(ax, 1:6, sales)
io = IOBuffer()
show(io, MIME("image/png"), fig)
addImage(sh, "D2:H12", io; alt = "Sales by month, a bar chart")
writeods("sales_plot.ods", ods)
The picture is anchored to the cells and resizes with them. It doesn't change when the data do.
A chart LibreOffice draws
The same data as a chart that LibreOffice draws from the cells, so it follows the data when they change and can be edited in LibreOffice like any chart made there. data gives the whole range, as LibreOffice's chart wizard takes it, with the first row and column as labels:
using OpenDocumentSpreadsheets, OpenDocumentSpreadsheets.Charts
ods = openods("sales.ods"; mode = "rw")
sh = ods["Sales"]
addChart(sh, :column; anchor = "D2:H12", data = "A1:B7", firstRowLabels = true, firstColumnLabels = true)
writeods("sales_chart.ods", ods)
A diverging stacked bar chart
Survey answers on a five-point scale, from strongly disagree to strongly agree, are often shown as a diverging stacked bar chart. Each question gets one bar, the disagreeing answers run left of a central line, the agreeing ones right, and the neutral ones straddle it. Here it is built from the raw counts, with the proportions calculated by formulas, so editing the counts or sorting the table in LibreOffice changes the chart.
The counts
Six questions, with the number of answers at each level. Not every respondent answered every question, so the totals differ. The counts are a database range, so Data ▸ Sort sorts them.
using OpenDocumentSpreadsheets, OpenDocumentSpreadsheets.Charts
questions = ["The course objectives were clear",
"The pace of the course was about right",
"The course materials were useful",
"The assessments were fair",
"I would recommend this course to others",
"The venue was comfortable"]
levels = ["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"]
counts = [2 5 8 20 15
4 10 12 15 7
1 3 6 22 18
6 12 9 12 6
3 6 9 18 14
9 12 9 8 4]
n = length(questions)
last = n + 1
ods = newods("Survey")
s = ods["Survey"]
writetable!(s, [questions, collect.(eachcol(counts))...], ["Question"; levels];
as_table = true, table_name = "Answers")The proportions
Each count is divided by its question's total. To make the bars diverge, the disagreeing proportions are made negative, and the neutral one is split into two halves, one negative and one positive, so that it straddles zero. LibreOffice stacks the negative values outwards from zero in series order, so the neutral half comes first, then disagree, then strongly disagree.
Each column of proportions is one array formula over the six questions, and a column of zeros follows for the legend (below):
headers = ["Neutral (left half)", "Disagree", "Strongly disagree",
"Neutral (right half)", "Agree", "Strongly agree", "Key"]
s["H1:N1"] = permutedims(headers)
total = "(B2:B$last+C2:C$last+D2:D$last+E2:E$last+F2:F$last)"
setFormula(s, "H2:H$last"; val = "=-D2:D$last/2/$total", array = true) # neutral, left half
setFormula(s, "I2:I$last"; val = "=-C2:C$last/$total", array = true) # disagree
setFormula(s, "J2:J$last"; val = "=-B2:B$last/$total", array = true) # strongly disagree
setFormula(s, "K2:K$last"; val = "=D2:D$last/2/$total", array = true) # neutral, right half
setFormula(s, "L2:L$last"; val = "=E2:E$last/$total", array = true) # agree
setFormula(s, "M2:M$last"; val = "=F2:F$last/$total", array = true) # strongly agree
s["N2:N$last"] = 0 # the key: plots nothing
setFormat(s, "H2:M$last"; format = "Percentage")The value axis runs from the furthest reach on the left to the furthest on the right, each rounded out to the next 20%. An axis's bounds are numbers, not formulas, so they are calculated here, from the same counts: −80% and 100%.
p = counts ./ sum(counts; dims = 2)
half = p[:, 3] ./ 2
left = vec(sum(p[:, 1:2]; dims = 2)) .+ half
right = vec(sum(p[:, 4:5]; dims = 2)) .+ half
lo = -ceil(maximum(left) * 5) / 5
hi = ceil(maximum(right) * 5) / 5The chart
A horizontal stacked bar chart below the data, one series per column of proportions, with the questions as categories. The two neutral halves have the same colour, so the split doesn't show.
palette = ["C00000", "F4B183", "FFD966", "A9D18E", "548235"]
cats = "Survey.A2:A$last"
c = addChart(s, :stackedBar; anchor = "A9:N40", title = "Course feedback")
for (col, level) in [('H', 3), ('I', 2), ('J', 1), ('K', 3), ('L', 4), ('M', 5)]
addSeries(c, "Survey.$(col)2:$(col)$last"; categories = cats, name = levels[level], color = palette[level])
endThe legend has an entry for each series, in series order: two Neutral entries, and the disagreeing levels in reverse. So the chart gets five more series, one per level in order, each plotting the column of zeros. They draw nothing, but each has a legend entry, and the entries of the six series that draw the data are hidden:
for level in 1:5
addSeries(c, "Survey.N2:N$last"; categories = cats, name = levels[level], color = palette[level])
end
setLegendEntryDeleted(c, 1:6, true)
setLegendPos(c, :b)Its format
Thin black borders on the bars, and narrower gaps between them:
for i in 1:11
setSeriesLine(c, i; color = "000000", width = 0.75)
end
setGroupGapWidth(c, only(getChartGroups(c)), 50)A bar chart draws its first category at the bottom. Reversing the category axis puts the first question at the top, and the value axis then crosses at the category axis's other end, the bottom. The questions are placed at the left edge of the plot, not beside the zero line where the category axis now sits.
catax = only(getChartAxes(c, :category))
valax = only(getChartAxes(c, :value))
setAxisOrientation(c, catax, :maxMin)
setAxisTickLabelPos(c, catax, :low)
setAxisCrosses(c, valax, :max)The value axis gets the range calculated above, a mark every 20%, and the number format 0%;0%, whose second part, for negative values, has no minus sign, so both sides read as positive.
setAxisScaling(c, valax; min = lo, max = hi)
setAxisMajorUnit(c, valax, 0.2)
setAxisNumberFormatCode(c, valax, "0%;0%")
setAxisTitleText(c, valax, "Proportion of answers")Last, no grid lines, a black border round the plot area, black axes, and all the text in DejaVu Sans, which comes with LibreOffice:
setAxisGridlines(c, valax; major = false)
setPlotAreaLine(c; color = "000000")
font, black = "DejaVu Sans", "000000"
for (ax, size, mark) in ((catax, 12, :cross), (valax, 10, :out))
setAxisLine(c, ax; color = black)
setAxisMajorTickMark(c, ax, mark)
setAxisTextProp(c, ax, :size, size)
setAxisTextProp(c, ax, :font, font)
setAxisTextProp(c, ax, :color, black)
end
setAxisTitleTextProp(c, valax, :size, 11)
setAxisTitleTextProp(c, valax, :font, font)
setChartTitleTextProp(c, :size, 16)
setChartTitleTextProp(c, :font, font)
setLegendTextProp(c, :size, 11)
setLegendTextProp(c, :font, font)
writeods("survey.ods", ods)
Not available
- GROUPBY, PIVOTBY and LAMBDA: LibreOffice has no such functions. A summary by group is made with
AVERAGEIFS,COUNTIFSand the like, as above. - Pivot tables (LibreOffice's Insert ▸ Pivot Table) can't be made or read.
- Formulas that spill into as many cells as their results need: LibreOffice's array formulas have a fixed range.
- Table styles: LibreOffice's database ranges have none; a table is formatted with cell styles, as above.