C++ Builder Tutorials

C++Builder - ClientDataSet, part 5

Because the free Starter edition of C++Builder does not include a Report Generator, we build our own.

We'll write reports as HTML files. Thus, we don't have to re-invent the wheel in writing a printing routine.


Preparations

  1. If you haven't done so already, create a new folder \CppProjects on your disk.
  2. Create folder XMLDatabase5 "under" \CppProjects.
  3. Download XMLDatabase5.zip and unzip it to folder XMLDatabase5.
  4. Compile and run the application, immediately stop it and next copy Articles.xml from folder XMLDatabase5 to folder XMLDatabase5\Win32\Debug.

Writing a report to an HTML file

For this tutorial, we simplified our application a bit, in order to make it easier to spot the new code.
Later, you can add that code to XMLDatabase4 if you wish.

We added two buttons, btnReport and btnReportView.

Clicking btnReport writes the code for our report file into a TMemo component and next saves the lines of the TMemo to disk:

{
  String SLine;
  Memo1->Clear();
  Memo1->Lines->Add("<!DOCTYPE html><html><head><title>Report</title></head>");
  Memo1->Lines->Add("<body><table cellspacing='0' cellpadding='3' border='1'>");
  Memo1->Lines->Add("<tr><td>ID</td><td>Name</td><td>Type</td><td>Price</td><td>Stock</td></tr>");
  cdsArt->First();
  while (!(cdsArt->Eof)) {
    SLine = "<tr><td>" + cdsArt->FieldByName("ID")->AsString + "</td>";
    SLine += "<td>" + cdsArt->FieldByName("Name")->AsString + "</td>";
    SLine += "<td>" + cdsArt->FieldByName("Type")->AsString + "</td>";
    SLine += "<td align='right'>" + FormatFloat("0.00",
      cdsArt->FieldByName("Price")->AsFloat) + "</td></td>";
    SLine += "<td align='right'>" + cdsArt->FieldByName("Stock")->AsString +
      "</td></tr>";
    Memo1->Lines->Add(SLine);
    cdsArt->Next();
  };
  Memo1->Lines->Add("</table></body></html>");
  Memo1->Lines->SaveToFile(ReportFile);
}

You could add some CSS code to the HTML for formatting, selecting another font, and so on...

Clicking btnReportView opens the HTML file in your default browser, from where you can print it:

void __fastcall TForm1::btnReportViewClick(TObject *Sender)
{
  if (FileExists(ReportFile))
    // ShellExecute does not accept Unicode strings, use S.c_strc()
    ShellExecute(NULL, L"open", ReportFile.c_str(), NULL, NULL, SW_SHOWNORMAL);
  else
    ShowMessage("Firstly, create a report");
}