testcom2.pp 2.4 KB

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