How do I create an Excel BarChart in UniOffice?
A chart is not a property of a sheet. It lives in a drawing, and the drawing is attached to the sheet. So there are four steps: write the data into cells, add a drawing, add the chart and its series, then hand the drawing to the sheet.
ss := spreadsheet.New()
defer ss.Close()
sheet := ss.AddSheet()
// The chart reads its numbers out of cells, so write them first.
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
}
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
bc := chart.AddBarChart()
series := bc.AddSeries()
series.SetText("Price")
series.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
series.Values().SetReference(`'Sheet 1'!B2:B6`)
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
bc.AddAxis(ca)
bc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
sheet.SetDrawing(dwng)Swapping AddBarChart for AddLineChart, AddPieChart or any of the other
constructors is the only change needed for a different chart type. Everything
around it is the same.
Things that catch people out
A series holds a cell reference, not values. The numbers must exist in the sheet even when the chart is the only reason for them. The reference is written into the file unparsed, so a wrong range fails when Excel opens the file, not when Go writes it.
Quote the sheet name. AddSheet names sheets Sheet 1, Sheet 2 and so on
with a space, which is why every reference above reads 'Sheet 1'!A2:A6.
Axes must cross each other. A bar chart needs a category axis and a value
axis, added to the chart and then associated with the plot, with SetCrosses
called both ways. Miss that pairing and Excel has no reference axis to draw
against. The pie family is the exception: it has no axes at all.
The anchor type decides which setters work. With AnchorTypeTwoCell use
SetWidthCells and SetHeightCells; SetWidth and SetHeight are silent
no-ops on it, and the reverse is true for AnchorTypeOneCell. This is the usual
reason a chart comes out the wrong size.
One drawing per sheet. Several charts on one sheet all go into the same
Drawing.
Validate() does not inspect charts, so a chart with a missing axis or a bad
range saves without complaint.
The chart guides cover every type, with a table of which constructor produces which chart and what data shape it takes.