Technical Article

A Live Excel Sales Dashboard in Delphi with HotXLS

An Excel dashboard can show the new sales total beside a chart that still shows yesterday's figures. With HotXLS, use one XLSX workbook for the editor and the export, recalculate its formulas after each committed edit, and refresh the chart data from the recalculated cells before saving or drawing the preview.

HotXLS dashboard flow: a committed cell edit is recalculated, the chart cache is refreshed, and the same workbook feeds the preview and the export
The same workbook carries a committed edit through recalculation and the chart cache refresh to the preview and the export

A dashboard generated from editable detail rows

Put customer or sales inputs on a Details sheet and reserve a Dashboard sheet for formulas, charts, and presentation. In the small example below two rows belong to Q1 and one belongs to Q2, and users change the quantities and unit prices in those detail rows. The dashboard has one formula for each quarter, so its numbers respond to those edits without copying data back from a painted chart or text label. One more placement rule. Make Dashboard the first worksheet if you intend to export it by index as CSV.

uses
  lxHandleX;

procedure BuildDashboard(Book: TXLSXWorkbook; out Chart: TXLSXChart);
var
  Dashboard, Details: TXLSXWorksheet;
begin
  Dashboard := Book.Sheets.Add('Dashboard');
  Details := Book.Sheets.Add('Details');
  Details.Cells[1, 3].Value := 'Quarter';
  Details.Cells[1, 4].Value := 'Units';
  Details.Cells[1, 5].Value := 'Unit price';
  Details.Cells[1, 6].Value := 'Revenue';
  Details.Cells[2, 3].Value := 'Q1';
  Details.Cells[2, 4].Value := 12;
  Details.Cells[2, 5].Value := 10;
  Details.Cells[2, 6].Formula := 'D2*E2';
  Details.Cells[3, 3].Value := 'Q1';
  Details.Cells[3, 4].Value := 2;
  Details.Cells[3, 5].Value := 10;
  Details.Cells[3, 6].Formula := 'D3*E3';
  Details.Cells[4, 3].Value := 'Q2';
  Details.Cells[4, 4].Value := 5;
  Details.Cells[4, 5].Value := 20;
  Details.Cells[4, 6].Formula := 'D4*E4';

  Dashboard.Cells[3, 1].Value := 'Quarter';
  Dashboard.Cells[3, 3].Value := 'Revenue';
  Dashboard.Cells[4, 1].Value := 'Q1';
  Dashboard.Cells[5, 1].Value := 'Q2';
  Dashboard.Cells[4, 3].Formula := 'SUMIF(Details!$C$2:$C$4,A4,Details!$F$2:$F$4)';
  Dashboard.Cells[5, 3].Formula := 'SUMIF(Details!$C$2:$C$4,A5,Details!$F$2:$F$4)';
  Dashboard.Cells[6, 1].Value := 'TOTAL';
  Dashboard.Cells[6, 3].Formula := 'SUM(C4:C5)';
  Dashboard.Range['C4:C6'].SetNumberFormat('"$"#,##0.00');
  Dashboard.Cells[8, 1].Value := 'Open the detail rows';
  Dashboard.AddHyperlinkToCell(8, 1, 'Details!C1', 'Open the detail rows');
  Details.SetAutoFilter('C1:F4');
  Chart := Dashboard.AddChart(xlsxChartColumn, 'Quarterly revenue', 3, 6, 16, 12);
  Chart.AddSeries('Revenue', 'Dashboard!$A$4:$A$5', 'Dashboard!$C$4:$C$5');
end;

At the starting prices, Q1 contributes 140 and Q2 contributes 100. For a scenario button, keep a baseline array of input prices and set each price to its baseline multiplied by the factor. Raise all three prices by 10%. The expected values are 154 and 110. Applying the same factor twice should produce the same figures each time. Multiplying the current cells on each click compounds the increase, so the second click would push the total above 264 even though the UI still says "+10%." Decide how manual price edits affect that baseline. Label the control accordingly.

The example stops at row 4. In a real order feed, derive the last row from the number of records written and use it for both SUMIF ranges and the AutoFilter. A fourth order appended below row 4 can look like part of the table whilst contributing nothing to the summary. A Q2 order for 3 units at 20 makes that visible. Once both ranges reach row 5 the Q2 result rises from its original 100 to 160, and the dashboard still has two points because the number of quarters has not changed.

