Building an Excel Table

In the case of Excel, I've used a slightly different approach and worked with the application object. The code creates a new Excel spreadsheet, fills it with a database table, and formats the result. It uses an Excel internal object, Range, which is not to be confused with a similar type available in Word (the reason this type is prefixed with the name of the unit defining the Excel type library). Here is the complete code:

procedure TFormOff.BtnExcelClick(Sender: TObject); var

RangeE: Excel97.Range; I, Row: Integer; Bookmark: TBookmarkStr; begin

// create and show

  1. Visible [0] := True; ExcelApplication1.Workbooks.Add (NULL, 0); // fill is the first row with field titles RangeE := ExcelApplication1.ActiveCell; for I := 0 to Table1.Fields.Count - 1 do begin
  2. Value := Table1.Fields [I].DisplayLabel; RangeE := RangeE.Next; end;

// add field data in following rows


Bookmark := Table1.Bookmark; try

while not Table1.EOF do begin

RangeE := ExcelApplication1.Range ['A' + IntToStr (Row),

'A' + IntToStr (Row)]; for I := 0 to Table1.Fields.Count - 1 do begin

  1. Value := Table1.Fields [I].AsString; RangeE := RangeE.Next; end;
  2. Next; Inc (Row); end; finally
  3. Bookmark := Bookmark; end; finally
  4. EnableControls; end;

// format the section

RangeE := ExcelApplication1.Range ['A1', 'E' + IntToStr (Row - 1)]; RangeE.AutoFormat (3, NULL, NULL, NULL, NULL, NULL, NULL); end;

You can see the effect of this code in Figure 20.10. Notice that in the code I don't handle any events of the Office applications, but many are available. Handling these events was quite complex in the past, but they now become as simple to handle as events of native Delphi components. The presence of these events is a reason to have specific objects for documents and other specific elements: you might want to know when the user closes a document, and that therefore this is an event of the document object, not of the application object.

Was this article helpful?

0 0
Self Publishing a Book The Easy Way

Self Publishing a Book The Easy Way

This comprehensive guide will present you with a variety of self-publishing options and explore their viability. Well take a look at all types of books and book-delivery systems.

Get My Free Ebook

Post a comment