我想将 TQuery 的内容导出到 CSV 文件,而不使用 3d 零件组件(Delphi 7)。据我所知,这不能用 Delphi 标准组件来完成。
我的解决方案是将内容以 CSV 格式保存在 StringList 中,并将其保存到文件中。
有什么舒服的解决方案吗?
PS:我不想使用 JvCsvDataSet 或任何组件。问题是:这只能用Delphi 7或更高标准的组件来完成吗?
提前谢谢您!
最佳答案
当然可以。
您只需完成正确输出 CSV 内容的工作(正确引用、处理嵌入的引号和逗号等)。您可以使用 TFileStream
轻松编写输出,并正确使用 TQuery.Fields
和 TQuery.FieldCount
获取数据。
我将把精美的 CSV 引用和特殊处理留给您。这将解决简单的部分:
var
Stream: TFileStream;
i: Integer;
OutLine: string;
sTemp: string;
begin
Stream := TFileStream.Create('C:\Data\YourFile.csv', fmCreate);
try
while not Query1.Eof do
begin
// You'll need to add your special handling here where OutLine is built
OutLine := '';
for i := 0 to Query.FieldCount - 1 do
begin
sTemp := Query.Fields[i].AsString;
// Special handling to sTemp here
OutLine := OutLine + sTemp + ',';
end;
// Remove final unnecessary ','
SetLength(OutLine, Length(OutLine) - 1);
// Write line to file
Stream.Write(OutLine[1], Length(OutLine) * SizeOf(Char));
// Write line ending
Stream.Write(sLineBreak, Length(sLineBreak));
Query1.Next;
end;
finally
Stream.Free; // Saves the file
end;
end;
关于Delphi TQuery 保存到 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5680017/