Refreshing the chart data after calculating the workbook

Give each chart series references to the worksheet categories and values. To keep an in-process preview in step with an edit, rebuild the chart series caches from the calculated dashboard values as part of the refresh. Call it again after changing price inputs. Do so before drawing or exporting the current view. The chart references still point to the worksheet, so Excel can work with those cells when the recipient opens the XLSX.

uses
  SysUtils, Variants, lxHandleX;

procedure RefreshRevenueChart(Book: TXLSXWorkbook; Chart: TXLSXChart);
const
  FirstQuarterRow = 4;   // Dashboard rows 4 and 5 hold Q1 and Q2
  QuarterCount = 2;      // the rows the series ranges A4:A5 and C4:C5 cover
var
  Dashboard: TXLSXWorksheet;
  Series: TXLSXChartSeries;
  Labels: array[0..QuarterCount - 1] of string;
  Amounts: array[0..QuarterCount - 1] of Double;
  Settings: TFormatSettings;
  I: Integer;
begin
  if Book.Recalculate <> 1 then
    raise Exception.Create('Dashboard calculation failed');
  Dashboard := Book.Sheets.SheetByName('Dashboard');
  if Dashboard = nil then
    raise Exception.Create('Missing Dashboard sheet');

  for I := 0 to QuarterCount - 1 do
  begin
    Labels[I] := VarToStr(Dashboard.Cells[I + FirstQuarterRow, 1].Value);
    Amounts[I] := Double(Dashboard.Cells[I + FirstQuarterRow, 3].Value);
  end;

  Settings := FormatSettings;
  Settings.DecimalSeparator := '.';
  Series := Chart.Series[0];
  Series.CategoryCache.Clear;
  Series.CategoryCache.Kind := xlsxChartCacheString;
  Series.ValueCache.Clear;
  Series.ValueCache.Kind := xlsxChartCacheNumber;
  for I := 0 to QuarterCount - 1 do
  begin
    Series.CategoryCache.Add(I, Labels[I]);
    Series.ValueCache.Add(I, FloatToStr(Amounts[I], Settings));
  end;
end;

Read all the points before clearing either cache. A numeric conversion error will surface whilst the chart still has both of its previous caches. The decimal point in the cache text is independent of the workstation's locale, so a label on a French screen can still use the local comma. For a dashboard with a second chart, collect its points from the same recalculation pass, then update both charts. The HotXLS drawing and chart guide explains the underlying worksheet and drawing objects.

A refresh also needs a deliberate axis scale. On a price-comparison screen, an automatic axis can make a 10% rise look smaller if the entire scale changes between views. If the comparison is the main job, keep a shared maximum high enough for both scenarios, which is what the next procedure pins through ValueAxis.MaxValue. If you use a calculated maximum for a single dashboard view, derive it from the new data points, with extra room above the highest bar so a data label fits. A well-chosen maximum for one release may be too small after a batch of large orders appears.

uses
  lxHandleX;

// Baseline and +10% views of the example both fit under one fixed scale
procedure PinRevenueAxis(Chart: TXLSXChart);
const
  SharedMaximum = 200;   // above every bar the example produces
begin
  Chart.ValueAxis.MinValue := 0;
  Chart.ValueAxis.MaxValue := SharedMaximum;
end;

A C++Builder preview connected to the exported workbook

Point TXLSWorkbookViewer.XlsxWorkbook at the workbook that will be saved. Set WorksheetIndex := 1 and Editable := True during setup. Keep worksheet navigation out of the export handler. Switching worksheets can cancel an active cell edit. In Delphi or C++Builder, an active cell editor can hold the user's latest input until it is committed. Finish that edit, recalculate and refresh the existing workbook, and save from the same object.

If you provide a formula bar, EditSelectedCell gives it the viewer's edit path. Store scenario changes through the viewer's edit flow if you want them to participate in undo. A handler that writes cells directly leaves no entry in that history, and that has a visible cost: Ctrl+Z can put an earlier cell value back into the new scenario. The switch for that is UndoLimit. Assigning 0 empties both the undo and the redo stacks. Assigning the previous limit afterwards restores the capacity, so typed edits made later can still be undone.

#include <System.SysUtils.hpp>
#include <System.Variants.hpp>
#include "lxHandleX.hpp"
#include "lxWorkbookViewer.hpp"

