导出到记事本(打开直接显示文本而不是乱码的写法)
本例子导出效果图:
dbgrideh导出记事本效果图:
实例代码:
方法1:独立事件单独写法
procedure TForm3.N34Click(Sender: TObject);
var
AList:TStringList;
SaveDialog:TSaveDialog;
AStr,ATitle,AFieldName,AFieldValue:string;
i:Integer;
begin
SaveDialog:=TSaveDialog.Create(nil);
SaveDialog.DefaultExt:='txt';
SaveDialog.Filter:='Text files (*.txt)|*.TXT';
Alist:=TStringList.Create;
try
//这部分是为了打开文件,如果这个文件名不存在就重新创建个;
//把数据写入文件中
AStr:='';
ATitle:='';
AList.Clear;
//添加标题
for i:=0 to frmDataPool.qry需要做的事.Fields.count-1 Do
begin
AFieldName:=frmDataPool.qry需要做的事.Fields[I].FieldName;
ATitle:=ATitle+AFieldName+'|';
end;
AList.Insert(0,ATitle);
//添加数据记录
frmDataPool.qry需要做的事.First;
while not frmDataPool.qry需要做的事.eof do
begin
for i:=0 to frmDataPool.qry需要做的事.Fields.count-1 Do
begin
AFieldName:=frmDataPool.qry需要做的事.Fields[I].FieldName;
AFieldValue:=frmDataPool.qry需要做的事.FieldByName(AFieldName).AsString;
AStr:=AStr+AFieldValue+';';
end;
AList.Add(AStr);
AStr:='';
frmDataPool.qry需要做的事.Next;
end;
if SaveDialog.Execute then
begin
AList.SaveToFile(SaveDialog.FileName);
ShowMessage('导出成功');
end;
finally
Alist.free;
SaveDialog.Free;
end;
end;
方法2:类写法,注意不要写成ExportTXT 这样编译器不通过,不能用系统的标识符;
unit UExportExt;
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>
/// 导出数据到记事本的写法,运用list的save方法
/// </summary>
type TExportExt=class
public
class procedure exportextall(var SAdq:TADOQuery);
end;
implementation
class procedure TExportExt.exportextall(var SAdq:TADOQuery);
var
AList:TStringList;
SaveDialog:TSaveDialog;
AStr,ATitle,AFieldName,AFieldValue:string;
i:Integer;
begin
SaveDialog:=TSaveDialog.Create(nil);
SaveDialog.DefaultExt:='txt';
SaveDialog.Filter:='Text files (*.txt)|*.TXT';
Alist:=TStringList.Create;
try
//这部分是为了打开文件,如果这个文件名不存在就重新创建个;
//把数据写入文件中
AStr:='';
ATitle:='';
AList.Clear;
//添加标题
for i:=0 to SAdq.Fields.count-1 Do
begin
AFieldName:=SAdq.Fields[I].FieldName;
ATitle:=ATitle+AFieldName+'|';
end;
AList.Insert(0,ATitle);
//添加数据记录
SAdq.First;
while not SAdq.eof do
begin
for i:=0 to SAdq.Fields.count-1 Do
begin
AFieldName:=SAdq.Fields[I].FieldName;
AFieldValue:=SAdq.FieldByName(AFieldName).AsString;
AStr:=AStr+AFieldValue+';';
end;
AList.Add(AStr);
AStr:='';
SAdq.Next;
end;
if SaveDialog.Execute then
begin
AList.SaveToFile(SaveDialog.FileName);
ShowMessage('导出成功');
end;
finally
Alist.free;
SaveDialog.Free;
end;
end;
end.
类引用,记住uses中添加需要引用的类单元名UExportExt
procedure TForm3.N34Click(Sender: TObject);
begin
//用list的savetofile方法导出数据到记事本
TExportExt.exportextall(frmDataPool.qry需要做的事);
end;