Technical Article

BIFF8 Chart Secondary Axis Groups in Delphi with HotXLS

A Classic .xls column-and-line chart with a secondary value scale carries four Axis records, and the AXESUSED record in front of them holds the number 2, not 4. The record name reads as an axis count, so the natural first attempt at a dual-axis chart is to write more axes and bump the counter, and that attempt produces a file whose second series has nowhere to attach. AXESUSED counts axis groups, and in the BIFF8 chart grammar every axis group is a complete block that owns its own plot area and its own chart group

Why does a second chart group after the axes bind nothing?

The grammar settles it in two lines of ABNF. The CHARTFOMATS rule in [MS-XLS] 2.1.7.20.1 reads AxesUsed 1*2AXISPARENT, and the next production spells out AXISPARENT = AxisParent Begin Pos [AXES] 1*4CRT End. Put those side by side and the shape is fixed: chart groups are children of an axis group. A substream with two axis pairs followed by one trailing chart group is a chart with one chart group and a handful of axis records that belong to nothing

The binding record makes the consequence concrete. SerToCrt ($1045) sits inside each series' format block and carries a zero-based chart group index, which is a different thing from an axis index. Writing crt = 1 into a file that contains only one CRT block points the series at a chart group that was never written. So the second value scale is not something you add to an existing group; you get it by emitting a second AxisParent block, and that block drags a full Pos, axis pair, plot area, ChartFormat, chart type record and CrtLink along with it

The BIFF8 chart grammar HotXLS follows in Delphi: CHARTFOMATS reads AxesUsed 1*2AXISPARENT and AXISPARENT wraps AxisParent, Begin, Pos, axes and one to four CRT blocks, so each ChartFormat and CrtLink chart group lives inside an axis group, while a chart group emitted after End leaves SerToCrt pointing at nothing
The ABNF makes the nesting explicit: a chart group is a child of its axis group, so a trailing CRT after the axes is not a secondary group but a set of orphan records

Marking a series for the secondary axis group in Delphi

HotXLS reduces all of that to one Boolean per series. TXLSChartSeriesInfo (unit lxChartBuilder) has a SecondaryAxis field, and setting it on any entry of the series array you pass to TXLSWorksheets.AddChartSheet puts the chart builder into two-group mode. There is no separate switch and no axis-count argument. The count follows from the series: if one of them asks for the secondary group, the chart gets two

var
  Wb: TXLSWorkbook;
  ChartSheet: TXLSWorksheet;
  Series: array [0..1] of TXLSChartSeriesInfo;
begin
  Wb := TXLSWorkbook.Create;
  try
    Wb.Sheets.Add.Name := 'Data';
    // ... fill A1:C12 with months, revenue and margin percentage ...

    Series[0] := Default(TXLSChartSeriesInfo);   // never FillChar this record
    Series[0].Name := 'Revenue';
    Series[0].Categories := 'Data!$A$1:$A$12';
    Series[0].Values := 'Data!$B$1:$B$12';

    Series[1] := Default(TXLSChartSeriesInfo);
    Series[1].Name := 'Margin %';
    Series[1].Categories := 'Data!$A$1:$A$12';
    Series[1].Values := 'Data!$C$1:$C$12';
    Series[1].SecondaryAxis := True;             // AXESUSED becomes 2

    ChartSheet := Wb.Sheets.AddChartSheet('Revenue and Margin',
      xlsChartTypeLine, 'Revenue vs Margin', 'Month', 'Revenue', Series);
    Wb.SaveAs('dual-axis.xls', xlExcel97);
  finally
    Wb.Free;
  end;
end;

The Default(TXLSChartSeriesInfo) lines matter because Delphi clears only the managed fields of a local record, so an uninitialised SecondaryAxis is whatever was on the stack and can flip the chart between one and two axis groups. FillChar happens to work on a fresh local, but on an array reused in a loop it zeroes strings and arrays that are already assigned and leaks them

The range strings need a sheet prefix. Each one resolves through the workbook's EXTERNSHEET table before the builder sees it, the same index machinery described in how HotXLS classifies BIFF SupBook and XTI external links. A range that names a sheet the workbook does not have, or names the chart sheet itself, becomes an empty placeholder BRAI record, so Excel opens the file and shows the chart frame with no data in that series

The record sequence HotXLS writes for two axis groups

With no secondary series the builder writes AXESUSED = 1 and one AxisParent block with iax = 0. Pie and 3D pie charts get the same, with no Axis records inside the group. Once any series sets SecondaryAxis, AXESUSED holds 2 and the block is written twice, with iax (the first word of the 18-byte AxisParent payload, record $1041) set to 0 and then 1

Each pass writes the same skeleton:

  • AxisParent, Begin ($1033) and a Pos record for the group
  • a category axis and a value axis, both Axis ($101D) blocks with their own range and tick records
  • the PlotArea marker ($1035) and a default Frame
  • ChartFormat ($1014), Begin, the chart type record, CrtLink ($1022), then an End for the chart group and a second End for the axis group

Series bind by position in that list. A primary series writes SerToCrt with crt = 0; a series with SecondaryAxis = True writes crt = 1. A few records are written once rather than per group. The legend goes into the first chart group only, because an Excel chart has one legend no matter how many axis groups it holds. The CatAxisTitle and ValAxisTitle arguments of AddChartSheet label the primary axes, and the secondary value axis comes out untitled; if the margin scale needs a caption, the chart title or the series name is where that text goes

The record sequence HotXLS emits for a Delphi dual-axis chart sheet: SecondaryAxis True raises AXESUSED to 2, two AxisParent blocks with iax 0 and 1 each carry Pos, Axis, PlotArea, Frame, ChartFormat, the chart type record and CrtLink, and SerToCrt binds the primary series to group 0 and the secondary to group 1
Setting SecondaryAxis on one series switches the builder into two-group mode, and each pass emits a complete axis pair and chart group, with the legend deliberately written only once

The secondary group always arrives with its own category axis, even though a revenue-and-margin chart only cares about the second value scale. That extra Axis block costs a few dozen bytes and buys two groups of identical shape, so any reader that walks AXISPARENT blocks finds the same structure twice. That is the right trade for a binary format with no schema validator to catch a missing record. One more difference shows up with trendlines: on a dual-axis chart, linear trendlines are written as Trendline records inside each series block rather than as separate auxiliary series

Reading the axis-group binding back

TXLSCustomChart.GetChartModel walks the chart record list twice, and the order of the records forces that. AXESUSED appears before the blocks it describes, so the first pass reads its first word as the group count while it collects chart type, series count and legend. The count starts at 1 and only goes up: the model keeps the larger of the current value and the declared one, so a duplicated or malformed AXESUSED later in the stream cannot pull a chart that already declared two groups back down to one. The second pass tracks the current group, updates it at every AxisParent, and stamps that index onto each Axis record until the next AxisParent shows up

How HotXLS chart inspection recovers axis-group bindings in two passes: the first scan reads the AXESUSED $1046 word as the group count and never lowers it, the second tracks the current AxisParent and stamps every Axis record with that index, and the model reports AxisGroupCount, axis stamps 0 0 1 1 and series groups 0 and 1
Two passes are required because AXESUSED arrives before the blocks it describes, so the count is read first and the positional axis stamps are applied on a second walk of the record list
var
  Model: TXLSChartModel;
  i: Integer;
begin
  // ChartSheet is the result of AddChartSheet, or a chart sheet
  // from a workbook loaded from .xls
  // _Chart exposes the sheet's chart record list
  Model := ChartSheet._Chart.GetChartModel;   // caller owns the model
  try
    Writeln('declared axis groups: ', Model.AxisGroupCount);
    for i := 0 to Model.AxisCount - 1 do
      Writeln('axis ', i, ' type ', Ord(Model.GetAxis(i).AxisType),
        ' group ', Model.GetAxis(i).AxisGroup);
    for i := 0 to Model.SeriesCount - 1 do
      Writeln('series ', i, ' chart group ', Model.GetSeries(i).ChartGroup);
  finally
    Model.Free;
  end;
end;

For the chart built in the first example this prints a group count of 2, four axes stamped 0, 0, 1, 1, and series chart groups 0 and 1. With files you did not write, keep in mind that TXLSChartModel.AxisGroupCount is what the file declares: a file that says 2 and contains one AxisParent block still reports 2, and AxisCount is where the gap shows. TXLSChartAxis.AxisGroup is positional, recording which block the axis sat in. On the series side, SerToCrt is decoded only inside a series block, since the same record id can turn up in other contexts, and a decoder that accepts it anywhere would overwrite the binding of whichever series happened to be current

Checking a decoder with a synthesised record sequence

Structural decoding depends only on the order and payloads of the records, so a hand-built sequence exercises it exactly as a captured Excel file would. TXLSCustomChart (unit lxChart) accepts raw records through AddData, and TXLSBlob (unit lxBlob) builds the payloads:

// Reader-side helper (not part of the library): one record with a 2-byte payload
procedure AddWordRecord(Chart: TXLSCustomChart; RecId, Value: Word);
var
  B: TXLSBlob;
begin
  B := TXLSBlob.Create(2);
  try
    B.AddWord(Value);
    Chart.AddData(RecId, B.DataLength, B);   // AddData copies the payload
  finally
    B.Free;
  end;
