//这是数据库转文本文件的,文本文件转数据库的比这还容易,你自己写吧!
procedure DatToTxt;
var
F: TextFile;
FieldLen: array[0..30] of integer;
RecordStr: array[0..300] of char;
i,j: integer;
s: string;
pt: pointer;
// 检查文件是否存在
function CheckFile(F: string): Boolean;
begin
result:= True;
if FileExists(F) then
Application.MessageBox(pchar('文件已经存在!'),
pchar('提示'),MB_ICONINFORMATION or MB_OK)
else
result:= False;
end;
// 取得文件名
function OpenFile:Boolean;
begin
SaveFile_dlg.Title:= '指定文本文件'; //使用TSaveDialog控件
result:= False;
if SaveFile_dlg.Execute then
begin
if CheckFile(SaveFile_dlg.FileName) then
exit;
AssignFile(F, SaveFile_dlg.FileName+'.TxT');
Rewrite(F);
result:= True;
end;
end;
// 将各字段长度保存到数组
procedure GetFieldLen;
var
i: integer;
begin
with YourQuery do
for i:=0 to FieldDefs.Count-1 do
begin
if FieldDefs.Items.DataType= ftFixedChar then
FieldLen:= FieldDefs.Items.Size
else
if FieldDefs.Items.DataType= ftInteger then
FieldLen:= 8
else
if FieldDefs.Items.DataType= ftFloat then
FieldLen:= 8;
if Length(FieldDefs.Items.Name)>=FieldLen then
FieldLen:= Length(FieldDefs.Items.Name);
FieldLen:= FieldLen+2; // 防止各个字段输出后紧密相连
end;
FieldLen[ YourQuery.FieldDefs.Count]:= 0;
end;
begin
if YourQuery.RecordCount<=0 then
begin
Application.MessageBox(pchar('没有找到指定记录!'),
pchar('提示'),MB_ICONINFORMATION or MB_OK);
exit;
end;
if OpenFile then
try
try
GetFieldLen;
j:=0;
FillChar(RecordStr,300,' ');
with YourQuery do
for i:=0 to FieldDefs.Count-1 do
begin
s:= FieldDefs.Items.Name;
pt:= @s;
pt:= pointer(pt^);
move(pt^,RecordStr[j],Length(s));
j:=j+FieldLen;
end;
RecordStr[j]:= chr($0);
Writeln(F, RecordStr);
FillChar(RecordStr,j-1,'=');
Writeln(F, RecordStr);
with YourQuery do
begin
First;
s:='';
while not Eof do
begin
j:=0;
FillChar(RecordStr,300,' ');
for i:=0 to FieldDefs.Count-1 do
begin
s:= Fields.Fields.AsString;
pt:= @s;
pt:= pointer(pt^);
move(pt^,RecordStr[j],Length(s));
j:=j+FieldLen;
end;
RecordStr[j]:= chr($0);
Writeln(F, RecordStr);
Next;
end;
Application.MessageBox(pchar('输出完毕!'),
pchar('提示'),MB_ICONINFORMATION or MB_OK);
end;
finally
CloseFile(F);
end;
except
Application.MessageBox(pchar('运行出现错误,不能正常输出!'),
pchar('提示'),MB_ICONINFORMATION or MB_OK);
end;
end;