如何将DBGrid中的数据集转为电子表格?(100分)

  • 主题发起人 主题发起人 tjlqp
  • 开始时间 开始时间
T

tjlqp

Unregistered / Unconfirmed
GUEST, unregistred user!
如何将DBGrid中的数据集转为电子表格,或其他格式。需要加什么控件,如何设,源代码....主要是我太菜,请大侠指教。tjlqp@sina.com打酒烧菜,敬候您......
 
抄来的,没试验,你自己多琢磨一下:
{
功能描述:把DBGrid输出到Excel表格(支持多Sheet)
调用格式:CopyDbDataToExcel([DBGrid1, DBGrid2]);
}
procedure CopyDbDataToExcel(Args: array of const);
var
iCount, jCount: Integer;
XLApp: Variant;
Sheet: Variant;
I: Integer;
begin
Screen.Cursor := crHourGlass;
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
VarClear(XLApp);
end;

try
XLApp := CreateOleObject(‘Excel.Application‘);
except
Screen.Cursor := crDefault;
Exit;
end;

XLApp.WorkBooks.Add;
XLApp.SheetsInNewWorkbook := High(Args) + 1;
for I := Low(Args) to High(Args)do
begin
XLApp.WorkBooks[1].WorkSheets[I+1].Name := TDBGrid(Args.VObject).Name;
Sheet := XLApp.Workbooks[1].WorkSheets[TDBGrid(Args.VObject).Name];
if not TDBGrid(Args.VObject).DataSource.DataSet.Active then
begin
Screen.Cursor := crDefault;
Exit;
end;

TDBGrid(Args.VObject).DataSource.DataSet.first;
for iCount := 0 to TDBGrid(Args.VObject).Columns.Count - 1do
Sheet.Cells[1, iCount + 1] :=
TDBGrid(Args.VObject).Columns.Items[iCount].Title.Caption;
jCount := 1;
while not TDBGrid(Args.VObject).DataSource.DataSet.Eofdo
begin
for iCount := 0 to TDBGrid(Args.VObject).Columns.Count - 1do
Sheet.Cells[jCount + 1, iCount + 1] :=
TDBGrid(Args.VObject).Columns.Items[iCount].Field.AsString;
Inc(jCount);
TDBGrid(Args.VObject).DataSource.DataSet.Next;
end;
XlApp.Visible := True;
end;
Screen.Cursor := crDefault;
end;
 
记得在俺的笔记上面有记载,可以参考一下
http://www.delphibbs.com/keylife/iblog_show.asp?xid=4091
 
用DBGridEh
function DBGridehExport(const sFileName:string;const DBGridEh :TDBGridEh;IsAllRecord:boolean) : String;
var ExpClass:TDBGridEhExportClass;
Ext:String;
SaveDialog1 : TSaveDialog;
begin
Result := '';
SaveDialog1 := TSaveDialog.Create (nil);
SaveDialog1.Filter := 'Microsoft Excel Workbook (*.xls)|*.XLS | Text files (*.txt)|*.TXT|Comma separated values (*.csv)|*.CSV|HTML file (*.htm)|*.HTM|Rich Text Format (*.rtf)|*.RTF';
SaveDialog1.Options :=[ofHideReadOnly,ofEnableSizing];
try
SaveDialog1.FileName := sFileName;
if SaveDialog1.Execute then
begin
case SaveDialog1.FilterIndex of
1: begin
ExpClass := TDBGridEhExportAsXLS;
Ext := 'xls';
end;
2: begin
ExpClass := TDBGridEhExportAsText;
Ext := 'txt';
end;
3: begin
ExpClass := TDBGridEhExportAsCSV;
Ext := 'csv';
end;
4: begin
ExpClass := TDBGridEhExportAsHTML;
Ext := 'htm';
end;
5: begin
ExpClass := TDBGridEhExportAsRTF;
Ext := 'rtf';
end;
else
ExpClass := nil;
Ext := '';
end;
if ExpClass <> nil then
begin
if UpperCase(Copy(SaveDialog1.FileName,Length(SaveDialog1.FileName)-2,3)) <> UpperCase(Ext) then
SaveDialog1.FileName := SaveDialog1.FileName + '.' + Ext;
SaveDBGridEhToExportFile(ExpClass,DBGridEh,SaveDialog1.FileName,IsAllRecord);
end;
end;
Result := SaveDialog1.FileName ;
finally
SaveDialog1.Free;
end;
end;
 
后退
顶部