testcom2.pp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. {$ifdef FPC}
  2. {$mode objfpc}
  3. {$endif FPC}
  4. program excel;
  5. uses variants,Windows,activeX,comobj;
  6. Const
  7. IID_IDISPATCH : TGUID = '{00020400-0000-0000-C000-000000000046}';
  8. Type
  9. tArguments = array[0..63] of variant;
  10. ExcelRange = dispinterface ['{00020846-0000-0000-C000-000000000046}']
  11. property _Default[{optional}RowIndex: OleVariant; {optional} ColumnIndex: OleVariant]: OleVariant dispid 0; default;
  12. property Value: OleVariant dispid 6;
  13. end;
  14. WorksheetDisp = dispinterface ['{000208D8-0000-0000-C000-000000000046}']
  15. property Cells: ExcelRange readonly dispid 238;
  16. end;
  17. ExcelWorkbook = interface(IDispatch)
  18. end;
  19. WorkbooksDisp = dispinterface ['{000208DB-0000-0000-C000-000000000046}']
  20. function Add({optional} Template: OleVariant): ExcelWorkbook; dispid 181;
  21. end;
  22. ExcelApplicationDisp = dispinterface ['{000208D5-0000-0000-C000-000000000046}']
  23. property ActiveSheet: IDispatch readonly dispid 307;
  24. property Workbooks: IDispatch readonly dispid 572;
  25. property Visible: WordBool dispid 558;
  26. end;
  27. Function CheckOle(Msg : string;hres : HResult) : HResult;
  28. begin
  29. Result:=hres;
  30. if Failed(hres) then
  31. writeln(Msg,' error')
  32. else if hres=S_OK then
  33. writeln(Msg,' S_OK')
  34. else if hres=REGDB_E_CLASSNOTREG then
  35. writeln(Msg,'CLASSNOTREG')
  36. else if hres=CLASS_E_NOAGGREGATION then
  37. writeln(Msg,'NOAGGREGATION')
  38. else
  39. writeln(Msg,'other error:',longint(hres));
  40. end;
  41. Var
  42. hres : HRESULT;
  43. aclsID : TGUID;
  44. excelapp : ExcelApplicationDisp;
  45. WorkBooks : WorkbooksDisp;
  46. ActiveSheet : WorksheetDisp;
  47. Cells : ExcelRange;
  48. i, j : longint;
  49. begin
  50. hres := CheckOle('CoInit',CoInitializeEx(nil,COINIT_MULTITHREADED));
  51. hres := CheckOle('CLSIDFromProgID',CLSIDFromProgID('Excel.Application', aclsid));
  52. hres := CheckOle('CoCreate',CoCreateInstance(aclsid, Nil, {CLSCTX_INPROC_SERVER or }CLSCTX_LOCAL_SERVER, IID_IDispatch, excelApp));
  53. ExcelApp.Visible := true;
  54. { Following should also be possible as ExcelApp.Workbooks.Add !!}
  55. WorkBooks := ExcelApp.WorkBooks as WorkBooksDisp;
  56. WorkBooks.Add(EmptyParam);
  57. {
  58. The following should also work as
  59. For I:=1 to 5 do
  60. For J:=1 to 5 do
  61. ExcelApp.ActiveSheet.Cells[i,j] := i+j;
  62. }
  63. ActiveSheet:=ExcelApp.ActiveSheet as WorksheetDisp;
  64. For I:=1 to 5 do
  65. for j:=1 to 5 do
  66. begin
  67. Cells:=ActiveSheet.Cells[I,J];
  68. Cells.Value:=I+J;
  69. end;
  70. // Free everything.
  71. Cells:=Nil;
  72. ActiveSheet:=Nil;
  73. WorkBooks:=Nil;
  74. excelApp:=Nil;
  75. end.