导出选中记录到excel
方法1:独立事件单独写法
procedure TForm3.excel2Click(Sender: TObject);
var
SaveDialog:TSaveDialog;
begin
try
try
SaveDialog:=TSaveDialog.Create(nil);
SaveDialog.Filter:='EXCEL电子表格|*.XLS';
//if dbgrdh1.SelectedRows.Count=0 then
//begin
//ShowMessage('请先选中要导出的数据');
//Exit;
//end;
if SaveDialog.Execute then
begin
SaveDialog.FileName:=SaveDialog.FileName+'.xls';
// ShowMessage(SaveDialog.FileName);
// ShowMessage(Length(SaveDialog.FileName).ToString());
// ShowMessage(Length('E:\翠玲研究delphi\工作小助手\工作小助手输出文件\导出数据到excel\666.xls').ToString());
// ShowMessage(Length('E:\delphi\\\excel\666.xls').ToString());
// ShowMessage(Length('翠玲研究工作小助手工作小助手输出文件导出数据到').ToString());
// ShowMessage(Copy(SaveDialog.FileName,Length(SaveDialog.FileName)-2,3));
if FileExists(SaveDialog.FileName) then
begin
if application.MessageBox('文件名已存在,是否覆盖 ', '提示', MB_ICONASTERISK or MB_OKCANCEL)<>idok then
exit;
end;
Screen.Cursor := crHourGlass;
SaveDBGridEhToExportFile(TDBGridEhExportAsXls,dbgrdh1,SaveDialog.FileName,false);
Screen.Cursor := crDefault;
MessageBox(Handle, '导出成功 ', '提示', MB_OK +MB_ICONINFORMATION);
end;
except
on e: exception do
begin
Application.MessageBox(PChar(e.message), '错误', MB_OK + MB_ICONSTOP);
end;
end;
finally
SaveDialog.Free;
end;
end;
方法2:类写法
unit UExportExcel;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Data.DB, Data.Win.ADODB,
Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Clipbrd, Vcl.Menus,
Vcl.StdCtrls, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh,
EhLibVCL, GridsEh, DBAxisGridsEh, DBGridEh,EhLibADO,DBGridEhImpExp;
/// <summary>
/// 导出全部记录数据到excel,思路是用dbgrideh的方法
/// </summary>
type TExportExcel =class
public
class procedure exportexcelselected(var ADbgrdh:TDBGridEh);
end;
implementation
class procedure TExportExcel.exportexcelselected(var ADbgrdh:TDBGridEh);
var
SaveDialog:TSaveDialog;
begin
try
try
//设置报错对话框的属性
SaveDialog:=TSaveDialog.Create(nil);
SaveDialog.Filter:='EXCEL电子表格|*.XLS';
if SaveDialog.Execute then
begin
//设置文件名后缀
SaveDialog.FileName:=SaveDialog.FileName+'.xls';
//判断文件是否已经存在
if FileExists(SaveDialog.FileName) then
begin
if application.MessageBox('文件名已存在,是否覆盖 ', '提示', MB_ICONASTERISK or MB_OKCANCEL)<>idok then
exit;
end;
Screen.Cursor := crHourGlass; //屏幕鼠标沙漏忙碌状态
//导出选中记录,最后设false
SaveDBGridEhToExportFile(TDBGridEhExportAsXls,ADbgrdh,SaveDialog.FileName,false);
Screen.Cursor := crDefault; //鼠标恢复默认状态
//提示导出成功
MessageBox(0, '导出成功 ', '提示', MB_OK +MB_ICONINFORMATION);
end;
except
//异常报错
on e: exception do
begin
Application.MessageBox(PChar(e.message), '错误', MB_OK + MB_ICONSTOP);
end;
end;
finally
SaveDialog.Free;
end;
end;
end.
类引用,记得在uses中添加要引用的类单元名UExportExcel
procedure TForm3.excel2Click(Sender: TObject);
begin
//导出选中记录到excel
TExportExcel.exportexcelselected(dbgrdh1);
end;
附加效果图: