CSV/ru

From Free Pascal wiki
Jump to navigationJump to search

English (en) русский (ru)

Обзор

CSV означает Comma-Separated Values (значения, разделенные запятыми) и является популярным форматом файлов, который, к сожалению, не полностью стандартизирован.

Это текстовый формат файла с

  • полями данных, разделенными запятыми (или, в некоторых случаях, другими символами, такими как табуляции и точки с запятой)
  • строкой заголовка, в которой перечислены имена полей (которой может и не быть)
  • данными полей, содержащих разделители, которые могут быть запрещенными или быть заключенными в кавычки (чаще всего это знак двойной кавычки)
  • окончаниями строк (#13 и/или #10), которые могут или не могут быть разрешены в данных полей

RFC4180 (см.здесь) пытается кодифицировать и стандартизировать существующую практику; имеет смысл соответствовать этому стандарту при записи данных CSV (и принимать все данные RFC4180 при чтении).

Другая, альтернативная, спецификация может быть найдена здесь

Образец фрагмента CSV:

FirstName,Surname,DOB,Remarks
Jim,Weston,19560818,"Also known as ""The Butcher"""
Alice,Cooper,19760312,""

Как видно, здесь используется строка заголовка, как и квотирование с использованием двойных кавычек.

Пакеты электронных таблиц, такие как Microsoft Excel и OpenOffice/LibreOFfice Calc, могут экспортировать и импортировать из этого формата. Однако, поскольку Microsoft Excel может интерпретировать некоторые поля, такие как поля даты, по-разному в зависимости от языкового стандарта операционной системы пользователя, возможно целесообразнее найти альтернативные способы передачи данных (например, используя код FPSpreadsheet).

CSV и SDF

Delphi (и FreePascal) имеют очень похожий (но не идентичный) формат SDF. См. SDF для получения более подробной информации.

Реализации

CsvDocument

CsvDocument является надежной реализацией как CSV-формата RFC 4180 ,так и альтернативного CSV-формата Creativyst/Excel. Он предлагает как линейный, так и документный доступ. Рекомендуется для использования с FPC/Lazarus. См. CsvDocument.

DelimitedText

TStringList предлагает свойство DelimitedText. Оно разбивает строку текста на отдельные поля. Обратите внимание, однако, что DelimitedText должен быть в SDF-формате, специфичном для Delphi, который очень похож на CSV, но не полностью соответствует RFC4180.

Совет: при чтении данных CSV установите для свойства StrictDelimiter значение true.

При записи CSV-данных установите для StrictDelimiter значение false и выведите свойство DelimitedText. Тут есть одна странность, заключающаяся в том, что, например, символы табуляции удаляются при записи данных с использованием StrictDelimiter:=false

Формат SDF

См. формат SDF

SDFDataset

FreePascal offers the TSdfDataSet, which stores data in SDF format. Note: FPC 2.6.x and earlier store sdfdataset data in a format that is not completely CSV or completely SDF compatible. Sdfdataset is planned to be rewritten to store data in CSV format.

As indicated, SDF differs from CSV. Depending on the flavour of CSV, this format may be close enough to what a reading application expects to function.

Warning-icon.png

Предупреждение: TSDFDataset will likely not work at least on ARM-based Windows CE/Windows mobile, see http://bugs.freepascal.org/view.php?id=17871

Light bulb  Примечание: Nov 2012: SDFDataset is intended to be (but has not yet been) redefined to use RFC4180 CSV format. See e.g. http://bugs.freepascal.org/view.php?id=22980

TSdfDataset and TFixedDataset sample files

Sample SDF file

Below is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:
ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE
1,resistor,resistor,1,1,1,LINE
2,capacitor,capacitor,1,1,1,LINE
3,transistor npn,transistor npn
  • Sample TFixedDataset file
Each record occupies a fixed amount of space, and if the field is smaller, spaces should be used to fill the remaining size.
Name = 15 chars; Surname = 15 chars; e_mail = 20 chars;
Piet           Pompies                  piet@pompies.net

Using the datasets: example code

Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:

  • The lines in the database can have a maximum size of about 300. A fix is being researched.
  • It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file.
  • One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions.
  • The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will currently not be possible to have line endings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another rarely used char, like #. When showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.
uses sdfdata, db;

constructor TComponentsDatabase.Create;
var
  FDataset: TSdfDataset;
begin
  inherited Create;

  FDataset := TSdfDataset.Create(nil);
  FDataset.FileName := vConfigurations.ComponentsDBFile;
  FDataset.FileMustExist := false; //don't require existing csv file

  // Not necessary with TSdfDataset:
  //  FDataset.TableName := STR_DB_COMPONENTS_TABLE;
  //  FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;

  // Adds field definitions
  FDataset.FieldDefs.Add('ID', ftString);
  //schema addition is needed so that sdfdataset writes out the csv header correctly:
  FDataset.Schema.Add('ID'); 
  FDataset.FieldDefs.Add('NAMEEN', ftString);
  FDataset.Schema.Add('NAMEEN'); 
  FDataset.FieldDefs.Add('NAMEPT', ftString);
  FDataset.Schema.Add('NAMEPT'); 
  FDataset.FieldDefs.Add('HEIGHT', ftString);
  FDataset.Schema.Add('HEIGHT'); 
  FDataset.FieldDefs.Add('WIDTH', ftString);
  FDataset.Schema.Add('WIDTH'); 
  FDataset.FieldDefs.Add('PINS', ftString);
  FDataset.Schema.Add('PINS'); 
  FDataset.FieldDefs.Add('DRAWINGCODE', ftString);
  FDataset.Schema.Add('DRAWINGCODE'); 

  // Necessary for TSdfDataset
  FDataset.Delimiter := ',';
  FDataset.FirstLineAsSchema := True;

  FDataset.Active := True;

  // Sets the initial record
  CurrentRecNo := 1;
  FDataset.First;
end;

When using TSdfDataSet directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.

If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1.

Example code:

{@@
  Moves to the desired record using TDataset.Next and TDataset.Prior
  This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.

  @param AID Indicates the record number. The first record has number 1
}
procedure TComponentsDatabase.GoToRec(AID: Integer);
begin
  // We are before the desired record, move forward
  if CurrentRecNo < AID then
  begin
    while (not FDataset.EOF) and (CurrentRecNo < AID) do
    begin
      FDataset.Next;
      FDataset.CursorPosChanged;
      Inc(CurrentRecNo);
    end;
  end
  // We are after the desired record, move back
  else if CurrentRecNo > AID  then
  begin
    while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do
    begin
      FDataset.Prior;
      FDataset.CursorPosChanged;
      Dec(CurrentRecNo);
    end;
  end;
end;

Data Export

FreePascal/Lazarus database export functionality (e.g. TCSVExporter on the Data Export tab) offers CSV export functionality for datasets.

Jan's CSV components

See JCSV (Jans CSV Components).

ZMSQL

ZMSQL stores data in semicolon-delimited files (using SDF?).