動機:
對於Delphi Form內顯示的TDBGrid資料,
常常使用者會要求能夠匯出至Calc格式(免費Office),
俾提供做其他運用...
說明:
利用Delphi6支援的OLE Automation Object來呼叫Calc,
就可以看到匯出的資料了!!
程式碼如下:
procedure TfmQueryP.ExportToOpenOffice; var iRow, iTotal: integer; objServiceManager, objDesktop, oDocument, osheet: OleVariant; objDocName, objDocParam, objDocNum, objParam: variant; ApplicationPath: string; begin // The service manager is always the starting point objServiceManager := CreateOLEObject('com.sun.star.ServiceManager'); // Create the Desktop objDesktop := objServiceManager.createInstance('com.sun.star.frame.Desktop'); // Open a new empty scalc document ApplicationPath := ExtractFilePath(Application.ExeName); if copy(ApplicationPath, length(ApplicationPath), 1) <> '\' then ApplicationPath := ApplicationPath + '\'; ApplicationPath := AnsiReplaceStr( ApplicationPath, '\', '/'); ApplicationPath := AnsiReplaceStr( ApplicationPath, ':', '|'); ApplicationPath := 'File:///' + ApplicationPath + 'Report/QueryPathistk.ots'; objDocName := ApplicationPath; objDocParam := '_blank'; objDocNum := 0; objParam := VarArrayCreate([0, 1], VarVariant); objParam[0] := ''; // .Name = '' objParam[1] := 0; // .Value = 0 // oDocument will be ::com::sun::star::lang::XComponent; oDocument := objDesktop.loadComponentFromURL(objDocName, objDocParam, 0, VarArrayOf([])); //oDocument.getSheets will return ::com::sun::star::sheet::XSpreadsheets oSheet := oDocument.getSheets.getByIndex(0); iRow := 1; iTotal := qyP.RecordCount; qyP.DisableControls; qyTemp.SQL.Clear; qyTemp.SQL.Add(' Select * From TempP '); qyTemp.Open; qyP.First; while not qyP.Eof do begin osheet.getCellByPosition(0, iRow).String := qyP.FieldByName('field1').AsString; osheet.getCellByPosition(1, iRow).String := qyP.FieldByName('field2').AsString; osheet.getCellByPosition(2, iRow).String := qyP.FieldByName('field3').AsString; osheet.getCellByPosition(3, iRow).String := Trim(qyP.FieldByName('field4').AsString); osheet.getCellByPosition(4, iRow).String := Trim(qyP.FieldByName('field5').AsString); osheet.getCellByPosition(5, iRow).Value := qyP.FieldByName('field6').AsInteger; StatusBar1.Panels.Items[0].Text := '匯出資料中:第 ' + IntToStr(iRow) + ' 筆 / 共 ' + IntTostr(iTotal) + ' 筆'; Inc(iRow); Application.ProcessMessages; qyP.Next; end; qyP.First; qyTemp.Close; qyP.EnableControls; Tag := 1; end;
留言