老兄没分,像我这样的人不多了啊.
function TForm1.ExportExcel(FileName:string;DbGrid:TDbgrid): Boolean;
var
ExcelApp:Variant;
ExcelRow,ExcelCol,Temp_Row,fistcol,tempcol: integer;
ExcelRows, Excelcols,fistcols: integer; //记录汇总行位置
temps,tempstr:string;
flag:boolean;
InsertTemp,Temp:string;
Dataset:Tdataset;
begin
Result := false;
DataSet:=DbGrid.DataSource.DataSet; //取得dbgrid的数据集
if not DataSet.Active or (DataSet.RecordCount=0) then exit;
if not FileExists(FileName) Then exit; //假如文件不存在。。
try
ExcelApp:=UnAssigned;
ExcelApp:=CreateOleObject('Excel.Application');
ExcelApp.Visible:=True;
except
ExcelApp.Quit;
ExcelApp.Free;
ExcelApp:=Unassigned;
// Showmsg('电脑未安装MicroSoft Excel,是否继续导出?'+#13#13+'导出后在您的机器上不能直接打开,必须安装Excel后才能打开!',CoMessageTitle);
exit;
end; //try
ExcelApp.Caption := FileName;
try
ExcelApp.Workbooks.Open(FileName);
except
ExcelApp.Quit;
ExcelApp.Free;
ExcelApp:=Unassigned;
// Showmsg('打开Excel模板出错,不能导出数据',CoMessageTitle);
exit;
end; //try
DataSet.First;
ExcelApp.WorkSheets[1].Activate;
DbGrid.DataSource.DataSet.DisableControls;
for ExcelRow :=1 to 20 Do //循环行数...
begin
for Excelcol := 1 to 20 do //循环列数...
begin
Temp:=trim(ExcelApp.ActiveSheet.cells[ExcelRow, Excelcol].value); //取得每一个cell的值..
if Not (DataSet.eof) then
begin
if copy(temp,1,1)='#' then
begin
Temp:=copy(temp,2,Length(temp)-1); //Temp为#后面的字段名
if DataSet.Fields.FindField(Temp)=Nil Then
begin
ExcelApp.ActiveSheet.cells[ExcelRow+1, Excelcol].Value:=temp;
Continue;
end; //is Nil
tempstr:=DataSet.FieldByName(Temp).asstring;
ExcelApp.ActiveSheet.cells[ExcelRow, Excelcol].Value := tempstr;//插入一格数据
end; //is '#'
end; // is not eof
end; //for Excelcol
if not DataSet.Eof then DataSet.Next;
end; //for ExcelRow
end;