end;

procedure AddAxisGroup(Chart: TXLSCustomChart; Iax: Word);
begin
  AddWordRecord(Chart, $1041, Iax);   // AxisParent, iax in the first word
  Chart.AddData($1033, 0, nil);       // Begin: length 0, no payload
  AddWordRecord(Chart, $101D, 0);     // Axis, wType 0 = category
  AddWordRecord(Chart, $101D, 1);     // Axis, wType 1 = value
  Chart.AddData($1034, 0, nil);       // End
end;

var
  Chart: TXLSCustomChart;
  Model: TXLSChartModel;
begin
  Chart := TXLSCustomChart.Create(nil, $0600);
  try
    AddWordRecord(Chart, $1046, 2);   // AXESUSED: two axis groups
    AddAxisGroup(Chart, 0);
    AddAxisGroup(Chart, 1);
    Model := Chart.GetChartModel;
    try
      // Reader-added check: expect 2, 4, then groups 0 and 1
      if (Model.AxisGroupCount <> 2) or (Model.AxisCount <> 4) or
         (Model.GetAxis(1).AxisGroup <> 0) or
         (Model.GetAxis(2).AxisGroup <> 1) then
        raise Exception.Create('axis-group decode mismatch');
    finally
      Model.Free;
    end;
  finally
    Chart.Free;
  end;
end;

The Begin and End lines are where hand-built sequences usually go wrong. AddData(RecId, Len, nil) reads the payload whenever Len is non-zero, so a marker added with a nil blob and a leftover length raises an access violation. Markers take a length of 0

If you write your own decoder for these records, Pascal has one trap that fits this exact code shape. A record dispatcher is usually a long if RecID = ... then ... else if ... chain, and the AXESUSED branch wants a nested test (only raise the count when the new value is larger). Written as a bare nested if without begin/end, that inner if captures the next else, and every branch after AXESUSED in the chain stops running while AXESUSED itself keeps working, and a test that checks only the group count will not notice. Wrap any branch that contains a nested if in begin/end

A synthesised sequence proves the reader only. For the write side, save the chart built with AddChartSheet, reload it, and confirm stamps 0/0/1/1 and series groups 0/1 through GetChartModel. The record layouts themselves come from the [MS-XLS] text, which is the posture behind the rest of the HotXLS chart, image and drawing support for Delphi

Chart3d scene parameters and the fAuto trap

Two more records come up as soon as a chart moves past the defaults. Chart3d ($103A, [MS-XLS] 2.4.46) is a flat 14-byte payload written inside the chart group for the 3D chart types: rotation anRot, signed elevation anElev, perspective distance pcDist, pcHeight and pcDepth as percentages of chart width, pcGap, and a grbit with fPerspective $0001, fCluster $0002 and fAutoscale $0004 among its flags. The spec adds limits the layout cannot enforce: on a transposed bar chart anRot and anElev must not exceed 44, and on a pie chart anElev must not be negative. HotXLS exposes these fields through TXLSChart3DInfo and the AddChartSheet overload that takes it. With Has3D left False, a 3D chart type gets 20 degrees of rotation, 15 of elevation, 100% height and depth, a gap of 150 and the fCluster plus fAutoscale bits

The second record family produces the "my colours were ignored" report. LineFormat ($1007), AreaFormat ($100A) and MarkerFormat ($1009) all keep fAuto in bit 0 of their grbit. With that bit set, Excel applies its automatic style and ignores the explicit RGB values, line style, marker shape and marker size stored right beside it. The default HotXLS series formats set the bit on purpose so Excel picks colours from its palette. A per-series style switches it off:

// Give the secondary-axis series an explicit look; the builder writes
// LineFormat and MarkerFormat with fAuto cleared for this series
Series[1].HasStyle := True;
Series[1].Style.HasLine := True;
Series[1].Style.LineRgb := $000000C0;      // LongRGB: red is the low byte
Series[1].Style.LineStyle := 0;            // solid
Series[1].Style.HasMarker := True;
Series[1].Style.MarkerImk := 8;            // circle
Series[1].Style.MarkerRgbFore := $000000C0;
Series[1].Style.MarkerRgbBack := $00FFFFFF;
Series[1].Style.MarkerSize := 6;           // points, 2 to 72

Editing a workbook someone else built follows different rules, because the chart's existing records have to survive the save; that case is covered in editing Excel charts without losing preserved ChartML

The HotXLS spreadsheet component for Delphi and C++Builder writes these dual-axis BIFF8 charts and reads their axis groups back through GetChartModel without Excel on the machine; its product page lists every AddChartSheet overload together with the chart record reference