[펌글] DB Grid 자료를 엑셀로 보내기
(klol)
2009-01-12 오후 11:39:47
DBGrid자료를 엑셀로 보내는 함수입니다.
uses
dbgrids, ComObj, Excel2000, Clipbrd;
.....
procedure ToExcle(vDBGrid: TDBGrid);
var
XL: Variant;
i,k: integer;
sData: string;
begin
try
XL := CreateOLEObject('Excel.Application');
except on E: Exception do
begin
ShowMessage('Excel OLE object를 오픈할 수 없습니다.'+E.Message);
Exit;
end; end;
try
XL.WorkBooks.Add; //새로운 페이지 생성
XL.Visible := False;
XL.Workbooks[XL.Workbooks.Count].WorkSheets[1].Name := 'Sheet1';
sData := '';
for i := 0 to vDBGrid.Columns.Count - 1 do
begin
sData := sData+vDBGrid.Columns[i].Title.Caption+#9;
if vDBGrid.Columns[i].Field.DataType in [ftString,ftMemo,ftWideString] then
begin
XL.Workbooks[XL.Workbooks.Count].WorkSheets['Sheet1'].Columns[i+1].Select;
XL.Selection.NumberFormatLocal := '@';
end;
end;
sData := sData+#$D#$A;
with vDBGrid do
begin
k := 0;
DataSource.DataSet.First;
while not DataSource.DataSet.Eof do
begin
inc(k);
for i := 0 to Columns.Count - 1 do
sData := sData+Columns[i].Field.AsString+#9;
sData := sData+#$D#$A;
DataSource.DataSet.Next;
end;
end;
Clipboard.SetTextBuf(PChar(sData));
XL.Cells[1,1].Pastespecial;
XL.Range['A1', Chr(64+vDBGrid.Columns.Count)+IntToStr(k)].select;
XL.Selection.Columns.AutoFit;
XL.Range['A1', 'A1'].select;
XL.Visible := True;
except on E: Exception do
begin
ShowMessage('Excel로 자료를 보내는 중 오류가 발생했습니다.'+E.Message);
XL.Visible := True;
Exit;
end; end;
end;
테스트결과 아주 잘 되는군요.