delphi7中将dbgrid数据导出到excel代码?
2个回答
展开全部
两个循环,内循环遍历所有Dbgrid的RecordCount,Fields.外循环遍历所有Excel对应的Rows,Columns.在两个循环体内,把Dbgrid对应的()RecordCount,Filed)赋给对应的Excel ()Rows,Columns)
追问
能给出详细的代码吗?谢谢
追答
function TForm1.ExportDBGrid(DBGrid: TDBGrid; SheetName: string): boolean;//直接保存,不显示EXCEL
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 := SheetName;
if SaveDialog1.Execute then
TempFileName := SaveDialog1.FileName
else
Exit;
app.Workbooks.add;
app.Visible := false;
Screen.Cursor := crHourGlass;
DBGrid.DataSource.DataSet.First;
c := DBGrid.DataSource.DataSet.FieldCount;
r := DBGrid.DataSource.DataSet.RecordCount;
Application.ProcessMessages;
for i := 0 to c - 1 do
app.cells(1, 1 + i) := DBGrid.DataSource.DataSet.Fields[i].DisplayLabel;
for j := 1 to r do
begin
for i := 0 to c - 1 do
app.cells(j + 1, 1 + i) := DBGrid.DataSource.DataSet.Fields[i].AsString;
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;
procedure TForm1.Button2Click(Sender: TObject); //按钮保存
begin
try
Screen.Cursor := crHourGlass;
ExportDBGrid(DBGrid1, '导出数据'); //暂时将导出的文件名称为“导出数据”(的execl文件)
finally
Screen.Cursor := crDefault;
end;
end;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询