Delphi TQuery保存到csv文件 [英] Delphi TQuery save to csv file

查看:602
本文介绍了Delphi TQuery保存到csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想不使用3d零件组件(Delphi 7)将TQuery的内容导出到CSV文件.据我所知,这不能用Delphi标准组件来完成.

I want to export content of a TQuery to a CSV file without using a 3d part component(Delphi 7). From my knowledge this can not be accomplished with Delphi standard components.

我的解决方案是将内容保存为CSV格式的StringList,然后将其保存到文件中.

My solution was to save the content in a StringList with a CSV format, and save it to a file.

有什么舒适的解决方案吗?

Is there any comfortable solution?

PS:我不想使用JvCsvDataSet或任何组件.问题是:仅使用Delphi 7或更高标准的组件才能实现吗?

PS:I don't want to use JvCsvDataSet or any component. Question is: can this be accomplished only with Delphi 7 or higher standard components?

提前谢谢!

推荐答案

当然可以.

您只需要做工作即可正确输出CSV内容(正确报价,处理嵌入的引号和逗号等).您可以轻松地使用TFileStream写入输出,并正确使用TQuery.FieldsTQuery.FieldCount获取数据.

You just have to do the work to properly output the CSV content (quoting properly, handling embedded quotes and commas, etc.). You can easily write the output using TFileStream, and get the data using the TQuery.Fields and TQuery.FieldCount properly.

我将把精美的CSV报价和特殊处理留给您.这将处理简单的部分:

I'll leave the fancy CSV quoting and special handling to you. This will take care of the easy part:

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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