void RefreshRevenueChart(TXLSXWorkbook *book, TXLSXChart *chart)
{
    const int FirstQuarterRow = 4;   // Dashboard rows 4 and 5 hold Q1 and Q2
    const int QuarterCount = 2;      // the rows the series ranges A4:A5 and C4:C5 cover

    if (book->Recalculate() != 1)
        throw System::Sysutils::Exception(L"Dashboard calculation failed");
    TXLSXWorksheet *dashboard = book->Sheets->SheetByName(WideString(L"Dashboard"));
    if (!dashboard)
        throw System::Sysutils::Exception(L"Missing Dashboard sheet");

    WideString labels[QuarterCount];
    double amounts[QuarterCount];
    for (int i = 0; i < QuarterCount; ++i)
    {
        labels[i] = WideString(System::Variants::VarToStr(
            dashboard->Cells->Item[i + FirstQuarterRow][1]->Value));
        amounts[i] = dashboard->Cells->Item[i + FirstQuarterRow][3]->Value;
    }

    TFormatSettings settings = FormatSettings;
    settings.DecimalSeparator = L'.';
    TXLSXChartSeries *series = chart->Series[0];
    series->CategoryCache->Clear();
    series->CategoryCache->Kind = xlsxChartCacheString;
    series->ValueCache->Clear();
    series->ValueCache->Kind = xlsxChartCacheNumber;
    for (int i = 0; i < QuarterCount; ++i)
    {
        series->CategoryCache->Add(i, labels[i]);
        series->ValueCache->Add(i, WideString(FloatToStr(amounts[i], settings)));
    }
}

// OutputFile is the XLSX path; the CSV takes the same path with a .csv extension
void ExportDashboard(TXLSWorkbookViewer *viewer, TXLSXChart *revenueChart,
    const UnicodeString &OutputFile)
{
    TXLSXWorkbook *book = viewer->XlsxWorkbook;
    if (viewer->Editing && !viewer->CommitEdit())
        throw System::Sysutils::Exception(L"Finish the current edit before exporting");
    RefreshRevenueChart(book, revenueChart);
    if (book->SaveAs(WideString(OutputFile)) != 1)
        throw System::Sysutils::Exception(L"Could not save the dashboard workbook");
    book->CSVEmitFormulas = false;
    if (book->SaveAsCSV(WideString(ChangeFileExt(OutputFile, L".csv")), 0, L',') < 0)
        throw System::Sysutils::Exception(L"Could not export dashboard values");
}

The viewer setup uses worksheet index 1, and the CSV export uses index 0. Different APIs, same first sheet. XLSX carries the editable formulas, detail sheet, and chart together. CSV carries the selected sheet's data. For an HTML or PDF copy, use SaveAsHTML for a selected worksheet or set the print area and call SaveAsPDF for a fixed layout. Generate those copies after the same edit and refresh sequence. See the Excel export format guide for the result each format carries.

Make the unit price available on the same detail row as its quantity and preserve both cells as numeric inputs. A percentage attached to the interface can be implemented as a scenario action, and a typed cell can still be cleared or pasted. Handle both cases before asking the user to export. The formula D2*E2 also gives a place to spot a bad input. Evaluate the changed order's revenue as well as the aggregate if the editor accepts pasted values, because a total assembled from several rows can make the cause of a single skewed amount difficult to find.

One price change checks every output

Save a baseline and a scenario workbook, then reopen the scenario XLSX and check Dashboard!C4, C5, and C6 for 154, 110, and 264 with the 10% change above. In the preview, the chart should show those same quarter values. The CSV should carry the recalculated numbers. One stronger check is to edit the quantity on a single Q1 row and verify that Q2 stays fixed. That separates a chart series reading the wrong cells from an ordinary rounding or formatting difference.

Check the overall row independently from the quarter rows. A chart that accidentally includes C6 in the plotted range will show an extra 264 bar, even though each displayed value came from a valid cell. A chart aimed at the data range C4:C5 should have exactly two points, and both the labels and numeric cache indexes should align with that range. Compare the preview with the last saved XLSX. If they differ, confirm that the export command used the preview's workbook and completed the active edit before starting its recalculation.

The workbook, viewer, and export APIs are available in the HotXLS spreadsheet component for Delphi and C++Builder.