from Delphi to Excel

terryisme發表於2009-03-06

從DBGrid,StringGrid匯出Excel

[日期:2008-07-04] 來源: 作者: [字型: ]
None

procedure TDM.CopyDbDataToExcel(Target: TDBGridEh;mb,FileName: string);
var
iCount, jCount: Integer;
XLApp: Variant;
Sheet: Variant;
begin
Screen.Cursor := crHourGlass;
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
VarClear(XLApp);
end;
//--------------------------選擇模板------
// CopyFile(pChar(Trim(ExtractFilePath(Application.ExeName)) mb '.xls'),pChar(FileName '1.xls'),false);
//------------------------
//透過ole建立Excel物件
try
XLApp := CreateOleObject('Excel.Application');
except
Screen.Cursor := crDefault;
Exit;
end;
if mb = '統計-專案資訊前' then
XLApp.WorkBooks.Add[Trim(ExtractFilePath(Application.ExeName)) mb '.xls'] //你要把資料放在那裡啊,先生成個檔案在e:1.xls
else
XLApp.WorkBooks.Add;
XLApp.WorkBooks[1].WorkSheets[1].Name := 'sheet1';
Sheet := XLApp.Workbooks[1].WorkSheets['sheet1'];
if not Target.DataSource.DataSet.Active then
begin
Screen.Cursor := crDefault;
Exit;
end;
Target.DataSource.DataSet.first;

for iCount := 0 to Target.Columns.Count - 1 do
begin
Sheet.cells[1, iCount 1] := trim(Target.Columns.Items[iCount].Title.Caption);
end;

jCount := 1;
while not Target.DataSource.DataSet.Eof do
begin

for iCount := 0 to Target.Columns.Count - 1 do //
begin
if iCount = 0 then
Sheet.cells[jCount 1, iCount 1] := IntToStr(jCount)
else
Sheet.cells[jCount 1, iCount 1] := trim(Target.Columns.Items[iCount].Field.AsString);
end;
Inc(jCount);
Target.DataSource.DataSet.Next;
end;

//--------------------可以在此新增Excel的宏-----------

軟體開發網

XLApp.ActiveWorkbook.SaveAs(FileName:=FileName); ;
Screen.Cursor := crDefault;
XLApp.ActiveWorkbook.Close;
end;
-----------------------------------------StringGridToExcel

procedure TDM.CopySGDataToExcel(Target: TStringGrid;FileName: string);
var
iCount, jCount: Integer;
XLApp: Variant;
Sheet: Variant;
begin
Screen.Cursor := crHourGlass;
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
VarClear(XLApp);
end;
//透過ole建立Excel物件
try
XLApp := CreateOleObject('Excel.Application');
except
Screen.Cursor := crDefault;
Exit;
end;
XLApp.WorkBooks.Add; //你要把資料放在那裡啊,先生成個檔案在e:1.xls
XLApp.WorkBooks[1].WorkSheets[1].Name := 'sheet1';
Sheet := XLApp.Workbooks[1].WorkSheets['sheet1'];
Target.Row := 0;
for iCount := 0 to Target.RowCount - 1 do
begin
for jCount := 0 to Target.ColCount - 1 do
Sheet.cells[iCount 1, jCount 1] := Target.Cells[jCount,iCount];
Target.Row := iCount;
end;
XLApp.ActiveWorkbook.SaveAs(FileName:=FileName);
Screen.Cursor := crDefault;
XLApp.ActiveWorkbook.Close;
end; 軟體開發網

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/93029/viewspace-1018195/,如需轉載,請註明出處,否則將追究法律責任。

相關文章