Using Delphi to Control MS Office via COM
Variant | Interface | |
Opening Excel and creating a new workbook | var sht: Variant; XLApp := CreateOLEObject('Excel.Application'); XLApp.Visible := true; XLApp.Workbooks.Add(xlWBatWorkSheet); XLApp.Workbooks[1].WorkSheets[1].Name := 'My Worksheet'; sht := XLApp.Workbooks[1].WorkSheets['My Worksheet']; sht.Cells[1,1] := 'First Cell'; sht.Cells.Item[1,10] := '=SUM(A2:A9)'; |
var wsht: _Worksheet; wbks: WorkBooks; wshts: Sheets; wbk: WorkBook; XLApp := Excel_TLB.CoApplication_.Create; XLApp.Visible[0] := True; wbks := XLApp.WorkBooks as WorkBooks; wbks.Add(XLWBatWorksheet,0); wbk := wbks.Item[1]; wshts := wbk.WorkSheets; wsht := wshts.Get_Item(1) as _WorkSheet; wsht.Name := 'My Worksheet'; wsht.Cells.Item[1,1] := 'First cell'; wsht.Cells.Item[1,10] := '=SUM(A2:A9)'; |
Examples of use: | var range, Col: Variant; range := XLApp.Workbooks[1].WorkSheets['My Worksheet'].Range['A2:A9']; range.Formula := 'RAND()'; range.Columns.Interior.ColorIndex := 3; range.Borders.LineStyle := xlContinuous; Col := XLApp.Workbooks[1].WorkSheets['My Worksheet'].Columns; Col.Columns[1].ColumnWidth := 5; Col.Columns[1].Font.Bold := True; Col.Columns[1].Font.Color := clBlue; |
|
Adding a chart: | var ARange, shts: variant; XLApp.WorkBooks[1].Sheets.Add(,,1,xlChart); shts := XLApp.Sheets; ARange := shts.item['My Worksheet'].Range['A1:A9']; shts.Item['Chart1'].SeriesCollection.Item[1].Values := ARange; //nb. instead of ARange could supply values via = VarArrayOf([val1,val2,..]) shts.Item['Chart1'].ChartType := xl3DPie; shts.Item['Chart1'].SeriesCollection.Item[1].HasDataLabels := True; // now lets copy chart to clipboard shts.Item['Chart1'].Select; XLApp.Selection.Copy; //now lets copy range of cells to clipboard: shts.Item['My Worksheet'].Activate; shts.Item['My Worksheet'].Range['A1:A9'].Select; shts.Item['My Worksheet'].UsedRange.Copy; |
var aRange: Excel_TLB.Range; aWsht:
Worksheet; aChrt: Chart; Index: OLEVariant;
aSeries: Series; aSeriesColl: SeriesCollection; aWsht := WorkSheets.Item['My Worksheet'] as Worksheet; aRange := aWsht.Range['A1', 'A9']; aChrt := XLApps.WorkBooks.Item[1].Sheets.Add(EmptyParam,EmptyParam,1,xlChart,0) as Chart; Index := 1; aSeries := aChrt.SeriesCollection(Index, 0) as Series; aSeries.Values := aRange; aChrt.ChartType := xl3DPie; aSeries.HasDataLabels := True; //copy chart: nb. aChrt.Copy(EmptyParam,EmptyParam,0) copies chart to excel NOT to clipboard, thus need to use variants (V) to copy to clipboard: aChrt.Activate; aChrt.Select(EmptyParam,0); V := aChrt.Application_; V.Selection.Copy; //can copy range OK though: ?? SetFocus aWsht.Activate(0); aRange := aWsht.Range['A1', 'A9']; aRange.Select; aRange := aWsht.UsedRange(0); aRange.Copy(EmptyParam); |
Closing application: | if not VarIsEmpty(XLApp) then XLApp.Quit; | if not VarIsEmpty(XLApp) then XLApp.Quit; |