刚改写完一段代码,可行
调用:
ExportDataSetEx(Query1, ADestTable, ttDefault,'',
False, '"', ',', 0);
非常好用,由于用BatchMove速度很快!!
procedure ExportDataSetEx(Source: TBDEDataSet; DestTable: TTable;
TableType: TTableType; const AsciiCharSet: string;
AsciiDelimited: Boolean; AsciiDelimiter, AsciiSeparator: Char;
MaxRecordCount: Longint);
function ExportAsciiField(Field: TField): Boolean;
begin
Result := Field.Visible and not (Field.Calculated
{$IFDEF WIN32} or Field.Lookup {$ENDIF}) and not (Field.DataType in
ftNonTextTypes + [ftUnknown]);
end;
const
TextExt = '.TXT';
SchemaExt = '.SCH';
var
I: Integer;
S, Path: string;
BatchMove: TBatchMove;
TablePath: array[0..dbiMaxPathLen] of Char;
begin
if Source = nil then DatabaseError(SDataSetEmpty);
if DestTable.Active then DestTable.Close;
if Source is TDBDataSet then
DestTable.SessionName := TDBDataSet(Source).SessionName;
if (TableType = ttDefault) then begin
if DestTable.TableType <> ttDefault then
TableType := DestTable.TableType
else if (CompareText(ExtractFileExt(DestTable.TableName), TextExt) = 0) then
TableType := ttASCII;
end;
BatchMove := TBatchMove.Create(nil);
try
StartWait;
try
BatchMove.Mode := batCopy;
BatchMove.Source := Source;
BatchMove.Destination := DestTable;
DestTable.TableType := TableType;
BatchMove.Mappings.Clear;
if (DestTable.TableType = ttASCII) then begin
if CompareText(ExtractFileExt(DestTable.TableName), SchemaExt) = 0 then
DestTable.TableName := ChangeFileExt(DestTable.TableName, TextExt);
with Source do
for I := 0 to FieldCount - 1 do begin
if ExportAsciiField(Fields) then
BatchMove.Mappings.Add(Format('%s=%0:s',
[Fields.FieldName]));
end;
BatchMove.RecordCount := 1;
end
else BatchMove.RecordCount := MaxRecordCount;
BatchMove.Execute;
if (DestTable.TableType = ttASCII) then begin
{ ASCII table always created in "fixed" format with "ascii"
character set }
with BatchMove do begin
Mode := batAppend;
RecordCount := MaxRecordCount;
end;
S := ChangeFileExt(ExtractFileName(DestTable.TableName), '');
Path := NormalDir(ExtractFilePath(DestTable.TableName));
if Path = '' then begin
DestTable.Open;
try
Check(DbiGetDirectory(DestTable.DBHandle, False, TablePath));
Path := NormalDir(OemToAnsiStr(StrPas(TablePath)));
finally
DestTable.Close;
end;
end;
with TIniFile.Create(ChangeFileExt(Path + S, SchemaExt)) do
try
if AsciiCharSet <> '' then
WriteString(S, 'CharSet', AsciiCharSet)
else WriteString(S, 'CharSet', 'ascii');
if AsciiDelimited then begin { change ASCII-file format to CSV }
WriteString(S, 'Filetype', 'VARYING');
WriteString(S, 'Delimiter', AsciiDelimiter);
WriteString(S, 'Separator', AsciiSeparator);
end;
finally
Free;
end;
{ clear previous output - overwrite existing file }
S := Path + ExtractFileName(DestTable.TableName);
if Length(ExtractFileExt(S)) < 2 then
S := ChangeFileExt(S, TextExt);
I := FileCreate(S);
if I < 0 then
raise EFCreateError.CreateFmt(SFCreateError, );
FileClose(I);
BatchMove.Execute;
end;
finally
StopWait;
end;
finally
BatchMove.Free;
end;
end;