Delphi DBGrid导出Excel2010年09月30日 星期四 下午 03:36uses ComObj;
//DBGrid:指定的DBGrid;SaveFileName:要保存的文件名
function ExportDBGrid(DBGrid: TDBGrid; SaveFileName: string): boolean;
var
c,r,i,j: integer;
app: Olevariant;
TempFileName, ResultFileName: string;
begin
try
result := True;
app := CreateOLEObject('Excel.application');
//app.WorkBooks.Add(xlWBatWorkSheet);
except
Application.MessageBox('Excel没有正确安装!','警告',MB_OK);
result := False;
exit;
end;
SaveDialog1.DefaultExt := 'xls';
SaveDialog1.FileName:=SaveFileName;
if SaveDialog1.Execute then
TempFileName := SaveDialog1.FileName
else
Exit;
app.Workbooks.add;
app.Visible := false;
Screen.Cursor := crHourGlass;
DBGrid1.DataSource.DataSet.First;
c:=DBGrid1.DataSource.DataSet.FieldCount;
r:=DBGrid1.DataSource.DataSet.RecordCount;
Application.ProcessMessages;
delphi appfor i:=0 to c-1 do
begin
app.ActiveSheet.Columns[i+1].ColumnWidth:=15;//设置格宽度
lls(1,1+i):=DBGrid1.DataSource.DataSet.Fields[i].DisplayLabel;
end;
for j := 1 to r do
begin
for i := 0 to c - 1 do
begin
lls[j+1,1].numberformatlocal:='@';//设置成文本
lls(j+1,1+i):=DBGrid1.DataSource.DataSet.Fields[i].AsString;
end;
DBGrid.DataSource.DataSet.Next;
end;
ResultFileName := TempFileName;
if ResultFileName = '' then
ResultFileName := '数据导出';
if FileExists(TempFileName) then
DeleteFile(TempFileName);
app.Activeworkbook.saveas(TempFileName);
app.Activeworkbook.close(false);
app.quit;
app := unassigned;
end;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论