Sign in Join
Wiki copytemporary

FPSpreadsheet: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11The fpSpreadsheet library offers a convenient way to generate and read spreadsheet documents in various formats. The library is written in a very flexible manner, capable of being extended to support any number of formats easily.
22
33Screenshot of spready demo program provided with fpspreadsheet showing an XLS file:
44
5-<figure>
6-<img src="fpsgrid.png" title="fpsgrid.png" />
7-<figcaption>fpsgrid.png</figcaption>
8-</figure>
9-
10-## Documentation
11-
12-This wiki page covers the latest development/trunk version of FPSpreadsheet available via subversion. Please see section Stable releases for documentation on the stable version that you can download.
13-
14-## API Documentation
15-
16-### API Reference
17-
18-A help file in CHM format can be found in the FPSpreadsheet installation folder *docs*. If you did not yet install the package follow [<http://lazarus-ccr.svn.sourceforge.net/viewvc/lazarus-ccr/components/fpspreadsheet/docs/fpspreadsheet-api.chm>](http://lazarus-ccr.svn.sourceforge.net/viewvc/lazarus-ccr/components/fpspreadsheet/docs/fpspreadsheet-api.chm) to *fpspreadsheet-api.chm*.
19-
20-The second CHM file available in the folder *docs*, *fpspreadsheet-wiki.chm*, is a snapshot of the FPSpreadsheet-related wiki pages bundled into a single help file.
21-
22-### Basics
23-
24-The smallest entities in a spreadsheet are the **cells** which contain the data. Cells can hold various data types, like strings, numbers, dates, times, boolean values, or formulas. In addition, cells can contain information on formatting, i.e. font style, background color, text alignment etc.
25-
26-The cells are arranged in a grid-like structure, called **worksheet**, or **spreadsheet**, consisting of **rows** and **columns**. Each cell has a unique address given by the row and column index.
27-
28-Worksheets are bound together to form a **workbook** which represents the document of the spreadsheet application. The workbook also stores information that is needed from all worksheets, i.e. font list, cell and number format lists, etc.
29-
30-FPSpreadsheet follows this same structure - there is a `TCell`, a `TsWorksheet`, and a `TsWorkbook`.
31-
32-#### Workbook
33-
34-The class `TsWorkbook` is the main class visible to the user. It provides methods for reading data from and writing to files. The versatile structure of the library provides access to various popular file formats, like Excel *.xls* or *.xlsx*, or OpenOffice/LibreOffice *.ods*.
35-
36-The file format is specified by the type `TsSpreadsheetFormat` defined in the unit `fpstypes`
37-
38-``` pascal
39-type
40- TsSpreadsheetFormat = (sfExcel2, sfExcel5, sfExcel8, sfExcelXML, sfOOXML,
41- sfOpenDocument, sfCSV, sfHTML, sfWikiTable_Pipes, sfWikiTable_WikiMedia, sfUser);
42-```
43-
44-where
45-
46-- `sfExcel2, sfExcel5, sfExcel8` stands for versions of the binary xls format used by Excel ("BIFF" = "Binary Interchange File Format") with `sfExcel8` being the most modern one.
47-- `sfOOXML` corresponds to the newer xlsx format introduced by Excel2007
48-- `sfExcelXML` is the xml format which was introduced by Microsoft for Office XP and 2003. Not very popular.
49-- `sfOpenDocument` is the spreadsheet format used by OpenOffice/LibreOffice; by default, the files have the extension *.ods*.
50-- `sfCSV` refers to comma-delimited text files (default extension *.csv*); they can be understood by any text editor and all spreadsheet programs, but do not contain formatting information.
51-- `sfHTML` denotes the standard HTML format as used in web browsers.
52-- `sfWikiTable_Pipes` and `sfWikiTable_WikiMedia` is the format used by tables in wiki websites.
53-- `sfUser` is needed to register a user-defined format. There are no plans to implement "ancient" file formats like Excel3.0/4.0 or Lotus. It is possible, however, to provide your own reading and writing classes to extend the functionality of FPSpreadsheet - see the section below on Adding new file formats
54-
55-When applying fpspreadsheet the first task is to create an instance of the workbook:
56-
57-``` pascal
58-var
59- MyWorkbook: TsWorkbook;
60-begin
61- MyWorkbook := TsWorkbook.Create;
62- ...
63-```
64-
65-Reading of spreadsheet files is accomplished (among others) by the workbook methods
66-
67-- `procedure ReadFromFile(AFileName: string):`\
68- Reads the file with the given name and automatically determines the correct file format.
69-- `procedure ReadFromFile(AFileName: string; AFormat: TsSpreadsheetFormat):`\
70- Reads the file, but assumes that the file format is as specified by `AFormat`.
71-
72-The following workbook methods can be used for saving to file:
73-
74-- `procedure WriteToFile(const AFileName: string; const AFormat: TsSpreadsheetFormat; const AOverwriteExisting: Boolean = False)`:\
75- Writes the workbook to the given file using the given spreadsheet format. If the file already exists it is automatically overwritten if `AOverwriteExisting` is `true`:
76-- `procedure WriteToFile(const AFileName: String; const AOverwriteExisting: Boolean = False)`:\
77- ditto, but the file format is determined from the file extension provided (in case of Excel's xls the most recent version, `sfExcel8`, is used).
78-
79-After calling these methods it is advantageous to look at the workbook's property `ErrorMsg` in which messages due to errors or warnings are collected that might have occured during reading/writing. This property returns a multi-lined string which is displayed best in a memo component; if everything was fine it is an empty string.
80-
81-<b>Note:</b> FPSpreadsheets provides specialized units for reading from and writing to each file format. These units are not available automatically, you have to add them to the uses clause explicitly. FPSpreadsheet will complain about "unsupported file format" if the requested reader/writer is not found. Here is a list of the unit names:
82-
83-- *xlsbiff2*, *xlsbiff5* and *xlsbiff8* for the binary xls file formats `sfExcel2`, `sfExcel5` and `sfExcel8`, respectively,
84-- *xlsxOOXML* for the xlsx file format `sfOOXML` of Excel 2007 and later,
85-- *xlsXML* for the xml format of Excel XP and 2003,
86-- *fpsopendocument* for the file format `sfOpenDocument` of OpenOffice/LibreOffice,
87-- *fpsCSV* for text files with comma-separated values (csv),
88-- *fpsHTML* for HTML files,
89-- *wikitables* for `sfWikiTable_Pipes` and `sfWikiTable_WikiMedia`,
90-- or, simply add *fpsallformats* to get read/write support for all file formats supported.
91-
92-#### Worksheet
93-
94-The workbook contains a list of `TsWorksheet` instances. They correspond to the tabs that you see in Excel or Open/LibreOffice. When reading a spreadsheet file the worksheets are created automatically according to the file contents. When a spreadsheet is created manually to be stored on file a worksheet has to be created by *adding* it to the workbook:
95-
96-``` pascal
97-var
98- MyWorkbook: TsWorkbook;
99- MyWorksheet: TsWorksheet;
100-begin
101- MyWorkbook := TsWorkbook.Create;
102- MyWorksheet := MyWorkbook.AddWorksheet('My_Table');
103- // 'My_Table' is the "name" of the worksheet
104- ...
105-```
106-
107-Already existing worksheets can be accessed by using the `TsWorkbook` methods
108-
109-- `function GetFirstWorksheet: TsWorksheet`: retrieves the first worksheet of the workbook.
110-- `function GetWorksheetByIndex(AIndex: Cardinal): TsWorksheet`: returns the worksheet with the given index (starting at 0).
111-- `function GetWorksheetByName(AName: String): TsWorksheet`: returns the worksheet with the given name which was used when the worksheet was added.
112-
113-The count of already existing worksheets can be queried by calling `GetWorksheetCount`.
114-
115-#### Cell
116-
117-The worksheet, finally, gives access to the cells. A newly created worksheet, as in above example, is empty and does not contain any cells. Cells are added by assigning data or attributes to them by one of the `WriteXXXX` methods of the worksheet. As already mentioned, a cell is addressed by the index of the row and column to which it belongs. As usual, row and column indexes start at 0. Therefore, cell "A1" belongs to row 0 and column 0. It should be noted that row and column index are always specified in this order, this is *different from the convention of*`TStringGrid`. The following example creates a cell at address A1 and puts the number `1.0` in it.
118-
119-``` pascal
120-var
121- MyWorkbook: TsWorkbook;
122- MyWorksheet: TsWorksheet;
123-begin
124- MyWorkbook := TsWorkbook.Create;
125- MyWorksheet := MyWorkbook.AddWorksheet('My_Table');
126- MyWorksheet.WriteNumber(0, 0, 1.0); // "A1" has row=0 and col=0
127- ...
128-```
129-
130-It is also possible to access cells directly by means of the methods `FindCell(ARow, ACol)` or `GetCell(ARow, ACol)` of the workbook. Both funtions exist also in an overloaded version to which the cell address can be passed in Excel notation: `FindCell(ACellStr: String)` or `GetCell(ACellStr: String)`. Please be aware that these functions return a `pointer` to the cell data (type `PCell`). Don't forget to dereference the pointers! The difference between `FindCell` and `GetCell` is that the former one returns `nil`, if a cell does not yet exist, while the latter one creates an empty cell in this case.
131-
132-``` pascal
133-if MyWorksheet.FindCell('A1') = nil then
134- WriteLn('Cell A1 does not exist.');
135-```
136-
137-##### The basic TCell record
138-
139-This is the declaration of the cell's data type:
140-
141-``` pascal
142-type
143- TCell = record
144- { Location of the cell }
145- Worksheet: TsWorksheet;
146- Col: Cardinal; // zero-based
147- Row: Cardinal; // zero-based
148-
149- { Index of format record }
150- FormatIndex: Integer;
151-
152- { Status flags }
153- Flags: TsCellFlags; // (cfHasComment, cfMerged, cfHyperlink, ...)
154-
155- { Cell content }
156- UTF8StringValue: String; // strings cannot be part of a variant record
157- case ContentType: TCellContentType of // must be at the end of the declaration
158- cctEmpty : (); // has no data at all
159- cctFormula : (); // UTF8StringValue is outside the variant record
160- cctNumber : (Numbervalue: Double);
161- cctUTF8String : (); // FormulaValue is outside the variant record
162- cctDateTime : (DateTimevalue: TDateTime);
163- cctBool : (BoolValue: boolean);
164- cctError : (ErrorValue: TsErrorValue);
165- end;
166- PCell = ^TCell;
167-```
168-
169-The field `ContentType` indicates which data type is stored in the cell:
170-
171-``` pascal
172-type
173- TCellContentType = (cctEmpty, cctFormula, cctNumber, cctUTF8String, cctDateTime, cctBool, cctError);
174-```
175-
176-According to this field the corresponding data can be found in the fields
177-
178-- `NumberValue` (for `ContentType=cctNumber`), or
179-- `UTF8StringValue` (for `ContentType=cctUTF8String`), or
180-- `DateTimeValue` (for `ContentType=cctDateTime`), or
181-- `BoolValue` (for `ContentType=cctBool`), i.e. `TRUE` or `FALSE`, or
182-- `ErrorValue` (for `ContentType=cctError`).
183-
184-Due to usage of a variant record most of these values are overlapping, i.e. modification of `NumberValue` affects also the other values. Therefore, always respect the `ContentType` when accessing the `TCell` record directly (the worksheet methods discussed below consider this automatically).
185-
186-The field `Flags` tells whether additional data are associated with the cell which are not included in the cell record usually to save memory:
187-
188-``` pascal
189-type
190- TsCellFlag = (cfHasComment, cfHyperlink, cfMerged, cfHasFormula, cf3dFormula);
191- TsCellFlags = set of TsCellFlag;
192-```
193-
194-- `cfHasComment`: A comment record can be found in the `Comments` of the worksheet.
195-- `cfHyperlink`: The cell is contains a hyperlink stored in the `Hyperlinks` of the worksheet.
196-- `cfMerged`: The cell belongs to a merged block and extends across several cells.
197-- `cfHasFormula`: The cell is associated with a formula which is stored in the `Formulas` of the worksheet.
198-- `cf3dFormula`: The formula associated with the cell contains elements referencing other sheets of the same workbook.
199-
200-> **Note:** After calculation of a formula or after reading of a file, the `ContentType` of the formula cell is converted to that of the result. Then the presence of a formula can only be detetected by calling the function `HasFormula(cell)` for the cell to be queried (`cell: PCell`) in unit *fpsUtils*; this function checks the presence of the element `cfHasFormula` in the cell flags.
201-
202-##### How to add and read data to/from a cell
203-
204-Adding values to a cell is most easily accompished by using one of the `WriteXXXX` methods of the worksheet. The most important ones are:
205-
206-``` pascal
207-type
208- TsWorksheet = class
209- ...
210- { Writing of currency values }
211- function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
212- ANumFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = 2;
213- ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
214- ANegCurrFormat: Integer = -1): PCell; overload;
215- procedure WriteCurrency(ACell: PCell; AValue: Double;
216- ANumFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = -1;
217- ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
218- ANegCurrFormat: Integer = -1); overload;
219- function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
220- ANumFormat: TsNumberFormat; ANumFormatString: String): PCell; overload;
221- procedure WriteCurrency(ACell: PCell; AValue: Double;
222- ANumFormat: TsNumberFormat; ANumFormatString: String); overload;
223-
224- { Writing of date/time values }
225- function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime): PCell; overload;
226- procedure WriteDateTime(ACell: PCell; AValue: TDateTime); overload;
227- function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
228- ANumFormat: TsNumberFormat; ANumFormatStr: String = ''): PCell; overload;
229- procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
230- ANumFormat: TsNumberFormat; ANumFormatStr: String = ''); overload;
231- function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
232- ANumFormatStr: String): PCell; overload;
233- procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
234- ANumFormatStr: String); overload;
235-
236- { Writing of number values }
237- function WriteNumber(ARow, ACol: Cardinal; ANumber: double): PCell; overload;
238- procedure WriteNumber(ACell: PCell; ANumber: Double); overload;
239- function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
240- ANumFormat: TsNumberFormat; ADecimals: Byte = 2): PCell; overload;
241- procedure WriteNumber(ACell: PCell; ANumber: Double;
242- ANumFormat: TsNumberFormat; ADecimals: Byte = 2); overload;
243- function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
244- ANumFormat: TsNumberFormat; ANumFormatString: String): PCell; overload;
245- procedure WriteNumber(ACell: PCell; ANumber: Double;
246- ANumFormat: TsNumberFormat; ANumFormatString: String); overload;
247-
248- { Writing of string values }
249- function WriteText(ARow, ACol: Cardinal; AText: ansistring;
250- ARichTextParams: TsRichTextParams = nil): PCell; overload;
251- procedure WriteText(ACell: PCell; AText: String;
252- ARichTextparams: TsRichTextParams = nil); overload;
253-
254- // the old string methods "WriteUTF8Text" are deprecated now
255- ...
256-```
257-
258-Some of these methods exist in overloaded versions in which cell formatting parameters can be added together with the cell value. Correspondingly to writing, there is also a number of `worksheet` methods for reading the cell values:
259-
260-``` pascal
261-type
262- TsWorksheet = class
263- ...
264- { Reading cell content as a string }
265- function ReadAsText(ARow, ACol: Cardinal): string; overload;
266- function ReadAsText(ACell: PCell): string; overload;
267- function ReadAsText(ACell: PCell; AFormatSettings: TFormatSettings): string; overload;
268-
269- { Reading cell content as a number }
270- function ReadAsNumber(ARow, ACol: Cardinal): Double; overload;
271- function ReadAsNumber(ACell: PCell): Double; overload;
272- function ReadNumericValue(ACell: PCell; out AValue: Double): Boolean;
273-
274- { Reading cell content as a date/time value }
275- function ReadAsDateTime(ARow, ACol: Cardinal; out AResult: TDateTime): Boolean; overload;
276- function ReadAsDateTime(ACell: PCell; out AResult: TDateTime): Boolean; overload;
277- ...
278-```
279-
280-##### Index to Cell format
281-
282-`FormatIndex` is the index of the <span id="id_cellformatrecord">cell format record</span>. It describes the formatting attributes of a cell. These records are collected by an internal list of the workbook and are defined like this:
283-
284-``` pascal
285-type
286- TsCellFormat = record
287- FontIndex: Integer;
288- TextRotation: TsTextRotation;
289- HorAlignment: TsHorAlignment;
290- VertAlignment: TsVertAlignment;
291- Border: TsCellBorders;
292- BorderStyles: TsCellBorderStyles;
293- Background: TsFillPattern;
294- NumberFormatIndex: Integer;
295- NumberFormat: TsNumberFormat;
296- NumberFormatStr: String;
297- BiDiMode: TsBiDiMode; // bdDefault, bdLTR {left-to-right}, bdRTL {right-to-left)
298- Protection: TsCellProtection; // cpLockCell, cpHideFormulas
299- UsedFormattingFields: TsUsedFormattingFields;
300- //uffTextRotation, uffFont, uffBold, uffBorder, uffBackground, uffNumberFormat, uffWordWrap, uffHorAlign, uffVertAlign, uffBiDi, uffProtection, uffDoNotPrint
301- end;
302-```
303-
304-- `FontIndex`: text font by specifying the index in the workbook's font list
305-- `TextRotation`: specifies whether the cell text is written horizontally or vertically
306-- `HorAlignment`: left-aligned, horizontally centered, or right-aligned text
307-- `VertAlignment`: top, bottom or vertically centered text
308-- `Border`: a set of flags indicating that - if set - a border line is drawn at the left, top, right, or bottom cell edge. The lines are drawn according to the `BorderStyles` which define the linestyle and color of the border.
309-- `Background`: a record defining the background fill of a cell (pattern style, pattern color, and background color - see chapter on cell background below).
310-- `NumberFormat` and `NumberFormatStr` specify how number or date/time values are formatted (e.g., number of decimal places, long or short date format, etc.).
311-- Only those format attributes for which a flag is set in the `UsedFormattingFields` are considered when formatting a cell. If a flag is not included then the corresponding attribute is ignored and replaced by its default value.
312-
313-For specifying a format for a given cell call the corresponding the worksheet method `WriteXXXX`, for retrieving a format call `ReadXXXX`. These methods usually get a pointer to the cell as a parameter, but there are also overloaded versions which accept the row and column index. Moreover, formatting styles can also be applied directly to the cell by using a record helper implemented in unit *fpsCell*.
314-
315-See cell formatting below for a more detailed description.
316-
317-#### Columns and rows
318-
319-Column and row records are added for each column and row having a non-default properties:
320-
321-``` pascal
322-type
323- TCol = record
324- Col: Cardinal;
325- Width: Single;
326- ColWidthType: TsColWidthType; // = (cwtDefault, cwtCustom)
327- FormatIndex: Integer;
328- Options: TsColRowOptions; // set of [croHidden, croPageBreak]
329- end;
330- PCol = ^TCol;
331-
332- TRow = record
333- Row: Cardinal;
334- Height: Single;
335- RowHeightType: TsRowHeightType; // = (rhtDefault, rhtCustom, rhtAuto)
336- FormatIndex: Integer;
337- Options: TsColRowOptions; // set of [croHidden, croPageBreak]
338- Hidden: Boolean;
339- PageBreak: Boolean;
340- end;
341- PRow = ^TRow;
342-```
343-
344-##### Column width / row height
345-
346-**Column widths** and **row heights** can be specified in a variety of units defined by the type `TsSizeUnits = (suChars, suLines, suMillimeters, suCentimeters, suPoints, suInches)`. `suChars` refers to the count of `0` characters fitting into the column width - this is the way how Excel defines column widths. `suLines` is the number of lines fitting into the row height. Both units are based on the character size of the workbook's default font. The other units are conventional physical length units (1 cm = 10 mm, 1 inch = 25.4 mm = 72 pt). Fractional values are accepted. The workbook and worksheets store lengths internally in millimeters (`MyWorkbook.Units`).
347-
348-The Office applications usually adjust the row heights automatically according to the font or text rotation of the cell content. This case is identified by `RowHeightType` having the value `rhtAuto`. Since the worksheet cannot calculate text size very accurately automatic row heights are not written by FPSpreadsheet; they are replaced by the **default row height**. The default row height is also used if a row is empty, i.e. does not contain any data cells. Its value can be changed by calling the worksheet's `WriteDefaultRowHeight()` or by using the worksheet property `DefaultRowHeight`. In `WriteDefaultRowHeight`, the units must be specified while in `DefaultRowHeight` they are assumed to be lines. Similarly, the **default column width** can be specified by `WriteDefaultColWidth()` or the property `DefaultColWidth` (in characters).
349-
350-In order to overrun automatic and default row heights call the worksheet method `WriteRowHeight()`. These row records are identified by `RowHeightType` having the value `rhtCustom`. In the same way the width of columns can be set to a specific value by calling `WriteColWidth()`. `ColWidthType` of these columns is `cwtCustom`.
351-
352-The height/width of a particular row/column can be retrieved by means of the methods `GetRowHeight` or `GetColWidth`. Note that these methods return the default row heights/column widths if there are no `TRow`/`TCol` records.
353-
354-``` pascal
355-type TsWorksheet = class
356- ...
357- { Set row height }
358- procedure WriteRowHeight(ARowIndex: Cardinal; AHeight: Single; AUnits: TsSizeUnits);
359- { Set column width }
360- procedure WriteColWidth(AColIndex: Cardinal; AWidth: Single; AUnits: TsSizeUnits);
361- { Set default row height }
362- procedure WriteDefaultRowHeight(AHeight: Single; AUnits: TsSizeUnits);
363- {Set default cokumn width }
364- procedure WriteDefaultColWidth(AWidth: Single; AUnits: TsSizeUnits);
365-
366- { Return row height }
367- function GetRowHeight(ARowIndex: Cardinal; AUnits: TsSizeUnits): Single;
368- { Return column width }
369- function GetColWidth(AColIndex: Cardinal; AUnits: TsSizeUnits): Single;
370- { Return default row height }
371- function ReadDefaultRowHeight(AUnits: TsSizeUnits): Single;
372- { Return default column width }
373- function ReadDefaultColWidth(AUnits: TsSizeUnits): Single;
374-
375- property DefaultRowHeight: Single; // in lines
376- property DefaultColWidht: Single; // in characters
377-```
378-
379-There are also overloaded versions of these methods which do not require the `AUnits` parameter. In this case, row heights are defined in terms of line count, and column widths are defined in terms of character count. Note that these variants are from previos versions and are deprecated now.
380-
381-##### Column and row formats
382-
383-The `FormatIndex` element of the row and column records format applied to the entire row or column. Together with cells, these formats are stored as `TsCellFormat` records in an internal workbook list, `FormatIndex` is the index of the format properties into this list. See details in section Cell formatting. **Row and column formats** are primarily applied to empty cells, but if a new cell is added it will automatically get the format of the row or column. (If both row and column have different formats then the row format will be used).
384-
385-Here is a listing of the worksheet methods available for column and row formatting:
386-
387-``` Pascal
388-type TsWorksheet = class
389- // Assign a format to a column or row
390- procedure WriteColFormatIndex(ACol: Cardinal; AFormatIndex: Integer);
391- procedure WriteRowFormatIndex(ARow: Cardinal; AFormatIndex: Integer);
392-
393- // Query the format of a column or row
394- function GetColFormatIndex(ACol: Cardinal): Integer;
395- function GetRowFormatIndex(ARow: Cardinal): Integer;
396-
397- // Returns the font assigned to a column or row
398- function ReadColFont(ACol: PCol): TsFont;
399- function ReadRowFont(ARow: PRow): TsFont;
400-
401- // Check whether any column or row uses a special format
402- function HasRowFormats: Boolean;
403- function HasColFormats: Boolean;
404-```
405-
406-##### Hidden columns / rows
407-
408-Adding the flag `croHidden` to the row's or column's `Options` hides the row or column in the Office application (or in TsWorksheetGrid). The following worksheet methods are helpers to handle **row/column visibility**:
409-
410-``` pascal
411-type TsWorksheet = class
412- ...
413- { Hide column/row }
414- procedure HideCol(ACol: Cardinal);
415- procedure HideRow(ARow: Cardinal);
416-
417- { Show a previously hidden column/row }
418- procedure ShowCol(ACol: Cardinal);
419- procedure ShowRow(ARow: Cardinal);
420-
421- { Check whether column/row is hidden }
422- function ColHidden(ACol: Cardinal): Boolean;
423- function RowHidden(ARow: Cardinal): Boolean;
424-```
425-
426-##### Page breaks
427-
428-The flag `croPageBreak` can be added to the row's or column's `Options` in order to force a **page break** before the corresponding row or column when the worksheet is printed by the Office applications. Note that FPSpreadsheet itself does not support printing. The following worksheet methods help with page breaks:
429-
430-``` pascal
431-type TsWorksheet = class
432- ...
433- { Enforce a page break before the specified column/row }
434- procedure AddPageBreakToCol(ACol: Cardinal);
435- procedure AddPageBreakToRow(ARow: Cardinal);
436-
437- { Removes a page break previously added to a column/row }
438- procedure RemovePageBreakFromCol(ACol: Cardinal);
439- procedure RemovePageBreakFromRow(ARow: Cardinal);
440-
441- { Checks whether a page break is forced before the specified column/row }
442- function IsPageBreakCol(ACol: Cardinal): Boolean;
443- function IsPageBreakRow(ARow: Cardinal): Boolean;
444-```
445-
446-#### Events
447-
448-Worksheets and workbooks fire a series of events such as OnChangeCell, OnChangeFont, etc. The events usually are intended for interaction with the [[FPSpreadsheet tutorial: Writing a mini spreadsheet application|visual spreadsheet controls]]. If you need to attach your own handlers you should make sure that the original handler is called, at least in a gui program using the spreadsheet controls. Or you use the events provided by the visual controls themselves, e.g. [[TsWorksheetGrid|WorksheetGrid]]`.OnEditingDone` instead of `WorksheetGrid.Worksheet.OnChangeCell`.
449-
450-### Formulas
451-
452-Two kinds of formulas are supported by FPSpreadsheet:
453-
454-- **String formulas**: These are written in strings just like in the office applications, for example `"=ROUND(A1+B1,0)"`. They are used internally in the files of Open/LibreOffice and Excel *.xlsx*.
455-- **RPN formulas** are used internally by the binary *.xls* Excel files. They are written in Reverse Polish Notation (RPN), for example: `A1, B1, Add, 0, ROUND`. If a spreadsheet containing formulas is to be saved in a binary Excel format, the RPN formulas required are generated automatically.
456-
457-FPSpreadsheet can convert between string and rpn formulas. Formulas in both types can be calculated.
458-
459-In older versions of FPSpreadsheet, formulas were stored directly in the cell record. This was given up to have parsed formulas available for faster calculation. The formulas are stored in the tree `Formulas` of the worksheet. The formula record contains the row and column index of the cell to which the formula belongs, the string representation of the formula, as well as the parser tree for quick evaluation.
460-
461-FPSpreadsheet supports the majority of the formulas provided by the common spreadsheet applications. However, when reading a file created by these applications, there is always a chance that an unsupported formula is contained. To avoid crashing of fpspreadsheet, reading of formulas is disabled by default; the cell displays only the result of the formula written by the Office application. To activate reading of formulas add the element `boReadformulas` to the workbook's `Options` before opening the file. If an error occurs in this case the reader normally catches the exception, writes the exception message into the workbook's errorlog and continues reading. If you want reading to stop you must add the `boAbortReadingOnFormulaError` to the workbook `Options`.
462-
463-Formulas can link to data in other sheets of the same workbook ("3d formulas") by applying the Excel syntax (see below). External links to spreadsheets in other files are not supported.
464-
465-Calculation of formulas is normally not needed when a file is written by FPSpreadsheet for opening in an Office application because that automatically calculates the formula results. If the same file, however, is openend by an application based on FPSpreadsheet the calculated cells would be empty because the formulas are not automatically calculated by default. To activate calculation of formulas before writing a spreadsheet to file you have to add the option `boCalcBeforeSaving` to the workbook's `Options`.
466-
467-If FPSpreadshet is used in an interactive application (such as the *spready* demo found in the *examples* folder of the FPSpreadsheet installation) it is desirable to calculate formulas automatically whenever formula strings or cell values are changed by the user. This can be achieved by the option `boAutoCalc` in the workbook's `Options`.
468-
469-The most general setting regarding formulas, therefore, is
470-
471-``` pascal
472- MyWorkbook.Options := MyWorkbook.Options + [boReadFormulas, boCalcBeforeSaving, boAutoCalc];
473-```
474-
475-Calculation of formulas can be triggered manually by calling the method `CalcFormulas` of the worksheet or workbook. The latter is absolutely required when the workbook contains 3d formulas where the result of one cell can affect cells in other sheets. If there are only within-sheet formulas then the worksheet's `CalcFormulas` is sufficient.
476-
477-#### String formulas
478-
479-String formulas are written in the same way as in the Office applications. The worksheet method for creating a string formula is `WriteFormula`:
480-
481-``` pascal
482-var
483- MyWorksheet: TsWorksheet;
484-//...
485- MyWorksheet.WriteFormula(0, 1, '=ROUND(A1+B2+1.215,0)');
486- // By default, use dot as decimal and comma as list separator!
487-```
488-
489-A few notes on **syntax**:
490-
491-- The leading `=` character which identifies formulas in the Office applications is not absolutely necessary here and can be dropped. The formula is stored in the cell record without it.
492-- The case of the formula name is ignored.
493-- Spaces can be added for better readability, but they will be lost when saving.
494-- Strings must be enclosed in double quotes.
495-- The corner points of a cell range must be separated by a colon (":"), e.g. `A1:C3`. Unordered ranges will be rearranged when the formula is parsed, i.e. `C3:A1` becomes `A1:C3`.
496-- Links to other worksheets must follow the Excel syntax which separates the sheetname and cell address by a "!". An single cell, for example, can be linked by `Sheet1!A1`. An range of sheets must be placed before the cell or cell range, e.g. `Sheet1:Sheet2!A1:C3`. Note that the Open/LibreOffice syntax with a separating point and reference to the corner points of the 3d box (i.e., `Sheet1.A1:Sheet2.C3`) is not supported. Note also that the worksheet(s) to which the formula links must exist at the time when the formula is added; otherwise the link will be replaced by the error code `#REF!`, and the formula will not be usable even if the missing sheet is added later.
497-- Normally, floating point numbers must be entered with a dot as decimal separator, and a comma must be used to separate function arguments.
498-- Setting the optional parameter `ALocalized` of the worksheet methods `WriteFormula` to `TRUE`, however, allows to use localized decimal and list separators taken from the workbook's `FormatSettings` - see *spready* demo.
499-
500-``` pascal
501-var
502- MyWorksheet: TsWorksheet;
503-//...
504- MyWorksheet.WriteFormula(0, 1, '=ROUND(A1+B2+1,215;0)', true);
505- // Because of the "true" the formula parser accepts the comma as decimal and the
506- // semicolon as list separator if the workbook's FormatSettings are set up like this.
507-```
508-
509-Use the worksheet methods `ReadFormula` or `ReadFormulaAsString` to retrieve the string formula assigned to the cell. The pointer to the cell must be given as a parameter. The latter function accepts an additional (boolean) parameter `ALocalized` to use the decimal and list separators of the workbook's `FormatSettings` for creation of the formula string.
510-
511-``` pascal
512-var
513- MyWorksheet: TsWorksheet;
514- cell: PCell;
515-//...
516- cell := MyWorksheet.FindCell(0, 1);
517- WriteLn('The formula in internal format is ', MyworkSheet.ReadFormula(cell));
518- WriteLn('The localized formula is ', MyWorksheet.ReadFormulaAsString(cell, true));
519-//-------------------------------------------------------------------
520-// For the previous example, this will result in the following output
521-The formula in internal format is ROUND(A1+B2+1.215,0)
522-The localized formula is ROUND(A1+B2+1,215;0)
523-```
524-
525-#### RPN formulas
526-
527-At application level, string formulas are mainly used, and RPN formulas are of little practical importance. Therefore, documentation of RPN formulas has been removed from this main FPSpreadsheet wiki and can be found in the article [[RPN Formulas in FPSpreadsheet|"RPN Formulas in FPSpreadsheet"]].
528-
529-#### Shared formulas and array formulas
530-
531-- **Shared formulas** are only supported for reading (from Excel files).
532-- **Array formulas** are not supported, currently.
533-
534-#### List of built-in formulas
535-
536-FPSpreadsheet supports more than 80 built-in formulas. In order not to blow up this wiki page too much documentation of these formulas has been moved to the [[FPSpreadsheet: List of formulas|separate document "List of formulas"]].
537-
538-To learn more about the functions available, look at file *testcases_calcrpnformula.inc* in the *tests* folder of the FPSpreadsheet installation where every function is included with at least one sample.
539-
540-#### Extending FPSpreadsheet by user-defined formulas
541-
542-Although the built-in formulas cover most of the applications there may be a need to access a formula which is available in the Office application, but not in FPSpreadsheet. For this reason, the library supports a registration mechanism which allows to add user-defined functions to the spreadsheets. This can be done by calling the procedure `RegisterFunction` from the unit *fpsExprParser*:
543-
544-``` pascal
545-procedure RegisterFunction(const AName: ShortString; const AResultType: Char;
546- const AParamTypes: String; const AExcelCode: Integer; ACallBack: TsExprFunctionCallBack); overload;
547-
548-procedure RegisterFunction(const AName: ShortString; const AResultType: Char;
549- const AParamTypes: String; const AExcelCode: Integer; ACallBack: TsExprEventCallBack); overload;
550-```
551-
552-- `AName` specifies the name under which the function will be called in the spreadsheet. It must match the name of the formula in the Office application.
553-- `AResultType` is a character which identifies the data type of the function result:
554- - `'F'` - floating point number
555- - `'I'` - integer
556- - `'D'` - date/time
557- - `'B'` - boolean
558- - `'S'` - string
559- - `'C'` - cell address, e.g. 'A1'
560- - `'R'` - cell range address, e.g. 'A1:C3'
561-- `AParamTypes` is a string in which each character identifies the data type of the corresponding argument. In addition to the list shown above the following symbols can be used:
562- - `'?'` - any type
563- - `'+'` - must be the last character. It means that the preceding character is repeated indefinitely. This allows for an arbitrary argument count. Please note, however, that Excel supports only up to 30 arguments.
564- - lowercase `'f', 'i', 'd', 'b', 's'` indicate optional parameters of the type explained above. Of course, uppercase symbols cannot follow lower-case symbols.
565-- `AExcelCode` is the identifier of the function in xls files. See "OpenOffice Documentation of the Microsoft Excel File Format", section 3.11, for a list.
566-- `ACallback` identifies which function is called by FPSpreadsheet for calculation of the formula. It can either be a procedure or an event handler.
567-
568-``` pascal
569-type
570- TsExprFunctionCallBack = procedure (var Result: TsExpressionResult; const Args: TsExprParameterArray);
571- TsExprFunctionEvent = procedure (var Result: TsExpressionResult; const Args: TsExprParameterArray) of object;
572-```
573-
574-The `TsExpressionResult` is a variant record containing result or argument data of several types:
575-
576-``` pascal
577-type
578- TsResultType = (rtEmpty, rtBoolean, rtInteger, rtFloat, rtDateTime, rtString,
579- rtCell, rtCellRange, rtError, rtAny);
580-
581- TsExpressionResult = record
582- Worksheet : TsWorksheet;
583- ResString : String;
584- case ResultType : TsResultType of
585- rtEmpty : ();
586- rtError : (ResError : TsErrorValue);
587- rtBoolean : (ResBoolean : Boolean);
588- rtInteger : (ResInteger : Int64);
589- rtFloat : (ResFloat : TsExprFloat);
590- rtDateTime : (ResDateTime : TDatetime);
591- rtCell : (ResRow, ResCol : Cardinal);
592- rtCellRange : (ResCellRange : TsCellRange);
593- rtString : ();
594- end;
595-
596- TsExprParameterArray = array of TsExpressionResult;
597-```
598-
599-As an example we show here the code for the `CONCATENATE()` formula which joins two or more strings:
600-
601-``` pascal
602-const
603- INT_EXCEL_SHEET_FUNC_CONCATENATE = 336;
604-...
605- RegisterFunction('CONCATENATE', 'S', 'S+', INT_EXCEL_SHEET_FUNC_CONCATENATE, @fpsCONCATENATE);
606-
607-procedure fpsCONCATENATE(var Result: TsExpressionResult; const Args: TsExprParameterArray);
608-// CONCATENATE( text1, text2, ... text_n )
609-var
610- s: String;
611- i: Integer;
612-begin
613- s := '';
614- for i:=0 to Length(Args)-1 do
615- begin
616- if Args[i].ResultType = rtError then
617- begin
618- Result := ErrorResult(Args[i].ResError);
619- exit;
620- end;
621- s := s + ArgToString(Args[i]);
622- // "ArgToString" simplifies getting the string from a TsExpressionResult as
623- // a string may be contained in the ResString and in the ResCell fields.
624- // There is such a function for each basic data type.
625- end;
626- Result := StringResult(s);
627- // "StringResult" stores the string s in the ResString field of the
628- // TsExpressionResult and sets the ResultType to rtString.
629- // There is such a function for each basic data type.
630-end;
631-```
632-
633-There is a worked-out example (*demo_formula_func.pas*) in the folder *examples/other* of the FPSpreadsheet installation. In this demo, four financial functions (`FV()`, `PV()`, `PMT()`, `RATE()`) are added to FPSpreadsheet.
634-
635-#### Unsupported formulas
636-
637-Sometimes it is required to create files for the Office applications with formulas not supported by fpspreadsheet. This is possible to some extent when the workbook option `boIgnoreFormulas` is active. Then any arbitrary formula can be written to a cell, and the formula is not checked and not evaluated. The workbook can be written to an .ods or .xlsx file. The old xls file format cannot be used because the formula would have to be parsed to create the rpn formula needed.
638-
639-In folder *examples/other* you can find the sample project *demo_ignore_formula* which creates an ods file with references to another data file - external references normally are not supported by fpspreadsheet, and thus the ignore-formulas workaround must be used. Note that this example does not work with xlsx because Excel writes information on the external links to separate xml files within the xlsx container.
640-
641-### Cell formatting
642-
643-#### Number and date/time formats
644-
645-Numbers and date/time values can be displayed in a variety of formats. In FPSpreadsheet this can be achieved in two ways:
646-
647-- using **built-in number formats** by specifiying a value for the `NumberFormat` of the cell
648-- using a custom **format string**.
649-
650-Number formats can be specified by these worksheet methods:
651-
652-``` pascal
653-type
654- TsWorksheet = class
655- public
656- // Set number formats alone
657- function WriteNumberFormat(ARow, ACol: Cardinal; ANumberFormat: TsNumberFormat;
658- const AFormatString: String = ''): PCell; overload;
659- procedure WriteNumberFormat(ACell: PCell; ANumberFormat: TsNumberFormat;
660- const AFormatString: String = ''); overload;
661-
662- function WriteNumberFormat(ARow, ACol: Cardinal; ANumFormat: TsNumberFormat;
663- ADecimals: Integer; ACurrencySymbol: String = ''; APosCurrFormat: Integer = -1;
664- ANegCurrFormat: Integer = -1): PCell; overload;
665- procedure WriteNumberFormat(ACell: PCell; ANumFormat: TsNumberFormat;
666- ADecimals: Integer; ACurrencySymbol: String = '';
667- APosCurrFormat: Integer = -1; ANegCurrFormat: Integer = -1); overload;
668-
669- function WriteFractionFormat(ARow, ACol: Cardinal; AMixedFraction: Boolean;
670- ANumeratorDigits, ADenominatorDigits: Integer): PCell; overload;
671- procedure WriteFractionFormat(ACell: PCell; AMixedFraction: Boolean;
672- ANumeratorDigits, ADenominatorDigits: Integer); overload;
673-
674- // Set date/time formats alone
675- function WriteDateTimeFormat(ARow, ACol: Cardinal; ANumberFormat: TsNumberFormat;
676- const AFormatString: String = ''): PCell; overload;
677- procedure WriteDateTimeFormat(ACell: PCell; ANumberFormat: TsNumberFormat;
678- const AFormatString: String = ''); overload;
679-
680- // Set cell values and number formats in one call
681-
682- // number values
683- function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
684- AFormat: TsNumberFormat = nfGeneral; ADecimals: Byte = 2;
685- ACurrencySymbol: String = ''): PCell; overload;
686- procedure WriteNumber(ACell: PCell; ANumber: Double; AFormat: TsNumberFormat = nfGeneral;
687- ADecimals: Byte = 2; ACurrencySymbol: String = ''); overload;
688- function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
689- AFormat: TsNumberFormat; AFormatString: String): PCell; overload;
690- procedure WriteNumber(ACell: PCell; ANumber: Double;
691- AFormat: TsNumberFormat; AFormatString: String); overload;
692-
693- // date/time values
694- function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
695- AFormat: TsNumberFormat = nfShortDateTime; AFormatStr: String = ''): PCell; overload;
696- procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
697- AFormat: TsNumberFormat = nfShortDateTime; AFormatStr: String = ''); overload;
698- function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
699- AFormatStr: String): PCell; overload;
700- procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
701- AFormatStr: String); overload;
702-
703- // currency values
704- function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
705- AFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = 2;
706- ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
707- ANegCurrFormat: Integer = -1): PCell; overload;
708- procedure WriteCurrency(ACell: PCell; AValue: Double;
709- AFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = -1;
710- ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
711- ANegCurrFormat: Integer = -1); overload;
712- function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
713- AFormat: TsNumberFormat; AFormatString: String): PCell; overload;
714- procedure WriteCurrency(ACell: PCell; AValue: Double;
715- AFormat: TsNumberFormat; AFormatString: String); overload;
716- ...
717-```
718-
719-##### Built-in number formats
720-
721-The **built-in formats** are defined by the enumeration `TsNumberFormat`. In spite of its name, the elements cover both number and date/time values:
722-
723-``` pascal
724-type
725- TsNumberFormat = (
726- // general-purpose for all numbers
727- nfGeneral,
728- // numbers
729- nfFixed, nfFixedTh, nfExp, nfPercentage, nfFraction,
730- // currency
731- nfCurrency, nfCurrencyRed,
732- // dates and times
733- nfShortDateTime, nfShortDate, nfLongDate, nfShortTime, nfLongTime,
734- nfShortTimeAM, nfLongTimeAM, nfDayMonth, nfMonthYear, nfTimeInterval,
735- // other (using format string)
736- nfCustom);
737-```
738-
739-- **nfGeneral** corresponds to the default formatting showing as many decimals as possible (the number `3.141592654` would be unchanged.)
740-- **nfFixed** limits the decimals. The number of decimal places has to be specified in the call to `WriteNumber`. Example: with 2 decimals, the number `3.141592654` becomes `3.14`.
741-- **nfFixedTh**: similar to `nfFixed`, but adds a thousand separator when the number is displayed as a string: The number `3.141592654` would remain like in the previous example because it is too small to show thousand separators. But the number `314159.2654` would become `314,159.26`, for 2 decimals.
742-- **nfExp** selects exponential presentation, i.e. splits off the exponent. The parameter `ADecimals` in `WriteNumber` determines how many decimal places are used. (The number `3.141592654` becomes `3.14E+00` in case of two decimals).
743-- **nfPercentage** displays the number as a percentage. This means that the value is multiplied by 100, and a percent sign is added. Again, specify in `ADecimals` how many decimal places are to be shown. (The number `3.141592654` is displayed as `314.92%`, in case of 2 decimals).
744-- **nfFraction** presents a number as a fraction. Details (mixed fraction?, maximum digit count for numerator or denominator) for can be specified in the worksheet method `WriteFractionFormat`.
745-- **nfCurrency** displays the number together with a currency symbol, and there are special rules how to display negative values (in brackets, or minus sign before or after the number). The FormatSettings of the workbook are used to define the currency sign and the way numbers are displayed (`FormatSettings.CurrencyString` for the currency symbol, `FormatSettings.CurrencyFormat` for positive, `FormatSettings.NegCurrFormat` for negative values). These settings can be overridden by specifying them in the call to `WriteCurrency` directly.
746-- **nfCurrendyRed** like `nfCurrency`, in addition negative values are displayed in red.
747-- **nfShortDateTime** presents the DateTimeValue of the cell in "short date/time format", i.e. days + two digit months + two digit year + hours + minutes, no seconds. The order of the date parts is taken from the workbook's `FormatSettings`. This applies also to the other date/time formats.
748-- **nfShortDate** creates a date string showing day + two-digit month + two-digit year
749-- **nfShortTime** creates a time string showing hours + minutes.
750-- **nfLongTime**, similar, but includes seconds as well
751-- **nfShortTimeAM**, similar to `nfShortTime`, but uses the AM/PM time format, i.e. hours go up to 12, and AM or PM is added to specify morning or evening/afternoon.
752-- **nfLongTimeAM**, like `nfShortTimeAM`, but includes seconds
753-- **nfTimeInterval**, like `nfLongTime`, but there can be more than 24 hours. The interval can also be expressed in minutes or seconds, if the format strings `[n]:ss`, or `[s]`, respectively, are used.
754-- **nfCustom** allows to specify a dedicated formatting string.
755-
756-As already noted the workbook has a property `FormatSettings` which provides additional information to control the resulting formatting. This is essentially a copy of the `DefaultFormatSettings` declared in the *sysutils* unit (the elements `LongDateFormat` and `ShortDateFormat` are slightly modified to better match the default settings in the main spreadsheet applications). The main purpose of the `FormatSettings` is to add a simple way of localization to the number formats.
757-
758-##### Number format strings
759-
760-In addition to these pre-defined formats, more specialized formatting can be achieved by using the format constant `nfCustom` along with a dedicated **format string**. The format string is constructed according to Excel syntax which is close to the syntax of fpc's `FormatFloat` and `FormatDateTime` commands (accepted as well, see the online-help for these functions).
761-
762-Here is a basic list of the symbols used:
763-
764-<table>
765-<thead>
766-<tr>
767-<th>Symbol</th>
768-<th>Meaning</th>
769-<th>Format string: Number --&gt; Output string</th>
770-</tr>
771-</thead>
772-<tbody>
773-<tr>
774-<td><code>General</code></td>
775-<td>Displays all decimal places of the number</td>
776-<td><code>'General'</code>:<br />
777-1.2345678 --&gt; <code>'1.2345678'</code></td>
778-</tr>
779-<tr>
780-<td><code>0</code></td>
781-<td>Displays insignificant zeros if a number has less digits than there are zeros in the format. If used for decimal places then the number is rounded to as many decimal places as 0s are found.</td>
782-<td><code>'000'</code>: 1 --&gt; <code>'001'</code><br />
783-<code>'0.0'</code>: 1 --&gt; <code>'1.0'</code><br />
784-<code>'0.0'</code>: 1.2345678 --&gt; <code>'1.2'</code></td>
785-</tr>
786-<tr>
787-<td><code>*</code></td>
788-<td>Like "0" above, but does not display insignificant zeros.</td>
789-<td><code>'0.*'</code>: 1 --&gt; <code>'1.'</code><br />
790-<code>'0.*'</code>: 1.2345678 --&gt; <code>'1.2'</code></td>
791-</tr>
792-<tr>
793-<td><code>?</code></td>
794-<td>Like "0" above, but insignificant zeros are replaced by space characters. Good for aligning decimal points and fractions</td>
795-<td><code>'??0'</code>: 1 --&gt; <code>' 1'</code><br />
796-<code>'0.0??'</code>: 1 --&gt; <code>'1.0 '</code></td>
797-</tr>
798-<tr>
799-<td><code>.</code></td>
800-<td>Decimal separator; will be replaced by the value used in the <code>DecimalSeparator</code> of the workbook's <code>FormatSettings</code></td>
801-<td><code>'0.00'</code>: 8.9 --&gt; <code>'8.90'</code></td>
802-</tr>
803-<tr>
804-<td><code>,</code></td>
805-<td>Thousand separator; will be replaced by the value used in the <code>ThousandSeparator</code> of the workbook's <code>FormatSettings</code>. If at the end of a number formatting sequence the displayed value is divided by 1000.</td>
806-<td><code>'#,##0.00'</code>: 1200 --&gt; <code>'1,200.00'</code><br />
807-<code>'0.00,'</code>: 1200 --&gt; <code>'1.20'</code></td>
808-</tr>
809-<tr>
810-<td><code>E+</code>, <code>e+</code></td>
811-<td>Displays a number in exponential format. The digits used for the exponent are defined by the number of zeros added the this symbol. The sign of the exponent is shown for positive and negative exponents.</td>
812-<td><code>'0.00E+00'</code>: 1200 --&gt; <code>1.20E+03</code></td>
813-</tr>
814-<tr>
815-<td><code>E-</code>, <code>e-</code></td>
816-<td>Displays a number in exponential format. The digits used for the exponent are defined by the number of zeros added the this symbol. The sign of the exponent is shown only for negative exponents.</td>
817-<td><code>'0.00e-000'</code>: 1200 --&gt; <code>1.20e003</code></td>
818-</tr>
819-<tr>
820-<td><code>%</code></td>
821-<td>Displays the number as a "percentage", i.e. the number is multiplied by 100 and a <code>%</code> sign is added.</td>
822-<td><code>'0.0%'</code>: 0.75 --&gt; <code>75.0%</code></td>
823-</tr>
824-<tr>
825-<td><code>/</code></td>
826-<td>This symbol has two meanings: if the cell represents a "number" then the slash indicates formatting as fraction, place holders for numerator and denominator must follow. If the cell represents a "date/time" then the slash indicates the date separator which will be replaced by the <code>DateSeparator</code> of the workbook's <code>FormatSettings</code></td>
827-<td><code>'#/#'</code>: 1.5 --&gt; <code>'3/2'</code><br />
828-<code>'# #/#'</code>: 1.5 --&gt; <code>'1 1/2'</code><br />
829-<code>'# #/16'</code>: 1.5 --&gt; <code>'1 8/16'</code><br />
830-also: see date/time examples below</td>
831-</tr>
832-<tr>
833-<td><code>:</code></td>
834-<td>Separator between hours, minutes and seconds of a date/time value. Will be replaced by the <code>TimeSeparator</code> of the workbook's <code>FormatSettings</code>.</td>
835-<td>see examples below</td>
836-</tr>
837-<tr>
838-<td><code>yyyy</code></td>
839-<td>Place holder for the year of a date/time value. The year is displayed as a four-digit number.</td>
840-<td><code>'yyyy/mm/dd'</code>:<br />
841-Jan 3, 2012 --&gt; <code>'2012-01-03'</code><br />
842-In this example, the <code>DateSeparator</code> is a dash character (<code>-</code>).</td>
843-</tr>
844-<tr>
845-<td><code>yy</code></td>
846-<td>Place holder for the year of a date/time value. The year is displayed as a two-digit number.</td>
847-<td><code>'yy/mm/dd'</code>:<br />
848-Jan 3, 2012 --&gt; <code>'12-01-03'</code></td>
849-</tr>
850-<tr>
851-<td><code>m</code></td>
852-<td>Place holder for the month of a date/time value. The month is shown as a number without extra digits.<br />
853-Please note that the <code>m</code> code can also be interpreted as the "minutes" of a time value (see below).</td>
854-<td><code>'yyyy/m/dd'</code>:<br />
855-Jan 3, 2012 --&gt; <code>'2012-1-03'</code></td>
856-</tr>
857-<tr>
858-<td><code>mm</code></td>
859-<td>Place holder for the month of a date/time value. The month is shown as a two-digit number, i.e. a leading zero is added for January to September.<br />
860-Please note that the <code>mm</code> code can also be interpreted as the "minutes" of a time value (see below).</td>
861-<td><code>'yyyy/mm/dd'</code>:<br />
862-Jan 3, 2012 --&gt; <code>'2012-01-03'</code></td>
863-</tr>
864-<tr>
865-<td><code>mmm</code></td>
866-<td>Place holder for the month of a date/time value. The month is displayed by its abbreviated name.</td>
867-<td><code>'yyyy/mmm/dd'</code>:<br />
868-Jan 3, 2012 --&gt; <code>'2012-Jan-03'</code></td>
869-</tr>
870-<tr>
871-<td><code>mmmm</code></td>
872-<td>Place holder for the month of a date/time value. The month is displayed by its full name.<br />
873-</td>
874-<td><code>'yyyy/mmm/dd'</code>:<br />
875-Jan 3, 2012 --&gt; <code>'2012-January-03'</code></td>
876-</tr>
877-<tr>
878-<td><code>d</code></td>
879-<td>Place holder for the day of a date/time value to be displayed as a number. The day is displayed as a simple number, without adding a leading zero.</td>
880-<td><code>'yyyy/mm/d'</code>:<br />
881-Jan 3, 2012 --&gt; <code>'2012-01-3'</code></td>
882-</tr>
883-<tr>
884-<td><code>dd</code></td>
885-<td>Place holder for the day of a date/time value to be displayed as a number. <code>dd</code> adds a leading zero to single-digit day numbers.</td>
886-<td><code>'yyyy/mm/dd'</code>:<br />
887-Jan 3, 2012 --&gt; <code>'2012-01-03'</code></td>
888-</tr>
889-<tr>
890-<td><code>ddd</code></td>
891-<td>Place holder for the day of a date/time value. The day is displayed as its abbreviated name.</td>
892-<td><code>'dddd, yyyy/mm/ddd'</code>:<br />
893-Jan 03, 2012 --&gt; <code>'Tue 2012-01-03'</code></td>
894-</tr>
895-<tr>
896-<td><code>dddd</code></td>
897-<td>Place holder for the day of a date/time value. The day is displayed as its full name.</td>
898-<td><code>'dddd, yyyy/mmmm/dd'</code>:<br />
899-Jan 03, 2012 --&gt; <code>'Tuesday 2012-01-03'</code></td>
900-</tr>
901-<tr>
902-<td><code>h</code></td>
903-<td>Place holder of the hour part of a date/time value. The hour is displayed as a simple number, without adding a leading zero.</td>
904-<td><code>'h:mm'</code>:<br />
905-0.25 --&gt; <code>'6:00'</code></td>
906-</tr>
907-<tr>
908-<td><code>hh</code></td>
909-<td>Place holder of the hour part of a date/time value. The hour is displayed with a leading zero if the hour is less than 10.</td>
910-<td><code>'hh:mm'</code>:<br />
911-0.25 --&gt; <code>'06:00'</code></td>
912-</tr>
913-<tr>
914-<td><code>[hh]</code>, or <code>[h]</code></td>
915-<td>Displays elapsed time such that the hour part can become greater than 23</td>
916-<td><code>'[h]:mm'</code>:<br />
917-1.25 --&gt; <code>'30:00'</code></td>
918-</tr>
919-<tr>
920-<td><code>m</code></td>
921-<td>Place holder of the minutes part of a date/time value. The minutes are shown as a simple number without adding a leading zero. Note that if the <code>m</code> codes are surrounded by date symbols (<code>y</code>, <code>d</code>) then they are interpreted as "month".</td>
922-<td><code>'h:m'</code>:<br />
923-0.25 --&gt; <code>'6:0'</code></td>
924-</tr>
925-<tr>
926-<td><code>mm</code></td>
927-<td>Place holder of the minutes part of a date/time value. Single-digit minutes are displayed with a leading zero. Note that if the <code>mm</code> code is surrounded by date symbols (<code>y</code>, <code>d</code>) then it is interpreted as "month".</td>
928-<td><code>'h:mm'</code>:<br />
929-0.25 --&gt; <code>'6:00'</code></td>
930-</tr>
931-<tr>
932-<td><code>[mm]</code>, or <code>[m]</code></td>
933-<td>Displays elapsed time such that the minute part can become greater than 59</td>
934-<td><code>'[mm]:ss'</code>:<br />
935-1.25 --&gt; <code>'1800:00'</code></td>
936-</tr>
937-<tr>
938-<td><code>s</code></td>
939-<td>Place holder of the seconds part of a date/time value. The seconds are displayed as a simple number, without adding a leading zero.</td>
940-<td><code>'hh:mm:s'</code>:<br />
941-0.25 --&gt; <code>'06:00:0'</code></td>
942-</tr>
943-<tr>
944-<td><code>ss</code></td>
945-<td>Place holder of the seconds part of a date/time value. Single-digit seconds are displayed with a leading zero.</td>
946-<td><code>'hh:mm:ss'</code>:<br />
947-0.25 --&gt; <code>'06:00:00'</code></td>
948-</tr>
949-<tr>
950-<td><code>[ss]</code>, or <code>[s]</code></td>
951-<td>Displays elapsed time such that the seconds part can become greater than 59</td>
952-<td><code>'[ss]'</code>:<br />
953-1.25 --&gt; <code>'108000'</code></td>
954-</tr>
955-<tr>
956-<td><code>AM/PM</code>, <code>am/pm</code>, <code>A/P</code>, or <code>a/p</code></td>
957-<td>Displays the time in the 12-hour format.</td>
958-<td><code>'hh:mm:ss AM/PM'</code>:<br />
959-0.25 --&gt; <code>'6:00:00 AM'</code></td>
960-</tr>
961-<tr>
962-<td><code>"</code></td>
963-<td>The text enclosed by quotation marks is inserted into the formatted strings literally.</td>
964-<td><code>'yyyy"/"mm"/"dd'</code>:<br />
965-Jan 3, 2012 --&gt; <code>'2012/01/03'</code> (i.e. the <code>/</code> is not replaced by the <code>DateSeparator</code> of the workbook).</td>
966-</tr>
967-<tr>
968-<td><code>\</code></td>
969-<td>The next character of the format string appears in the result string literally. The <code>\</code> itself does not show up.</td>
970-<td><code>'yyyy\/mm\/dd'</code>:<br />
971-Jan 3, 2012 --&gt; <code>'2012/01/03'</code></td>
972-</tr>
973-<tr>
974-<td><code>;</code></td>
975-<td>A format string can contain up to three sections separated by the semicolon. The first section is used for positive numbers, the second section for negative numbers, and the third section for zero numbers. If the third section is missing then a zero value is formatted as specified in the first section. If the second section is missing as well then all values are formatted according to the first section.</td>
976-<td><code>'"#,##0"$"';-#,##0"$";"-"'</code>:<br />
977-1200 --&gt; <code>'1,200$'</code><br />
978--1200 --&gt; <code>'1,200$'</code><br />
979-0 --&gt; <code>'-'</code></td>
980-</tr>
981-<tr>
982-<td><code>(</code>, and <code>)</code></td>
983-<td>Sometimes used for currency values to indicate negative numbers, instead of minus sign</td>
984-<td><code>'#,##0"$";(#,##0)"$"'</code>:<br />
985--1200 --&gt; <code>'(1200)$'</code></td>
986-</tr>
987-<tr>
988-<td><code>[red]</code></td>
989-<td>The formatted string is displayed in the specified color. Instead of <code>[red]</code>, you can use accordingly <code>[black]</code>, <code>[white]</code>, <code>[green]</code>, <code>[blue]</code>, <code>[magenta]</code>, <code>[yellow]</code>, or <code>[cyan]</code>. Often used to highlight negative currency values.</td>
990-<td><code>'"$" #,##0.00;[red]("$" #,##0.00)'</code>:<br />
991--1200 --&gt; '<span style="color:#FF0000"><code>($ 1200.00)</code></span>'</td>
992-</tr>
993-<tr>
994-<td></td>
995-<td></td>
996-<td></td>
997-</tr>
998-</tbody>
999-</table>
1000-
1001-##### A note on Excel dates
1002-
1003-There is a discrepancy between FPSpreadsheet and Excel presentation of dates: Excel incorrectly assumes that the year 1900 was a leap year and thus allows for the date Febr 29 1900. FPSpreadsheet does the date calculation correctly. As consequence, dates before March 1 1900 are off by one! BTW, FPSpreadsheet handles this issue in the same way as LibreOffice Calc.
1004-
1005-#### Colors
1006-
1007-FPSpreadsheet supports colors for text, cell background, and cell borders. The basic EGA colors are declared in unit *fpstypes* as constants:
1008-
1009-<figure>
1010-<img src="DefaultPalette.png" title="Predefined colors" />
1011-<figcaption>Predefined colors</figcaption>
1012-</figure>
1013-
1014-``` pascal
1015-type
1016- TsColor = DWORD;
1017-
1018-const
1019- scBlack = $00000000;
1020- scWhite = $00FFFFFF;
1021- scRed = $000000FF;
1022- scGreen = $0000FF00;
1023- scBlue = $00FF0000;
1024- scYellow = $0000FFFF;
1025- scMagenta = $00FF00FF;
1026- scCyan = $00FFFF00;
1027- scDarkRed = $00000080;
1028- scDarkGreen = $00008000;
1029- scDarkBlue = $00800000;
1030- scOlive = $00008080;
1031- scPurple = $00800080;
1032- scTeal = $00808000;
1033- scSilver = $00C0C0C0;
1034- scGray = $00808080;
1035- scGrey = scGray; // redefine to allow different spelling
1036-
1037- // Identifier for undefined color
1038- scNotDefined = $40000000;
1039-
1040- // Identifier for transparent color
1041- scTransparent = $20000000;
1042-```
1043-
1044-The `TsColor` represents the **rgb value** of a color, a single byte being used for the red, green, and blue components. The resulting number is in little endian notation, i.e. the red value comes first in memory: `$00BBGGRR`. (This is directly compatible with the color values as defined in the *graphics* unit.)
1045-
1046-The high order byte is usually zero but is used internally to identify special color values, such as for undefined or transparent colors.
1047-
1048-> **Note:** In older versions of the library colors were defined as indexes into a color palette. **THIS IS NO LONGER WORKING.**
1049-
1050-Unit *fpsutils* contains some useful functions for **modification of colors**:
1051-
1052-- `function GetColorName(AColor: TsColor): String;`\
1053- returns the name of the colors defined above, or a string showing the rgb components for other colors.
1054-- `function HighContrastColor(AColor: TsColor): TsColor;`\
1055- returns `scBlack` for a "bright", `scWhite` for a "dark" input color.
1056-- `function TintedColor(AColor: TsColor; tint: Double): TsColor;`\
1057- brightens or darkens a color by applying a factor `tint = -1..+1`, where `-1` means "100% darken", `+1` means "100% brighten", and `0` means "no change". The hue of the color is preserved.
1058-
1059-#### Cell background
1060-
1061-The cell background can be filled by predefined patterns which are identified by the record `TsFillPattern`:
1062-
1063-``` pascal
1064-type
1065- TsFillPattern = record
1066- Style: TsFillStyle; // fill style pattern as defined below
1067- FgColor: TsColor; // forground color of the fill pattern
1068- BgColor: TsColor; // background color of the fill pattern
1069- end;
1070-
1071- TsFillStyle = (fsNoFill, fsSolidFill, fsGray75, fsGray50, fsGray25, fsGray12, fsGray6,
1072- fsStripeHor, fsStripeVert, fsStripeDiagUp, fsStripeDiagDown,
1073- fsThinStripeHor, fsThinStripeVert, fsThinStripeDiagUp, fsThinStripeDiagDown,
1074- fsHatchDiag, fsThinHatchDiag, fsThickHatchDiag, fsThinHatchHor);
1075-```
1076-
1077-- Use the worksheet method `WriteBackground` to assign a fill pattern to a specific cell. Besides the cell address, this method requires the type of the fill pattern (`TsFillStyle`), and the foreground and background colors as specified by their `TsColor` values.
1078-- The fill pattern of a particular cell can be retrieved by calling the workbook method `ReadBackground`.
1079-- The simplified method `WriteBackgroundColor` can be used to achieve a uniform background color.
1080-- **Limitations:**
1081- - OpenDocument files support only uniform fills. The background color is a mixture of the foreground and background rgb components in a ratio defined by the fill pattern.
1082- - BIFF2 files support only a 12.5% black-and-white shaded pattern.
1083-
1084-``` pascal
1085-type
1086- TsWorksheet = class
1087- public
1088- function WriteBackground(ARow, ACol: Cardinal; AStyle: TsFillStyle; APatternColor, ABackgroundColor: TsColor): PCell; overload;
1089- procedure WriteBackground(ACell: PCell; AStyle: TsFillStyle; APatternColor, ABackgroundColor: TsColor); overload;
1090-
1091- function WriteBackgroundColor(ARow, ACol: Cardinal; AColor: TsColor): PCell; overload;
1092- procedure WriteBackgroundColor(ACell: PCell; AColor: TsColor); overload;
1093-
1094- function ReadBackground(ACell: PCell): TsFillPattern;
1095- function ReadBackgroundColor(ACell: PCell): TsColor; overload;
1096- // ...
1097- end;
1098-
1099-var
1100- cell: PCell;
1101-...
1102- // Example 1: Assign a pattern of thin, horizontal, yellow stripes on a blue background to empty cell A1 (row 0, column 0)
1103- MyWorksheet.WriteBackground(0, 0, fsThinStripeHor, scYellow, scBlue);
1104-
1105- // Example 2: Uniform gray background color of cell B1 (row 0, column 1) containing the number 3.14
1106- cell := MyWorksheet.WriteNumber(0, 1, 3.14);
1107- MyWorksheet.WriteBackgroundColor(cell, clSilver);
1108-```
1109-
1110-#### Cell borders
1111-
1112-Cells can be emphasized by drawing border lines along their edges or diagonal lines. There are four borders plus two diagonals enumerated in the data type `TsCellBorder`:
1113-
1114-``` pascal
1115-type
1116- TsCellBorder = (cbNorth, cbWest, cbEast, cbSouth, cbDiagUp, cbDiagDown);
1117- TsCellBorders = set of TsCellBorder;
1118-```
1119-
1120-In order to show a border line add the corresponding border to the cell's set `Borders` (type `TsCellBorders`, see above). In this way, each cell edge can be handled separately. Use the worksheet method `WriteBorders` for this purpose. This example adds top and bottom borders to the edges A1 and B1:
1121-
1122-``` pascal
1123- MyWorksheet.WriteBorders(0, 0, [cbNorth, cbSouth]); // A1: row 0, column 0
1124- MyWorksheet.WriteBorders(0, 1, [cbNorth, cbSourth]); // B1: row 0, column 1
1125-```
1126-
1127-Lines usually are drawn as thin, solid, black lines. But it is possible to modify **line style** and **color** of each line. For this purpose, the cell provides an array of `TsCellBorderStyle` records:
1128-
1129-``` pascal
1130-type
1131- TsLineStyle = (lsThin, lsMedium, lsDashed, lsDotted, lsThick, lsDouble, lsHair,
1132- lsMediumDash, lsDashDot, lsMediumDashDot, lsDashDotDot, lsMediumDashDotDot, lsSlantDashDot);
1133-
1134- TsCellBorderStyle = record
1135- LineStyle: TsLineStyle;
1136- Color: TsColor;
1137- end;
1138-
1139- TsCellBorderStyles = array[TsCellBorder] of TsCellBorderStyle;
1140-
1141- TsWorksheet = class
1142- public
1143- function WriteBorderStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; AStyle: TsCellBorderStyle): PCell; overload;
1144- procedure WriteBorderStyle(ACell: PCell; ABorder: TsCellBorder; AStyle: TsCellBorderStyle); overload;
1145-
1146- function WriteBorderStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; ALineStyle: TsLineStyle; AColor: TsColor): PCell; overload;
1147- procedure WriteBorderStyle(ACell: PCell; ABorder: TsCellBorder; ALineStyle: TsLineStyle; AColor: TsColor); overload;
1148-
1149- function WriteBorderColor(ARow, ACol: Cardinal; ABorder: TsCellBorder; AColor: TsColor): PCell; overload;
1150- procedure WriteBorderColor(ACell: PCell; ABorder: TsCellBorder; AColor: TsColor): PCell; overload;
1151-
1152- function WriteBorderLineStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; ALineStyle: TsLineStyle): PCell; overload;
1153- procedure WriteBorderLineStyle(ACell: PCell; ABorder: TsCellBorder; ALineStyle: TsLineStyle): PCell; overload;
1154-
1155- function WriteBorderStyles(ARow, ACol: Cardinal; const AStyles: TsCellBorderStyles): PCell; overload;
1156- procedure WriteBorderStyles(ACell: PCell; const AStyles: TsCellBorderStyles); overload;
1157-
1158- function WriteBorders(ARow, ACol: Cardinal; ABorders: TsCellBorders): PCell; overload
1159- procedure WriteBorders(ACell: PCell; ABorders: TsCellBorders); overload
1160-
1161- function ReadCellBorders(ACell: PCell): TsCellBorders;
1162- function ReadCellBorderStyle(ACell: PCell; ABorder: TsCellBorder): TsCellBorderStyle;
1163- function ReadCellBorderStyles(ACell: PCell): TsCellBorderStyles;
1164- ...
1165- end;
1166-```
1167-
1168-The style of a given cell border can be specified by the following methods provided by the worksheet:
1169-
1170-- **WriteBorderStyle** assigns a cell border style record to one border of the cell. There are two overloaded versions of this method: one takes an entire `TsCellBorderStyle` record, the other one takes the individual record elements.
1171-- **WriteBorderColor** changes the color of a given border without affecting the line style of this border.
1172-- **WriteBorderLineStyle** sets the line style of the border only, but leaves the color unchanged.
1173-- **WriteBorderStyles** sets the border style of all borders of a given cell at once. Useful for copying border styles from one cell to other cells.
1174-
1175-This example adds a thin black border to the top, and a thick blue border to the bottom of cells A1 and B1:
1176-
1177-``` pascal
1178-var
1179- cellA1, cellB1: PCell;
1180-...
1181- cellA1 := MyWorksheet.WriteBorders(0, 0, [cbNorth, cbSouth]); // cell A1: row 0, column 0
1182- MyWorksheet.WriteBorderStyle(cellA1, cbNorth, lsThin, scBlack);
1183- MyWorksheet.WriteBorderStyle(cellA1, cbSouth, lsThick, scBlue);
1184-
1185- cellB1 := MyWorksheet.WriteBorders(0, 1, [cbNorth, cbSouth]); // cell B1: row 0, column 1
1186- MyWorksheet.WriteBorderStyles(cellB1, cellA1^.BorderStyles); // copy all border styles from cell A1 to B1
1187-```
1188-
1189-> **Note:** Diagonal lines are not supported by *sfExcel2* and *sfExcel5* - they are just omitted. *sfExcel8* and *sfOOXML* use the same linestyle and color for both diagonals; when writing the border style of the diagonal-up line is assumed to be valid also for the diagonal-down line. Some writers do not support all the line styles of the `TsLineStyle` enumeration. In this case, appropriate replacement line styles are used.
1190-
1191-#### Fonts
1192-
1193-The cell text can displayed in various fonts. For this purpose, the workbook provides a list of `TsFont` items:
1194-
1195-``` pascal
1196-type
1197- TsFont = class
1198- FontName: String;
1199- Size: Single;
1200- Style: TsFontStyles;
1201- Color: TsColor;
1202- Position: TsFontPosition;
1203- end;
1204-```
1205-
1206-- The **FontName** corresponds to the name of the font as used by the operational system. In Windows, an example would be "Times New Roman".
1207-- The **FontSize** is given in "points", i.e. units 1/72 inch which are commonly used in Office applications.
1208-- The **FontStyle** is a set of the items `fssBold`, `fssItalic`, `fssStrikeout`, and `fssUnderline` which form the enumeration type `TsFontStyle`. The "normal" font corresponds to an empty set.
1209-- The **Color** determines the foreground color of the text characters given in rgb presentation as discussed above.
1210-- The **Position** is either `fpNormal`, `fpSuperscript`, or `fpSubscript` and indicates whether the font size should be decreased by about 1/3 and the characters should be displaced up (superscript) or down (subscript).
1211-
1212-Every cell is provided with an **index into the font list**.
1213-
1214-In order to assign a particular font to a cell, use one of the following methods of `TsSpreadsheet`:
1215-
1216-``` pascal
1217-type
1218- TsSpreadsheet = class
1219- public
1220- function WriteFont(ARow, ACol: Cardinal; const AFontName: String;
1221- AFontSize: Single; AFontStyle: TsFontStyles; AFontColor: TsColor): Integer; overload;
1222- procedure WriteFont(ARow, ACol: Cardinal; AFontIndex: Integer); overload;
1223- function WriteFontColor(ARow, ACol: Cardinal; AFontColor: TsColor): Integer;
1224- function WriteFontSize(ARow, ACol: Cardinal; ASize: Integer): Integer;
1225- function WriteFontStyle(ARow, ACol: Cardinal; AStyle: TsFontStyles): Integer;
1226- // plus: overloaded versions accepting a pointer to a cell record instead of the row and column index as parameter
1227- // ...
1228- end;
1229-```
1230-
1231-- **WriteFont** assigns a font to the cell. If the font does not yet exist in the font list a new entry is created. The function returns the index of the font in the font list. In addition, there is an overloaded version which only takes the font index as a parameter.
1232-- **WriteFontColor** replaces the color of the font that is currently assigned to the cell by a new one. Again, a new font list item is created if the font with the new color does not yet exist. The function returns the index of the font in the list.
1233-- **WriteFontSize** replaces the size of the currently used font of the cell.
1234-- **WriteFontStyle** replaces the style (normal, bold, italic, etc.) of the currently used cell font.
1235-
1236-The workbook's font list contains at least one item which is the **default font** for cells with unmodified fonts. By default, this is 10-point "Arial". Use the workbook method `SetDefaultFont` to assign a different font to the first list item.
1237-
1238-The font at a given index of the font list can be looked up by calling the workbook function `GetFont`. The count of available fonts is returned by `GetFontCount`.
1239-
1240-Here is an **example** which decreases the size of all 10-point "Arial" fonts to 9-point:
1241-
1242-``` pascal
1243-var
1244- i: Integer;
1245- font: TsFont;
1246-begin
1247- for i := 0 to MyWorkbook.GetFontCount-1 do
1248- begin
1249- font := MyWorkbook.GetFont(i);
1250- if (font.FontName = 'Arial') and (font.Size = 10.0) then
1251- font.Size := 9.0;
1252- end;
1253-end;
1254-```
1255-
1256-#### Rich-text formatting
1257-
1258-In addition to using a specific font for each cell it is also possible to specify particular font attributes for individual characters or groups of characters in each cell text. Following the Excel notation, we call this feature **Rich-text formatting** (although is has nothing in common with the "rich-text" file format).
1259-
1260-For this purpose, unit *fpstypes* declares the type `TsRichTextParams` which is an array of `TsRichTextParam` records:
1261-
1262-``` pascal
1263-type
1264- TsRichTextParam = record
1265- FontIndex: Integer;
1266- FirstIndex: Integer;
1267- end;
1268-
1269- TsRichTextParams = array of TsRichTextParam;
1270-```
1271-
1272-`FontIndex` refers to the index of the font in the workbook's FontList to be used for formatting of the characters beginning at the index `FirstIndex`. Being a string character index the `FirstIndex` is 1-based.
1273-
1274-There are two ways to add "rich-text" formatting to a cell text:
1275-
1276-- Embed corresponding HTML format codes into the cell text. This can be done using the method `WriteTextAsHTML` of the worksheet. In order to add the text "Area (m<sup>2</sup>)" to cell A1, pass the following HTML-coded string to this function
1277-
1278-``` pascal
1279- MyWorksheet.WriteTextAsHTML(0, 0, 'Area (m<sup>2</sup>');
1280-```
1281-
1282-- Alternatively, the standard text writing method, `WriteText` can be called with an additional parameter specifiying the rich-text formatting parameters to be used directly:
1283-
1284-``` pascal
1285-var
1286- richTextParams: TsRichTextParams;
1287- fnt: TsFont;
1288- cell: PCell;
1289-begin
1290- SetLength(rtp, 2);
1291- cell := MyWorksheet.GetFont(0, 0);
1292- fnt := MyWorksheet.ReadCellFont(cell);
1293- richTextParams[0].FirstIndex := 8; // The superscript groups begins with "2" which is the (1-based) character #8 of the cell text.
1294- richTextParams[0].FontIndex := MyWorkbook.AddFont(fnt.FontName, fnt.Size, fnt.Style, fnt.Color, fpSuperscript);
1295- richTextParams[1].FirstIndex := 9; // Normal font again beginning with character #9.
1296- richTextParams[1].FontIndex := MyWorksheet.ReadCellFontIndex(0, 0);
1297- MyWorksheet.WriteUTF8Text(cell, 'Area (m2)', richTextParams);
1298-end;
1299-```
1300-
1301-Use the worksheet method `DeleteRichTextParams` to remove rich-text formatting from a previously formatted cell.
1302-
1303-> **Note:** If the cell is supposed to have a font different from the worksheet's default font then this font must be written to the cell **before** writing the rich-text formatted text. Otherwise the font in the unformatted regions will not be up-to-date.
1304-
1305-#### Text rotation
1306-
1307-Usually text is displayed in the cells horizontally. However, it is also possible to rotate it by 90 degrees in clockwise or counterclockwise directions. In addition, there is also an option to stack horizontal characters vertically above each other.
1308-
1309-If you need this feature use the worksheet method `WriteTextRotation` and specify the text direction by an element of the enumeration type `TsTextRotation`:
1310-
1311-``` pascal
1312-type
1313- TsTextRotation = (trHorizontal, rt90DegreeClockwiseRotation,
1314- rt90DegreeCounterClockwiseRotation, rtStacked);
1315-
1316- TsWorksheet = class
1317- public
1318- function WriteTextRotation(ARow, ACol: Cardinal; ARotation: TsTextRotation): PCell; overload;
1319- procedure WriteTextRotation(ACell: PCell; ARotation: TsTextRotation); overload;
1320-
1321- function ReadTextRotation(ACell: PCell): TsTextRotation;
1322- // ...
1323- end;
1324-
1325- // example for counter-clockwise rotated text in cell A1:
1326- WriteTextRotation(0, 0, rt90DegreeCounterClockwiseRotation);
1327-```
1328-
1329-> **Warning:** Finer degrees of rotation which may be supported by some spreadsheet file formats are ignored.
1330-
1331-#### Text alignment
1332-
1333-By default, cell texts are aligned to the left and bottom edges of the cell, except for numbers which are right-aligned. This behavior can be changed by using the worksheet methods `WriteHorAlignment` and `WriteVertAlignment`:
1334-
1335-``` pascal
1336-type
1337- TsHorAlignment = (haDefault, haLeft, haCenter, haRight, haJustified, haDistributed, haFilled);
1338- TsVertAlignment = (vaDefault, vaTop, vaCenter, vaBottom);
1339-
1340- TsWorksheet = class
1341- public
1342- function WriteHorAlignment(ARow, ACol: Cardinal; AValue: TsHorAlignment): PCell; overload;
1343- procedure WriteHorAlignment(ACell: PCell; AValue: TsHorAlignment); overload;
1344- function ReadHorAlignment(ACell: PCell): TsHorAlignment;
1345-
1346- function WriteVertAlignment(ARow, ACol: Cardinal; AValue: TsVertAlignment): PCell; overload;
1347- procedure WriteVertAlignment(ACell: PCell; AValue: TsVertAlignment); overload;
1348- function ReadVertAlignment(ACell: PCell): TsVertAlignment;
1349- // ...
1350- end;
1351-
1352- // Example: Center the text in cell A1 both horizontally and vertically
1353- MyWorksheet.WriteHorAlignment(0, 0, haCenter);
1354- MyWorksheet.WriteVertAlignment(0, 0, vaCenter);
1355-```
1356-
1357-Explanation of special horizontal alignments:
1358-
1359-- `haDistributed`: The cell text is word-wrapped and its spaces are expanded so that the entire width of the cell is occupied. The text is both left- and right-justified.
1360-- `haJustified`: like `haDistributed`, expect for the last line which remains left-justified.
1361-- `haFilled`: the text is repeated to fill the entire cell.
1362-
1363-#### Word wrap
1364-
1365-Text which is longer than the width of a cell can wrap into several lines by calling the method `WriteWordwrap` of the spreadsheet:
1366-
1367-``` pascal
1368-type
1369- TsWorksheet = class
1370- public
1371- function WriteWordwrap(ARow, ACol: Cardinal; AValue: Boolean): PCell; overload;
1372- procedure WriteWordwrap(ACell: PCell; AValue: Boolean); overload;
1373- function ReadWordwrap(ACell: PCell): Boolean;
1374- //...
1375- end;
1376-
1377- // Example: activate wordwrap in cell A1
1378- MyWorksheet.WriteWordwrap(0, 0, true);
1379-```
1380-
1381-#### Merged cells
1382-
1383-Like the Office applications, FPSpreadsheet supports also to feature of merging cells to a single large cell which is often used as a common header above simlar columns. Simply call `MergeCells` and pass a parameter to specify the cell range to be merged, either an Excel range string (such as `A1:D5`), or the first and last rows and columns:
1384-
1385-``` pascal
1386- MyWorksheet.MergeCells('A1:D5');
1387- // or: MyWorksheet.MergeCells(0, 0, 4, 3); // first row, first column, last row, last column
1388-```
1389-
1390-The content and format displayed for a merged range is taken from the upper left corner of the range, cell `A1` in above example. This cell is called the `MergeBase` in the library. Except for this corner cell, there must not be any other cells in the range. If there are their contents and format will be hidden.
1391-
1392-In order to break up a merged range back up into individual cells, use the command `Unmerge` and pass any cell that is within the merged range:
1393-
1394-``` pascal
1395- MyWorksheet.UnmergeCells('B1');
1396- // or: MyWorksheet.UnmergeCells(0, 1); // row, column of any cell within the range
1397-```
1398-
1399-Merged cells can be read from/written to all file formats except for `sfCSV`, `sfExcel2` and `sfExcel5` which do not support this feature natively.
1400-
1401-The information which cells are merged is stored in an internal list. Unlike in earlier versions it is no longer possible to access the `MergeBase` from the cell directly. Use the following functions to extract information on merged cells:
1402-
1403-``` pascal
1404-var
1405- cell, base: PCell;
1406- r1,c1,r2,c2: Cardinal;
1407-...
1408- cell := MyWorksheet.FindCell('B1');
1409- if MyWorksheet.IsMerged(cell) then
1410- begin
1411- WriteLn('Cell B1 is merged.');
1412-
1413- MyWorksheet.FindMergedRange(cell, r1, c1, r2, c2);
1414- WriteLn('The merged range is ' + GetCellRangeString(r1, c1, r2, c2));
1415-
1416- base := MyWorksheet.FindMergeBase(cell);
1417- WriteLn('The merge base is cell ' + GetCellString(base^.Row, base^.Col));
1418- end;
1419-```
1420-
1421-#### Cell protection
1422-
1423-This is described in a separate section below.
1424-
1425-#### Miscellaneous
1426-
1427-##### Disable printing of specific cells
1428-
1429-Specific cells can be disabled from printing:
1430-
1431-``` pascal
1432-type
1433- TsWorksheet = class
1434- public
1435- function WriteDoNotPrintCell(ARow, ACol: Cardinal; AValue: boolean): PCell; overload;
1436- procedure WriteDoNotPrintCell(ACell: PCell; AValue: Boolean); overload;
1437- function ReadDoNotPrintCell(ACell: PCell): Boolean;
1438-```
1439-
1440-### Additional data
1441-
1442-#### Cell comments
1443-
1444-Comments can be attached to any cell by calling
1445-
1446-``` pascal
1447- MyWorksheet.WriteComment(0, 0, 'This is a comment for cell A1');
1448-```
1449-
1450-They are stored in an internal list of the worksheet. Use the corresponding worksheet methods to access comments:
1451-
1452-- If you want to know whether a particular cell contains a comment call the worksheet method `HasComment(cell)`.
1453-- For retrieving a cell comment use the method `ReadComment(cell)`, or its overloaded companion `ReadComment(ARow, ACol)`.
1454-- The total number of comments can be retrieved from `worksheet.Comments.Count`.
1455-
1456-#### Hyperlinks
1457-
1458-Hyperlinks can be attached to cells in order to link cells to other documents or other cells in the same workbook. The general syntax for creating hyperlinks is
1459-
1460-``` pascal
1461- procedure TWorksheet.WriteHyperlink(ARow, ACol: Cardinal; ATarget: String; ATooltip: String = '');
1462-```
1463-
1464-- The hyperlink target, passed as parameter `ATarget`, must be a fully qualified [URI (Uniform resource identifier)](http://en.wikipedia.org/wiki/Uniform_Resource_Identifier) consisting of a protocol phrase (e.g., [`http://`](http://), [`file:///`](file:///), `mailto:`, etc.) followed by specific information such as web URL, filename, or e-mail address and an optional bookmark identification separated by the character `'#'`. An exception are internal hyperlinks which enable to jump to a cell in the current workbook; they consist of the optional worksheet name and the cell address separated by the character `'!'`.
1465-- The optional `Tooltip` parameter is evaluated by Excel to display it in a hint window if the mouse if above the hyperlink.
1466-
1467-> **Note:** Hyperlinks can be added to empty cells or to cells with content. In the latter case, the displayed content is not changed by the hyperlink; in the former case the cell is converted to a label cell showing the hyperlink target. Be aware that OpenOffice/LibreOffice only does accept hyperlinks with non-text cells.
1468-
1469-**Examples:**
1470-
1471-``` pascal
1472- // Open the web site www.google.com
1473- MyWorksheet.WriteText(0, 0, 'Open google');
1474- MyWorksheet.WriteHyperlink(0, 0, 'http://www.google.com');
1475-
1476- // Open the local file with the absolute path "C:\readme.txt" (assuming Windows)
1477- MyWorksheet.WriteHyperlink(1, 0, 'file:///c:\readme.txt');
1478-
1479- // Open the mail client to send a mail
1480- MyWorksheet.WriteText('Send mail');
1481- MyWorksheet.WriteHyperlink(3, 0, 'mailto:somebody@gmail.com?subject=Test');
1482-
1483- // Jump to a particular cell
1484- MyWorksheet.WriteText(5, 0, 'Jump to cell A10 on sheet2');
1485- MyWorksheet.WriteHyperlink(5, 0, '#Sheet2!A10');
1486-
1487- // Jump to cell A10 on the current sheet and display a popup hint
1488- MyWorksheet.WriteHyperlink(5, 0, '#A10', 'Go to cell A10');
1489-```
1490-
1491-> **Note:** FPSpreadsheet does not "follow" the links, it only provides a mechanism to get access to the link data. TsWorksheetGrid from the *laz_fpspreadsheet_visual* package, however, fires the event `OnClickHyperlink` if a cell with an external hyperlink is clicked for fractions of a second. In the corresponding event handler, you can, for example, load a target spreadsheet, or open a web browser to display the linked web site. If the link is an internal link to another cell within the same workbook then the grid jumps to the related cell.
1492-
1493-#### Images
1494-
1495-FPSpreadsheet supports embedding of images in worksheets. Use one of the worksheet methods `WriteImage()` to add an image to the worksheet:
1496-
1497-``` pascal
1498- MyWorksheet.WriteImage(row, col, filename, offsetX, offsetY, scaleX, scaleY);
1499- MyWorksheet.WriteImage(row, col, stream, offsetX, offsetY, scaleX, scaleY);
1500- MyWorksheet.WriteImage(row, col, imageindex, offsetX, offsetY, scaleX, scaleY);
1501-```
1502-
1503-The upper/left corner of the image is placed at the upper/left corner of the cell in the specified row and column. The floating point parameters `offsetX`, `offsetY`, `scaleX` and `scaleY` are optional: they define an offset of this image anchor point from the cell corner and a magnification factor. The path to the image file is given as parameter `filename`. Alternatively, overloaded versions can be used which accept a stream in place of the file name or an image index in the workbook's EmbeddedObj list - use `MyWorkbook.FindEmbeddedObj(filename)` to get this index for a previously loaded image file.
1504-
1505-Note that FPSpreadsheet needs to know the image type for successfull picture import. Currently, the types *png*, *jpg*, *tiff*, *bmp*, *gif*, *svg*, *wmf*, *emf*, and *pcx* are supported (Excel2007 cannot read imported *svg* and *pcx* images). Other formats can be registered by writing a function which determines the image size and pixel density, and by registering the new format using the procedure `RegisterImageType` - see unit *fpsImages* for examples:
1506-
1507-``` pascal
1508-type
1509- TsImageType = integer;
1510- TGetImageSizeFunc = function (AStream: TStream; out AWidth, AHeight: DWord; out dpiX, dpiY: Double): Boolean;
1511-
1512-function RegisterImageType(AMimeType, AExtension: String; AGetImageSize: TGetImageSizeFunc): TsImageType;
1513-```
1514-
1515-Due to differences in row height and column width calculation between FPSpreadsheet and Office applications it is not possible to position images correctly. If exact image positions are important you should follow these rules:
1516-
1517-- Predefine the widths of all columns at least up to the one containing the right edge of the image.
1518-- Predefine the heights of all rows at least up to the one containing the lower edge of the image.
1519-- If the workbook is to be saved in OpenDocument format add the image after changing column widths and row heights because ods anchors the image to the sheet, not to the cell (like Excel and FPSpreadsheet).
1520-- If the exact size of the image is important make sure that it fits into a single cell.
1521-
1522-### Sorting
1523-
1524-Cells in a worksheet can be sorted for a variety of criteria by calling the `Sort` method of the worksheet. This method takes a `TsSortParams` record and the edges of the cell rectangle to be sorted as parameters; in an overloaded version, the cell rectangle can also be specified by means of an Excel-type range string (e.g. `'A1:G10'`):
1525-
1526-``` pascal
1527-type
1528- TsWorksheet = class
1529- // ...
1530- procedure Sort(const ASortParams: TsSortParams;
1531- ARowFrom, AColFrom, ARowTo, AColTo: Cardinal); overload;
1532- procedure Sort(ASortParams: TsSortParams; ARange: String); overload;
1533- // ...
1534- end;
1535-```
1536-
1537-The sorting criteria are defined by a record of type `TsSortParams`:
1538-
1539-``` pascal
1540-type
1541- TsSortParams = record
1542- SortByCols: Boolean;
1543- Priority: TsSortPriority; // spNumAlpha ("Numbers first"), or spAlphaNum ("Text first")
1544- Keys: TsSortKeys;
1545- end;
1546-
1547- TsSortKey = record
1548- ColRowIndex: Integer;
1549- Options: TsSortOptions; // set of [spDescending, spCaseInsensitive]
1550- end;
1551-```
1552-
1553-- The boolean value `SortByCols` determines wether sorting occurs along columns (`true`) or rows (`false`). The `ColRowIndex` specified in the sorting keys, accordingly, corresponds to a column or row index, respectively (see below).
1554-- `Priority` determines in mixed content cell ranges whether an ascending sort puts numerical values in front of text values or not. Empty cells are always moved to the end of the sorted column or row. In Excel, the priority is "numbers first" (`spNumAlpha`).
1555-- The array `Keys` specifies multiple sorting parameters. They consist of the index of the column or row to be sorted (`ColRowIndex`) and a set of `Options` for sorting direction (`spoDescending`) and character case (`spCaseInsensitive`). If `Options` is empty, cell comparison is case-sensitive, and cells are arranged in ascending order. If two cells are found to be "equal" on the basis of the first key (`sortParams.Keys[0]`) comparison proceeds with the next conditions in the `Keys` array until a difference is found or all conditions are used up.
1556-
1557-`InitSortParams` is a handy utility to initialize the sorting parameters:
1558-
1559-``` pascal
1560-function InitSortParams(ASortByCols: Boolean = true; ANumSortKeys: Integer = 1;
1561- ASortPriority: TsSortPriority = spNumAlpha): TsSortParams;
1562-```
1563-
1564-The next code fragment shows a typical sorting call:
1565-
1566-``` pascal
1567-var
1568- sortParams: TsSortParams;
1569-begin
1570- sortParams := InitSortParams(true, 2); // sorting along columns, 2 sorting keys
1571-
1572- // primary sorting key: column 3, ascending, case-insensitive
1573- sortParams.Keys[0].ColRowIndex := 3;
1574- sortParams.Keys[0].Options := [ssoCaseInsensitive];
1575-
1576- // secondary sorting key: colum 1, descending
1577- sortParams.Keys[1].ColRowIndex := 1;
1578- sortParams.Keys[1].Options := [ssoDescending];
1579-
1580- // The sorted block extends between cells A1 (row=0, col=0) and F10 (row=9, col=5)
1581- MyWorksheet.Sort(sortParams, 0, 0, 9, 5);
1582- // or: MyWorksheet.Sort(sortParams, 'A1:F10');
1583-end;
1584-```
1585-
1586-### Searching and replacing
1587-
1588-Unit *fpsSearch* implements a **search engine** which can be used to look for specific cell content within a workbook, or to replace the found cell content by some other string.
1589-
1590-**Example:**
1591-
1592-``` pascal
1593-uses
1594- fpsTypes, fpSpreadsheet, fpsUtils, fpsSearch, fpsAllFormats;
1595-var
1596- MyWorkbook: TsWorkbook;
1597- foundWorksheet: TsWorksheet;
1598- foundRow, foundCol: Cardinal;
1599- MySearchParams: TsSearchParams;
1600-begin
1601- MyWorkbook := TsWorkbook.Create;
1602- try
1603- MyWorkbook.ReadFromFile(AFileName);
1604-
1605- // Specify search criteria
1606- MySearchParams.SearchText := 'Hallo';
1607- MySearchParams.Options := [soEntireDocument];
1608- MySearchParams.Within := swWorkbook;
1609-
1610- // or: MySearchParaams := InitSearchParams('Hallo', [soEntireDocument], swWorkbook);
1611-
1612- // Create search engine and execute search
1613- with TsSearchEngine.Create(MyWorkbook) do begin
1614- if FindFirst(MySearchParams, foundWorksheet, foundRow, foundCol) then begin
1615- WriteLn('First "', MySearchparams.SearchText, '" found in cell ', GetCellString(foundRow, foundCol), ' of worksheet ', foundWorksheet.Name);
1616- while FindNext(MySeachParams, foundWorksheet, foundRow, foundCol) do
1617- WriteLn('Next "', MySearchParams.SearchText, '" found in cell ', GetCellString(foundRow, foundCol), ' of worksheet ', foundWorksheet.Name);
1618- end;
1619- Free;
1620- end;
1621- finally
1622- MyWorkbook.Free;
1623- end;
1624-end;
1625-```
1626-
1627-The search engine provides two methods for **searching**: `FindFirst` and `FindNext`. They are very similar, they only differ in where the search begins. In case of `FindFirst`, the starting cell is determined from the `Options` described below. In case of `FindNext` the search begins at the cell adjacent to the previously found cell. Both methods return the worksheet and row and column indexes of the cell in which the search text is found. If the search is not successful then the function result is `FALSE`, and the `foundWorksheet` is nil. It is clear that the `foundWorksheet` cannot be used for anything else while the search is running.
1628-
1629-The record `TsSearchParams` specifies the criteria used for searching:
1630-
1631-``` pascal
1632-type
1633- TsSearchParams = record
1634- SearchText: String;
1635- Options: TsSearchOptions;
1636- Within: TsSearchWithin;
1637- end;
1638-```
1639-
1640-Besides the text to be searched (`SearchText`) it provides a set of options to narrow the search:
1641-
1642-- `soCompareEntireCell`: Compares the `SearchText` with the entire cell content. If not contained in the `Options` then the cell text is compared only partially.
1643-- `soMatchCase`: Perform a case-sensitive search
1644-- `soRegularExpr`: The `SearchText` is considered as a regular expression
1645-- `soAlongRows`: The search engine proceeds first along the rows. If not contained in the `Options` then the search proceeds along the columns.
1646-- `soBackward`: The search begins at the end of the document, or runs backward from the active cell. If not contained in the `Options` then the search starts at the beginning of the document, or runs forward from the active cell.
1647-- `soWrapDocument`: If a search has reached the end of the document the search is resumed at its beginning (or vice versa, if `soBackward` is used).
1648-- `soEntireDocument`: Search begins at the first cell (or last cell if `soBackward` is used). If not contained in the `Options` then the search begins at the active cell of the worksheet. Ignored by `FindNext`.
1649-
1650-The record field `Within` identifies the part of the spreadsheet to be searched:
1651-
1652-- `swWorkbook`: The entire workbook is searched. If the search phrase is not found on the first worksheet (or last worksheet if `soBackward` is used) then the search continues with the next (previous) sheet.
1653-- `swWorksheet`: The search is limited to the currently active worksheet
1654-- `swColumn`: Search is restricted to the column of the active cell
1655-- `swRow`: Search is restricted to the row of the active cell.
1656-
1657-The search params record can be initialized by calling `InitSearchParams` (in unit *fpsutils*) with the record elements as optional parameters. Use the methods `Workbook.ActiveWorksheet` and `Worksheet.SelectCell(ARow, ACol)` to define the active worksheet and the position of the active cell, respectively, if needed by the search.
1658-
1659-In addition to searching the search engine can also be used for **replacing** the found text by another string. Call the functions `ReplaceFirst` or `ReplaceNext` for this purpose. They act like their `FindXXXX` counterparts, therefore, they require a `TsSearchParams` record to specify the search criteria. But in addition to searching, these functions also perform the text replacement according to the specification in a `TsReplaceParams` record:
1660-
1661-``` pascal
1662-type
1663- TsReplaceParams = record
1664- ReplaceText: String;
1665- Options: TsReplaceOptions;
1666- end;
1667-```
1668-
1669-The `ReplaceText` identifies the string which will replace the found text pattern. The `Options` define a set of criteria how the replacement is done:
1670-
1671-- `roReplaceEntirecell`: Replaces the entire cell text by the `ReplaceText`. If not contained in the `Options` then only the part matching the `SearchText` is replaced.
1672-- `roReplaceAll`: Performs the replacement in all found cells (i.e., simply call `ReplaceFirst` to replace all automatically).
1673-- `roConfirm`: Calls an event handler for the `OnConfirmReplacement` event in which the user must specify whether the replacement is to be performed or not. Note that this event handler is mandatory if `roConfirm` is set.
1674-
1675-Use the function `InitReplaceParams` (in unit *fpsutils*) to initialize the replace parameters record with the provided (but optional) values.
1676-
1677-### Column and row operations
1678-
1679-The worksheet provides these methods for inserting, deleting, hiding or unhiding columns and rows:
1680-
1681-``` pascal
1682-type
1683- TsWorksheet = class
1684- ...
1685- procedure DeleteCol(ACol: Cardinal);
1686- procedure DeleteRow(ARow: Cardinal);
1687-
1688- procedure InsertCol(ACol: Cardinal);
1689- procedure InsertRow(ARow: Cardinal);
1690-
1691- procedure RemoveCol(ACol: Cardinal);
1692- procedure RemoveRow(ARow: Cardinal);
1693-
1694- procedure RemoveAllCols;
1695- procedure RemoveAllRows
1696-
1697- procedure HideCol(ACol: Cardinal);
1698- procedure HideRow(ARow: Cardinal);
1699-
1700- procedure ShowCol(ACol: Cardinal);
1701- procedure ShowRow(ARow: Cardinal);
1702-
1703- function ColHidden(ACol: Cardinal): Boolean;
1704- function RowHidden(ARow: Cardinal): Boolean;
1705-```
1706-
1707-- When a column or row is **deleted** by `DeleteCol` or `DeleteRow`, any data assigned to this column or row are removed, i., cells, comments, hyperlinks, TCol or TRow records. Data at the right of or below the deleted column/row move to the left or up.
1708-
1709-- `RemoveCol` and `RemoveRow`, in contract, **remove** only the column or row record, i.e. reset column width and row height to their default values. Cell, comment, and hyperlink data are not affected.
1710-
1711-- `RemoveAllCols` **removes all** column records, i.e. resets all column widths; `RemoveAllRows` does the same with the row records and row heights.
1712-
1713-- A column or row is **inserted** before the index specified as parameter of the `InsertXXX` method.
1714-
1715-### Page layout
1716-
1717-#### General
1718-
1719-So far, FPSpreadsheet does not support printing of worksheets, but the Office applications do, and they provide a section of information in their files for this purpose. In FPSpreadsheets this information is available in the `TsPageLayout` class which belongs to the `TsWorksheet` data structure. Its properties and methods combine the most important features from the Excel and OpenDocument worlds.
1720-
1721-``` pascal
1722-type
1723- TsPageOrientation = (spoPortrait, spoLandscape);
1724-
1725- TsPrintOption = (poPrintGridLines, poPrintHeaders, poPrintPagesByRows,
1726- poMonochrome, poDraftQuality, poPrintCellComments, poDefaultOrientation,
1727- poUseStartPageNumber, poCommentsAtEnd, poHorCentered, poVertCentered,
1728- poDifferentOddEven, poDifferentFirst, poFitPages);
1729-
1730- TsPrintOptions = set of TsPrintOption;
1731-
1732- TsHeaderFooterSectionIndex = (hfsLeft, hfsCenter, hfsRight);
1733-
1734- TsCellRange = record
1735- Row1, Col1, Row2, Col2: Cardinal;
1736- end;
1737-
1738- TsPageLayout = class
1739- ...
1740- public
1741- ...
1742- { Methods }
1743- // embedded header/footer images
1744- procedure AddHeaderImage(AHeaderIndex: Integer;
1745- ASection: TsHeaderFooterSectionIndex; const AFilename: String);
1746- procedure AddFooterImage(AFooterIndex: Integer;
1747- ASection: TsHeaderFooterSectionIndex; const AFilename: String);
1748- procedure GetImageSections(out AHeaderTags, AFooterTags: String);
1749- function HasHeaderFooterImages: Boolean;
1750-
1751- // Repeated rows and columns
1752- function HasRepeatedCols: Boolean;
1753- function HasRepeatedRows: Boolean;
1754- procedure SetRepeatedCols(AFirstCol, ALastCol: Cardinal);
1755- procedure SetRepeatedRows(AFirstRow, ALastRow: Cardinal);
1756-
1757- // print ranges
1758- function AddPrintRange(ARow1, ACol1, ARow2, ACol2: Cardinal): Integer; overload;
1759- function AddPrintRange(const ARange: TsCellRange): Integer; overload;
1760- function GetPrintRange(AIndex: Integer): TsCellRange;
1761- function NumPrintRanges: Integer;
1762- procedure RemovePrintRange(AIndex: Integer);
1763-
1764- { Properties }
1765- property Orientation: TsPageOrientation read FOrientation write FOrientation;
1766- property PageWidth: Double read FPageWidth write FPageWidth;
1767- property PageHeight: Double read FPageHeight write FPageHeight;
1768- property LeftMargin: Double read FLeftMargin write FLeftMargin;
1769- property RightMargin: Double read FRightMargin write FRightMargin;
1770- property TopMargin: Double read FTopMargin write FTopMargin;
1771- property BottomMargin: Double read FBottomMargin write FBottomMargin;
1772- property HeaderMargin: Double read FHeaderMargin write FHeaderMargin;
1773- property FooterMargin: Double read FFooterMargin write FFooterMargin;
1774- property StartPageNumber: Integer read FStartPageNumber write SetStartPageNumber;
1775- property ScalingFactor: Integer read FScalingFactor write SetScalingFactor;
1776- property FitHeightToPages: Integer read FFitHeightToPages write SetFitHeightToPages;
1777- property FitWidthToPages: Integer read FFitWidthToPages write SetFitWidthToPages;
1778- property Copies: Integer read FCopies write FCopies;
1779- property Options: TsPrintOptions read FOptions write FOptions;
1780- property Headers[AIndex: Integer]: String read GetHeaders write SetHeaders;
1781- property Footers[AIndex: Integer]: String read GetFooters write SetFooters;
1782- property RepeatedCols: TsRowColRange read FRepeatedCols;
1783- property RepeatedRows: TsRowColRange read FRepeatedRows;
1784- property PrintRange[AIndex: Integer]: TsCellRange read GetPrintRange;
1785- property FooterImages[ASection: TsHeaderFooterSectionIndex]: TsHeaderFooterImage read GetFooterImages;
1786- property HeaderImages[ASection: TsHeaderFooterSectionIndex]: TsHeaderFooterImage read GetHeaderImages;
1787- end;
1788-
1789- TsWorksheet = class
1790- ...
1791- public
1792- property PageLayout: TsPageLayout;
1793- ...
1794- end;
1795-```
1796-
1797-> **Note:** The fact that the `PageLayout` belongs to the worksheet indicates that there can be several page layouts in the same workbook, one for each worksheet.
1798-
1799-- **Orientation** defines the orientation of the printed paper, either portrait or landscape.
1800-
1801-- **Page width** and **page height** refer to the standard orientation of the paper, usually portrait orientation.
1802-
1803-- **Left**, **top**, **right** and **bottom margins** are self-explanatory and are given in millimeters.
1804-
1805-- **HeaderMargin** is understood - like in Excel - as the distance between the paper top edge and the top of the header, and **TopMargin** correspondingly is the distance between the top paper edge and the top of the first table row, i.e. if the header contains several line breaks it can reach into the the table part of the print-out. This is different from OpenDocument files where the header can grow accordingly.
1806-
1807-- **StartPageNumber** should be altered if the print-out should not begin with page 1. This setting requires to add the option `poUseStartPageNumber` to the PageLayout's `Options` - but this is normally done automatically.
1808-
1809-- The **ScalingFactor** is given in percent and can be used to reduce the number of printed pages. Modifying this property clear the option `poFitToPages` from the PageLayout's `Options`.
1810-
1811-- Alternatively to ScalingFactor, you can also use **FitHeightToPages** or **FitWidthToPages**. The option `poFitToPages` must be active in order to override the `ScalingFactor`setting. `FitHeightToPages` specifies the number of pages onto which the entire height of the printed worksheet should fit. Accordingly, `FitWidthToPages` can be used to define the number of pages on which the entire width of the worksheet has to fit. The value `0` has the special meaning of "use as many pages as needed". In this way, the setting "Fit all columns on one page" of Excel, for example, can be achieved by this code:
1812-
1813-``` pascal
1814- MyWorksheet.PageLayout.Options := MyWorksheet.PageLayout.Options + [poFitPages];
1815- MyWorksheet.PageLayout.FitWidthToPages := 1; // all columns on one page width
1816- MyWorksheet.PageLayout.FitHeightToPages := 0; // use as many pages as needed
1817-```
1818-
1819-- **Header rows and columns repeated on every printed page** can be defined by the `RepeatedCols` and `RepeatedRows` records; their elements `FirstIndex` and `LastIndex` refer to the indexes of the first and last column or row, respectively, to be repeated. Use the methods `SetRepeatedCols` and `SetRepeatedRows` to define these numbers. Note that the second parameter for the last index can be omitted to use only a single header row or column.
1820-
1821-- **Print ranges** or **print areas** (using Excel terminology) can be used to restrict printing only to a range of cells. Use the methods `AddPrintRange` to define a cell range for printing: specify the indexes of the left column, top row, right column and bottom row of the range to be printed. A worksheet can contain several print ranges.
1822-
1823-- **Copies** specifies how often the worksheet will be printed.
1824-
1825-- The **Options** define further printing properties, their names are self-explaining. They were defined according to Excel files, some of them do not exist in ODS files and are ignored there.
1826-
1827-#### Headers and footers
1828-
1829-**Header and footer texts** can be composed of left-aligned, centered and right-aligned strings. Add the symbol `&L` to indicate that the following string is to be printed as the left-aligned part; use `&C` accordingly for the centered and `&R` for the right-aligned parts. There are other symbols which will be replaced by their counterparts during printing:
1830-
1831-- `&L`: begins the **left-aligned section** of a header or a footer text definition
1832-- `&C`: begins the **centered section** of a header or a footer text definition
1833-- `&R`: begins the **right-aligned section** of a header or a footer text definition
1834-- `&P`: **page number**
1835-- `&N`: **page count**
1836-- `&D`: current **date** of printing
1837-- `&T`: current **time** of printing
1838-- `&A`: **worksheet name**
1839-- `&F`: **file name** without path
1840-- `&Z`: **file path** without file name
1841-- `&G`: embedded **image** - use the methods `AddHeaderImage` or `AddFooterImage` to specify the image file; this also appends the `&G` to the other codes of the current header/footer section. Note that not all image types known by the Office application may be accepted. Currently the image can be *jpeg*, *png*, *gif*, *bmp*, *tiff*, *pcx*, *svg*, *wmf* or *emf*.
1842-- `&B`: **bold** on/off
1843-- `&I`: **italic** on/off
1844-- `&U`: **underlining** on/off
1845-- `&E`: **double-underlining** on/off
1846-- `&S`: **strike-out** on/off
1847-- `&H`: **shadow** on/off
1848-- `&O`: **outline** on/off
1849-- `&X`: **superscript** on/off
1850-- `&Y`: **subscript** on/off
1851-- `&"font"`: begin using of the **font** with the specified name, e.g. `&"Arial"`
1852-- `&number`: begin using of the specified **font size** (in points), e.g. `&16`
1853-- `&Krrggbb`: switch to the **font color** specified to the binary value of the specified color, e.g. use `&KFF0000` for red.
1854-
1855-The arrays `Headers[]`/`Footers[]` provide space for usage of three different headers or footers:
1856-
1857-- `Headers[0]` refers to the header used on the **first page** only, similarly for `Footers[0]`. Instead of index `0` you can use the constant `HEADER_FOOTER_INDEX_FIRST`. Leave this string empty if there is no special first-page header/footer.
1858-- `Headers[1]` refers to the header on pages with **odd page numbers**, similarly for `Footers[1]`. Instead of index `1` you may want to use the constant `HEADER_FOOTER_INDEX_ODD`.
1859-- `Headers[2]` refers to the header on lages with **even page nubmers**, similarly for `Footers[2]`. Instead of index `2` you may want to use the constant `HEADER_FOOTER_INDEX_EVEN`.
1860-
1861-Leave the strings at index 0 and 2 empty if the print-out should always have the same header/footer. You can use the constant `HEADER_FOOTER_INDEX_ALL` for better clarity. Example:
1862-
1863-``` pascal
1864- MyWorksheet.PageLayout.Headers[HEADER_FOOTER_INDEX_ALL] := '&C&D &T'; // centered "date time" on all pages as header
1865- MyWorksheet.PageLayout.Footers[HEADER_FOOTER_INDEX_ODD] := '&RPage &P of &N'; // right-aligned "Page .. of ..." on odd pages as footer
1866- MyWorksheet.PageLayout.Footers[HEADER_FOOTER_INDEX_EVEN] := '&LPage &P of &N'; // dto, but left-aligned on even pages
1867-```
1868-
1869-### Protection
1870-
1871-In the Office applications, workbooks can be protected from unintentional changes by the user. fpspreadsheet is able to read and write the data structures related to protection, but does not enforce them. This means, for example, that cells can be modified by the user although the worksheet is specified as being locked.
1872-
1873-Protection is handled at three levels: workbook protection, worksheet protection and cell protection.
1874-
1875-#### Workbook protection
1876-
1877-`TsWorkbook` contains a set of workbook or document protection options:
1878-
1879-- `bpLockRevision`: specifies that the workbook is locked for revisions
1880-- `bpLockStructure`: if this option is set then worksheets in the workbook cannot be moved, deleted, hidden, unhidden, or renamed, and new worksheets cannot be inserted.
1881-- `bpLockWindows`: indicates that the workbook windows in the Office application are locked. Windows are the same size and position each time the workbook is opened by the Office application.
1882-
1883-In relation to workbook protection is the worksheet option `soPanesProtection` which prevents the panes of a worksheet from being modified if the workbook is protected.
1884-
1885-Depending on the file format, only some of these options might be supported. In these cases, the non-supported options are commonly accepted default values.
1886-
1887-Office applications are able to encrypt their spreadsheet files. The readers of FPSpreadsheet basically are not able to open these files. However, there exists a related package, **laz_fpspreadsheet_crypto.lpk**, which has access to decryption routines and is able to read xlsx and ods files. These readers are in the units *xlsxOOXML_crypto* and *fpsOpendocument_crypto*, respectively. Adding them to the uses clause of the application installs user-provided readers with `FormatID` `sfidOOXML_crypto` and `sfidOpenDocument_crypto`, respectively. If the password is known it can be specified as a parameter to the workbook's `LoadFromFile`/`ReadFromStream` methods. If no password is specified the workbook fires the event `OnQueryPassword` in which the user can provide the password, e.g. like this:
1888-
1889-``` pascal
1890-function TForm1.QueryPasswordHandler: String;
1891-begin
1892- Result := InputBox('Password required', 'Password', '');
1893-end;
1894-
1895-procedure TForm1.LoadWorkbook(AFileName: String);
1896-var
1897- workbook: TsWorkbook;
1898-begin
1899- workbook := TsWorkbook.Create;
1900- try
1901- workbook.OnQueryPassword := @QueryPasswordHandler;
1902- workbook.ReadFromFile(AFileName);
1903- ...
1904- finally
1905- workbook.Free;
1906- end;
1907-end;
1908-
1909-// or
1910-
1911-procedure TForm1.LoadWorkbookWithPassword(AFileName, APassword: STring);
1912-var
1913- workbook: TsWorkbook;
1914-begin
1915- workbook := TsWorkbook.Create;
1916- try
1917- workbook.ReadFromFile(AFileName, APassword);
1918- ...
1919-```
1920-
1921-#### Worksheet protection
1922-
1923-`TsWorksheet` houses a similar set of protection options. Whenever an option is included in the set `Protection` of the workbook the corresponding action is not allowed and locked:
1924-
1925-- `spCells`: the cells in the sheet are protected. It depends on the level of cell protection whether a particular cell can be changed or not. By default, no cell can be changed.
1926-- `spDeleteColumns`: deleting of columns is not be allowed
1927-- `spDeleteRows`: it is not possible to delete rows
1928-- `spFormatCells`: formatting of cells is not allowed
1929-- `spFormatColumns`: columns cannot be formatted.
1930-- `spFormatRows`: rows cannot be formatted
1931-- `spInsertColumns`: it is not allowed to insert columns
1932-- `spInsertRows`: rows cannot be inserted
1933-- `spInsertHyperlinks`: it is not possible to insert new hyperlinks
1934-- `spSort`: the worksheet is not allowed to be sorted.
1935-- `spSelectLockedCells`: Cells which are locked cannot be selected any more.
1936-- `spSelectUnlockedCells`: Even cells which are unlocked cannot be selected. Together with `spSelectLockedCells` this means that the selection in the worksheet is frozen.
1937-
1938-These levels of protection become active if the option `soProtected` is added to the worksheet's `Options`, or by calling the worksheet method `Protect(true)`.
1939-
1940-#### Cell protection
1941-
1942-Cell protection becomes active when the worksheet protection is enabled. It is controlled by a set of `TsCellProtection` elements which belong to the cell format record:
1943-
1944-- `cpLockCell`: This option determines whether cell content can be modified by the user. Since it is on by default cells of a protected worksheet normally cannot be edited. In order to unlock some cells for user input the option `cpLockCell` must be removed from the protection of these cells.
1945-- `cpHideFormulas`: prevents formulas from being shown in the Office application.
1946-
1947-Cell protection can be changed by calling the worksheet method `WriteCellProtection`. Conversely, `ReadCellProtection` can be used to retrieve the protection state of a particular cell:
1948-
1949-``` pascal
1950-// query and modifiy the protection state of cell A1 (row=0, col=0)
1951-var
1952- cell: PCell;
1953- cellprot: TsCellProtections;
1954-...
1955- // Find the cell
1956- cell := worksheet.FindCell(0, 0);
1957- // query cell protection
1958- cellprot := worksheet.ReadCellProtection(cell);
1959- // Unlock the cell for editing, don't change the visibility of formulas
1960- worksheet.WriteCellProtection(cell, cellprot - [cpLockCell]);
1961- // Hide formula of the cell and unlock the cell.
1962- worksheet.WriteCellProtection(cell, [cpHideFormulas]);
1963- // Activate protection
1964- worksheet.Protect(true);
1965-```
1966-
1967-#### Passwords
1968-
1969-Workbook and worksheet protection can be secured by passwords. Note that these passwords do not encrypt the file (except for workbook protection in Excel 2007). In the Office applications the user must enter this password to turn off protection or to change protection items. The encrypted password is stored in the `CryptoInfo` record of the wordbook and the worksheets, respectively:
1970-
1971-``` pascal
1972-type
1973- TsCryptoInfo = record
1974- PasswordHash: String;
1975- Algorithm: TsCryptoAlgorithm; // caExcel, caSHA1, caSHA256, etc.
1976- SaltValue: String;
1977- SpinCount: Integer;
1978- end;
1979-```
1980-
1981-> **Warning:** FPSpreadsheet does not perform any hashing calculations, the `CryptoInfo` record is just passed through from reading to writing. This causes problems when different file formats are involved in reading and writing. It is attempted to detect **incompatible combinations**. In these cases, the **password protection is removed**, and an error is logged by the workbook.
1982-
1983-### Loading and saving
1984-
1985-#### Adding new file formats
1986-
1987-FPSpreadsheet is open to any spreadsheet file format. In addition to the built-in file formats which are specified by one of the `sfXXXX` declarations, it is possible to provide dedicated reader and writer units to get access to special file formats.
1988-
1989-- Write a unit implementing a reader and a writer for the new file format. They must inherit from the basic `TsCustomSpreadReader` and `TsCustomWriter`, respectively, - both are implemented in unit *fpsReaderWriter* -, or from one of the more advanced ones belonging to the built-in file formats.
1990-- Register the new reader/writer by calling the function `RegisterSpreadFileFormat` in the `initialization` section of this unit (implemented in unit *fpsRegFileFormats*):
1991-
1992-``` pascal
1993-function RegisterSpreadFormat(AFormat: TsSpreadsheetFormat; AReaderClass: TsSpreadReaderClass; AWriterClass: TsSpreadWriterClass;
1994- AFormatName, ATechnicalName: String; const AFileExtensions: array of String): TsSpreadFormatID;
1995-```
1996-
1997-- `AFormat` must have the value `sfUser` to register an external file format.
1998-- `AReaderClass` is the class of the reader (or nil, if reading functionality is not implemented).
1999-- `AWriterClass` is the class of the writer (or nil, if writing functionality is not implemented).
2000-- `AFormatName` defines the name of the format as used for example in the filter list of file-open dialogs.
2001-- `ATechnicalName` defines a shorter format name.
2002-- `AFileExtensions` is an array of file extensions used in the files. The first array element denotes the default extension. The extensions must begin with a period as in `.xls`.
2003-- The registration function returns a numerical value (`TsSpreadFormatID`) which can be used as format identifier in the workbook reading and writing functions which exist in overloaded version accepting a numerical value for the format specifier. In contract to the built-in formats the FormatID is negative.
2004-- Finally, in your application, add the new unit to the `uses` clause. This will call the registrations function when the unit is loaded and make the new file format available to FPSpreadsheet.
2005-
2006-#### Stream selection
2007-
2008-Workbooks are loaded and saved by means of the `ReadFromFile` and `WriteToFile` methods, respectively (or by their stream counterparts, `ReadFromStream` and `WriteToStream`).
2009-
2010-By default, the data files are accessed by means of **memory streams** which yields the fastest access to the files. In case of very large files (e.g. tens of thousands of rows), however, the system may run out of memory. There are two methods to defer the memory overflow by some extent.
2011-
2012-- Add the element `boBufStream` to the workbook's `Options`. In this case, a **"buffered" stream** is used for accessing the data. This kind of stream holds a memory buffer of a given size and swaps data to file if the buffer becomes too small.
2013-- Add the element `boFileStream` to the workbook's `Options`. This option avoids memory streams altogether and creates temporary **files** if needed. This is, however, the slowest method of data access.
2014-- If both options are set then `boBufStream` is ignored.
2015-- In practice, however, the effect of the selected streams is not very large if memory is to be saved.
2016-
2017-#### Virtual mode
2018-
2019-Beyond the transient memory usage during reading/writing the main memory consumptions originates in the internal structure of FPSpreadsheet which holds all data in memory. To overcome this limitation, a "virtual mode" has been introduced. In this mode, data are received from a data source (such as a database table) and are passed through to the writer without being collected in the worksheet. It is clear that data loaded in virtual mode cannot be displayed in the visual controls. Virtual mode is good for conversion between different data formats.
2020-
2021-These are the steps required to use this mode:
2022-
2023-- Activate virtual mode by adding the option `boVirtualMode` to the `Options` of the workbook.
2024-- Tell the spreadsheet writer how many rows and columns are to be written. The corresponding worksheet properties are `VirtualRowCount` and `VirtualColCount`.
2025-- Write an event handler for the event `OnWriteCellData` of the worksheet. This handler gets the index of row and column of the cell currently being saved. You have to return the value which will be saved in this cell. You can also specify a template cell that physically exists in the workbook from which the formatting style is copied to the destination cell. Please be aware that when exporting a database, you are responsible for advancing the dataset pointer to the next database record when writing of a row is complete.
2026-- Call the `WriteToFile` method of the workbook.
2027-
2028-Virtual mode also works for reading spreadsheet files.
2029-
2030-The folder *example/other* contains a worked out sample project demonstrating virtual mode using random data. More realistic database examples are in *example/db_import_export* and in the chapter on converting a large database table using virtual mode.
2031-
2032-### Dataset export
2033-
2034-FPC contains a set of units that allow you to export datasets to various formats (XML, SQL statements, DBF files,...). There is a master package that allows you to choose an export format at design time or run time (Lazarus package lazdbexport).
2035-
2036-FPSpreadsheet has `TFPSExport` which plugs into this system. It allows you to export the contents of a dataset to a new spreadsheet (*.xls*, *.xlsx*, *.ods*, wikitable format) file into a table on the first sheet by default. In addition, if `MultipleSheets` is set to `TRUE` it is possible to combine several sheets into individual worksheets in the same file. You can optionally include the field names as header cells on the first row using the `HeaderRow` properties in the export settings. The export component tries to find the number format of the cells according to the dataset field types.
2037-
2038-For more complicated exports, you need to manually code a solution (see examples below) but for simple data transfer/dynamic exports at user request, this unit will probably be sufficient.
2039-
2040-A simple example of how this works:
2041-
2042-``` pascal
2043-uses
2044-...
2045-fpsexport
2046-...
2047-var
2048- Exp: TFPSExport;
2049- ExpSettings: TFPSExportFormatSettings;
2050- TheDate: TDateTime;
2051-begin
2052- FDataset.First; //assume we have a dataset called FDataset
2053- Exp := TFPSExport.Create(nil);
2054- ExpSettings := TFPSExportFormatSettings.Create(true);
2055- try
2056- ExpSettings.ExportFormat := efXLS; // choose file format
2057- ExpSettings.HeaderRow := true; // include header row with field names
2058- Exp.FormatSettings := ExpSettings; // apply settings to export object
2059- Exp.Dataset:=FDataset; // specify source
2060- Exp.FileName := 'c:\temp\datadump.xls';
2061- Exp.Execute; // run the export
2062- finally
2063- Exp.Free;
2064- ExpSettings.Free;
2065- end;
2066-```
2067-
2068-#### Export to DBF
2069-
2070-You can save the information from Excel to dbf rather easily. Here is the example from forum. Please note that this example is supposed to work with Win1251 encoding by default. To get more information please refer to this thread [1](http://forum.lazarus.freepascal.org/index.php/topic,41636.0.html)
2071-
2072-``` pascal
2073-procedure TForm1.ExportToDBF(AWorksheet: TsWorksheet; AFileName: String);
2074-var
2075- i: Integer;
2076- f: TField;
2077- r, c: Cardinal;
2078- cell: PCell;
2079-begin
2080- DbfGlobals.DefaultCreateCodePage := 1251; //default encoding of the dbf
2081- DbfGlobals.DefaultOpenCodePage := 1251; //default encoding of the dbf
2082- if Dbf1.Active then Dbf1.Close;
2083- if FileExists(AFileName) then DeleteFile(AFileName);
2084-
2085- Dbf1.FilePathFull := ExtractFilePath(AFileName);
2086- Dbf1.TableName := ExtractFileName(AFileName);
2087- Dbf1.TableLevel := 25; // DBase IV: 4 - most widely used; or 25 = FoxPro supports nfCurrency
2088- Dbf1.LanguageID := $C9; //russian language by default
2089- Dbf1.FieldDefs.Clear;
2090- //below are the fields in excel
2091- Dbf1.FieldDefs.Add('fam', ftString);
2092- //add other fields you want to save
2093-
2094- Dbf1.CreateTable;
2095- Dbf1.Open;
2096-
2097- for f in Dbf1.Fields do
2098- f.OnGetText := @DbfGetTextHandler;
2099-
2100- // Skip row 0 which contains the headers
2101- for r := 1 to AWorksheet.GetLastRowIndex do begin
2102- Dbf1.Append;
2103- for c := 0 to Dbf1.FieldDefs.Count-1 do begin
2104- f := Dbf1.Fields[c];
2105- cell := AWorksheet.FindCell(r, c);
2106- if cell = nil then
2107- f.Value := NULL
2108- else
2109- case cell^.ContentType of
2110- cctUTF8String: f.AsString := UTF8ToCP1251(cell^.UTF8StringValue);
2111- cctNumber: f.AsFloat := cell^.NumberValue;
2112- cctDateTime: f.AsDateTime := cell^.DateTimeValue;
2113- else f.AsString := UTF8ToCP1251(AWorksheet.ReadAsText(cell));
2114- end;
2115- end;
2116- Dbf1.Post;
2117- end;
2118-end;
2119-
2120-//This procedure is called so the text in the cells could be correctly dispayed on WorkSheetGrid on the form, otherwise '?' symbols showing
2121-procedure TForm1.DbfGetTextHandler(Sender: TField; var AText: string; DisplayText: Boolean);
2122-begin
2123- if DisplayText then
2124- AText := CP1251ToUTF8(Sender.AsString);
2125-end;
2126-```
2127-
2128-## Visual controls for FPSpreadsheet
2129-
2130-The package **laz_fpspreadsheet_visual** implements a series of controls which simiplify creation of visual GUI applications:
2131-
2132-- **TsWorkwookSource** links the controls to a workbook and notifies the controls of changes in the workbook.
2133-- **[[TsWorksheetGrid]]** implements a grid control with editing and formatting capabilities; it can be applied in a similar way to TStringGrid.
2134-- **TsWorkbookTabControl** provides a tab sheet for each worksheet of the workbook. It is the ideal container for a [[TsWorksheetGrid]].
2135-- **TsWorksheetIndicator**: a combobox which lists all worksheets of the workbook.
2136-- **TsCellEdit** corresponds to the editing line in Excel or Open/LibreOffice. Direct editing in the grid, however, is possible as well.
2137-- **TsCellIndicator** displays the name of the currently selected cell; it can be used for navigation purposes by entering a cell address string.
2138-- **TsCellCombobox** offers to pick cell properties for a selection of formatting attributes: font name, font size, font color, background color.
2139-- **TsSpreadsheetInspector** is a tool mainly for debugging; it displays various properties of workbook, worksheet, cell value and cell formatting, similar to the ObjectInspector of Lazarus. It is read-only, though.
2140-- Various standard actions are provided in the unit **fpsActions**. Applied to menu or toolbar, they simplify typical formatting and editing tasks without having to write a line of code.
2141-- **TsWorkbookChartSource** interfaces a workbook with the [[TAChart]] library. It defines the cell ranges from which a Chart series can get its data. There is also an older component, [[TsWorksheetChartSource]], which requires all cells to be from the same worksheet. For this reason, it has not been fully integrated into the environment of FPSpreadsheet controls and will be removed from the library in the future.
2142-
2143-See the [[FPSpreadsheet tutorial: Writing a mini spreadsheet application]] for more information and a tutorial, and see demo projects for examples of the application of these components.
2144-
2145-## Examples
2146-
2147-Please see [[FPSpreadsheet: Examples]] for a variety of code examples.
2148-
2149-## Download
2150-
2151-### Subversion
2152-
2153-You can download FPSpreadsheet using the subversion software and the following command line:
2154-
2155-``` bash
2156-svn checkout https://svn.code.sf.net/p/lazarus-ccr/svn/components/fpspreadsheet fpspreadsheet
2157-```
2158-
2159-### Stable releases
2160-
2161-The most current release is distributed by the Online-Package-Manger which is integrated in the Lazarus IDE (menu "Package" \> "Online package manager"): Scroll down the list of available packages, check the entry "FPSpreadsheet" and click "Install". Confirm the prompt to rebuild the IDE. When the process is complete you find the new components in palette "FPSpreadsheet".
2162-
2163-Older releases of FPSpreadsheet cann still be found on [sourceforge](https://sourceforge.net/projects/lazarus-ccr/files/FPSpreadsheet/).
2164-
2165-## Installation
2166-
2167-- If you only need non-GUI components: in Lazarus: Package/Open Package File, select **laz_fpspreadsheet.lpk**, click Compile. Now the package is known to Lazarus (and should e.g. show up in Package/Package Links). Now you can add a dependency on `laz_fpspreadsheet` in your project options and `fpspreadsheet` to the uses clause of the project units that need to use it.
2168-- If you also want GUI components ([[TsWorksheetGrid]] and [[TsWorksheetChartSource]]): Package/Open Package File, select **laz_fpspreadsheet_visual.lpk**, click Compile, then click Use, Install and follow the prompts to rebuild Lazarus with the new package. Drop needed grid/chart components on your forms as usual.
2169-- If you want to have a GUI component for dataset export: Package/Open Package File, select **laz_fpspreadsheetexport_visual.lpk**, click Compile, then click, Use, Install and follow the prompts to rebuild Lazarus with the new package. Drop needed export components from the **Data Export** tab on your forms as usual.
2170-- FPSpreadsheet is developed with the latest stable fpc version (currently fpc 3.0.2). We only occasionally check older versions.
2171-- The basic spreadsheet functionality works with Lazarus versions back to version 1.0. Some visual controls or demo programs, however, require newer versions. Please update your Lazarus if you have an older version and experience problems.
2172-
2173-### Conditional defines
2174-
2175-Here is a list of **conditional defines** which can be activated in order to tweak some operating modes of the packages and/or make it compilable with older Lazarus/FPC versions:
2176-
2177-- `FPS_DONT_USE_CLOCALE`: In Unix systems, the unit `clocale` is automatically added to the uses clause of *fpspreadsheet.pas*. This unit sets up localization settings needed for locale-dependent number and date/time formats. However, this adds a dependence on the C library to the package [2](http://lazarus-ccr.sourceforge.net/docs/rtl/clocale/index.html). If this is not wanted, define `FPS_DONT_USE_CLOCALE`.
2178-- `FPS_VARISBOOL`: fpspreadsheet requires the function VarIsBool which was introduced by fpc 2.6.4. If an older FPC versions is used define `FPS_VARISBOOL`. Keep undefined for the current FPC version.
2179-- `FPS_LAZUTF8`: fpspreadsheet requires some functions from the unit LazUTF8 which were introduced by Lazarus 1.2. If an older Lazarus version is used define `FPS_LAZUTF8`. Keep undefined for the current Lazarus version.
2180-- `FPS_NO_GRID_MULTISELECT`: In order to allow selection of multiple ranges in the WorksheetGrid a sufficiently new version of the basic TCustomGrid is needed. The required property "RangeSelect" was introduced in Lazarus 1.4. In order to compile the package with older versions activate the define `FPS_NO_GRID_MULTISELECT`.
2181-- `FPS_PTRINT`: In order to provide safe casting of integers to pointers new version of FPC provide the types PtrInt and IntPtr. This is not yet available in fpc 2.6.0. </tt>
2182-- `FPS_NEED_STRINGHASHLIST`: Unit stringhashlist belongs to LCL before Lazarus 1.8. To avoid a requirement of LCL in laz_fpspreadsheet.lpk a copy in the fps directory is provided. This copy is used when the define FPS_NEED_STRINGHASHLIST is active. The define is not needed for Lazarus versions \>= 1.8.
2183-- `FPS_NO_NEW_UTF8_ROUTINES`: In Lazarus 2.0+ some UTF8 routines in unit LazUTF8 were renamed from UTF8CharacterXXX to UTF8CodePointXXX. Activate the following define when the new routines are not available, i.e. for Lazarus version \< 2.0.
2184-- `FPS_NO_LAZUTF16`: Lazarus 1.8+ has unit LazUTF16 for special access to widestring. This define must be active when this unit is not available, i.e. for Lazarus versions before 1.8.0.
2185-- `FPS_NO_STRING_SPLIT`: Activate the following define if FPS does not have the string Split helper, e.g. before v3.0
2186-
2187-All these defines are collected in the include file *fps.inc*.
2188-
2189-In the most recent test (Feb 2023), all fpspreadsheet packages compile fine with Laz 1.6+ / fpc 3.0+ (some defines in *fps.inc* may have to be adapted, though). With Laz 1.4 / fpc 2.6.4 or older, *fpspreadsheet_dataset.lpk* and *fpspreadsheet_crypto.lpk* cannot be used any more.
2190-
2191-## Support and Bug Reporting
2192-
2193-The recommended place to discuss FPSpreadsheet and obtain support is asking in the [Lazarus Forum](http://forum.lazarus.freepascal.org/index.php?board=49.0).
2194-
2195-Bug reports should be sent to the [Lazarus/Free Pascal Bug Tracker](http://bugs.freepascal.org/); please specify the "Lazarus-CCR" project.
2196-
2197-## Current Progress
2198-
2199-### Progress by supported cell content
2200-
2201-<table>
2202-<thead>
2203-<tr>
2204-<th>Format</th>
2205-<th>Multiple<br />
2206-sheets</th>
2207-<th>Unicode</th>
2208-<th>Reader<br />
2209-support</th>
2210-<th>Writer<br />
2211-support</th>
2212-<th>Text</th>
2213-<th>Number</th>
2214-<th>String<br />
2215-Formula</th>
2216-<th>RPN<br />
2217-Formula</th>
2218-<th>3D cell<br />
2219-references</th>
2220-<th>Date/Time</th>
2221-<th>Comments</th>
2222-<th>Hyperlinks</th>
2223-<th>Images +++</th>
2224-<th>Protection</th>
2225-<th>Conditional<br />
2226-formats</th>
2227-</tr>
2228-</thead>
2229-<tbody>
2230-<tr>
2231-<td>CSV files</td>
2232-<td style="text-align: center;">No</td>
2233-<td style="text-align: center;">Yes +</td>
2234-<td class="working">Working ++</td>
2235-<td class="working">Working ++</td>
2236-<td class="working">Working ++</td>
2237-<td class="working">Working ++</td>
2238-<td style="text-align: center;">N/A</td>
2239-<td style="text-align: center;">N/A</td>
2240-<td style="text-align: center;">N/A</td>
2241-<td class="working">Working ++</td>
2242-<td style="text-align: center;">N/A</td>
2243-<td style="text-align: center;">N/A</td>
2244-<td style="text-align: center;">N/A</td>
2245-<td style="text-align: center;">N/A</td>
2246-<td style="text-align: center;">N/A</td>
2247-</tr>
2248-<tr>
2249-<td>Excel 2.x</td>
2250-<td style="text-align: center;">No</td>
2251-<td style="text-align: center;">No *</td>
2252-<td class="working">Working **</td>
2253-<td class="working">Working</td>
2254-<td class="working">Working</td>
2255-<td class="working">Working</td>
2256-<td class="working">Working</td>
2257-<td class="working">Working ***</td>
2258-<td style="text-align: center;">N/A</td>
2259-<td class="working">Working ****</td>
2260-<td class="working">Working</td>
2261-<td style="text-align: center;">N/A</td>
2262-<td style="text-align: center;">N/A</td>
2263-<td class="working">Working</td>
2264-<td style="text-align: center;">N/A</td>
2265-</tr>
2266-<tr>
2267-<td>Excel 5.0 (Excel 5.0 and 95)</td>
2268-<td style="text-align: center;">Yes</td>
2269-<td style="text-align: center;">No *</td>
2270-<td class="working">Working **</td>
2271-<td class="working">Working</td>
2272-<td class="working">Working</td>
2273-<td class="working">Working</td>
2274-<td class="working">Working</td>
2275-<td class="working">Working ***</td>
2276-<td class="working">Working</td>
2277-<td class="working">Working ****</td>
2278-<td class="working">Working</td>
2279-<td style="text-align: center;">N/A</td>
2280-<td style="text-align: center;">N/A</td>
2281-<td class="working">Working</td>
2282-<td style="text-align: center;">N/A</td>
2283-</tr>
2284-<tr>
2285-<td>Excel 8.0 (Excel 97- 2003)</td>
2286-<td style="text-align: center;">Yes</td>
2287-<td style="text-align: center;">Yes</td>
2288-<td class="working">Working **</td>
2289-<td class="working">Working</td>
2290-<td class="working">Working</td>
2291-<td class="working">Working</td>
2292-<td class="working">Working</td>
2293-<td class="working">Working ***</td>
2294-<td class="working">Working</td>
2295-<td class="working">Working ****</td>
2296-<td class="partial">Reading only</td>
2297-<td class="working">Working</td>
2298-<td class="not working">Not working</td>
2299-<td class="working">Working</td>
2300-<td class="not working">Not working</td>
2301-</tr>
2302-<tr>
2303-<td>Excel 2003/XML</td>
2304-<td style="text-align: center;">Yes</td>
2305-<td style="text-align: center;">Yes</td>
2306-<td class="working">Working **</td>
2307-<td class="working">Working</td>
2308-<td class="working">Working</td>
2309-<td class="working">Working</td>
2310-<td class="working">Working ***</td>
2311-<td class="working">Working</td>
2312-<td class="working">Working</td>
2313-<td class="working">Working ****</td>
2314-<td class="working">Working</td>
2315-<td class="working">Working</td>
2316-<td style="text-align: center;">N/A</td>
2317-<td class="working">Working</td>
2318-<td class="working">Working</td>
2319-</tr>
2320-<tr>
2321-<td>Excel OOXML</td>
2322-<td style="text-align: center;">Yes</td>
2323-<td style="text-align: center;">Yes</td>
2324-<td class="working">Working **</td>
2325-<td class="working">Working</td>
2326-<td class="working">Working</td>
2327-<td class="working">Working</td>
2328-<td class="working">Working ***</td>
2329-<td class="working">Working</td>
2330-<td class="working">Working</td>
2331-<td class="working">Working ****</td>
2332-<td class="working">Working</td>
2333-<td class="working">Working</td>
2334-<td class="working">Working</td>
2335-<td class="working">Working</td>
2336-<td class="working">Working ++++</td>
2337-</tr>
2338-<tr>
2339-<td>OpenDocument</td>
2340-<td style="text-align: center;">Yes</td>
2341-<td style="text-align: center;">Yes</td>
2342-<td class="working">Working **</td>
2343-<td class="working">Working</td>
2344-<td class="working">Working</td>
2345-<td class="working">Working</td>
2346-<td class="working">Working ***</td>
2347-<td class="working">Working</td>
2348-<td class="working">Working</td>
2349-<td class="working">Working ****</td>
2350-<td class="working">Working</td>
2351-<td class="working">Working</td>
2352-<td class="working">Working</td>
2353-<td class="working">Working</td>
2354-<td class="working">Working</td>
2355-</tr>
2356-<tr>
2357-<td>HTML</td>
2358-<td style="text-align: center;">No</td>
2359-<td style="text-align: center;">Yes</td>
2360-<td class="working">Working ++</td>
2361-<td class="working">Working ++</td>
2362-<td class="working">Working ++</td>
2363-<td class="working">Working ++</td>
2364-<td style="text-align: center;">N/A</td>
2365-<td style="text-align: center;">N/A</td>
2366-<td style="text-align: center;">N/A</td>
2367-<td class="working">Working ++</td>
2368-<td style="text-align: center;">N/A</td>
2369-<td class="working">Working</td>
2370-<td class="not working">Not working</td>
2371-<td style="text-align: center;">N/A</td>
2372-<td style="text-align: center;">N/A</td>
2373-</tr>
2374-<tr>
2375-<td>Wikitable files (Mediawiki)</td>
2376-<td style="text-align: center;">No</td>
2377-<td style="text-align: center;">Yes</td>
2378-<td style="text-align: center;">planned</td>
2379-<td class="working">Working ++</td>
2380-<td class="working">Working ++</td>
2381-<td class="working">Working ++</td>
2382-<td style="text-align: center;">N/A</td>
2383-<td style="text-align: center;">N/A</td>
2384-<td style="text-align: center;">N/A</td>
2385-<td class="working">Working ++</td>
2386-<td style="text-align: center;">N/A</td>
2387-<td style="text-align: center;">N/A</td>
2388-<td class="not working">Not working</td>
2389-<td style="text-align: center;">N/A</td>
2390-<td style="text-align: center;">N/A</td>
2391-</tr>
2392-</tbody>
2393-</table>
2394-
2395-(+) Depends on file.\
2396-(++) No "true" number format support because the file does not containg number formatting information. But the number format currently used in the spreadsheet understood.\
2397-(+++) Only very basic image support: no transformations, no cropping, no image manipulation.\
2398-(++++) Extended OOXML formatting options not supported.\
2399-(*) In formats which don't support Unicode the data is stored by default as ISO 8859-1 (Latin 1). You can change the encoding in TsWorkbook.Encoding. Note that FPSpreadsheet offers UTF-8 read and write routines, but the data might be converted to ISO when reading or writing to the disk. Be careful that characters which don't fit selected encoding will be lost in those operations. The remarks here are only valid for formats which don't support Unicode.\
2400-(**) Some cell could be returned blank due to missing or non ready implemented number and text formats.\
2401-(***) This is the format in which the formulas are written to file (determined by design of the file format).\
2402-(****) Writing of all formats is supported. Some rare custom formats, however, may not be recognized correctly. BIFF2 supports only built-in formats by design.
2403-
2404-### Progress of the formatting options
2405-
2406-The following formatting options are available:
2407-
2408-<table>
2409-<thead>
2410-<tr>
2411-<th>Format</th>
2412-<th>Text<br />
2413-alignment</th>
2414-<th>Text<br />
2415-rotation</th>
2416-<th>    Font    </th>
2417-<th>Rich<br />
2418-text</th>
2419-<th>  Border  </th>
2420-<th>Color<br />
2421-support</th>
2422-<th>Back<br />
2423-ground</th>
2424-<th>Word<br />
2425-wrap</th>
2426-<th>Col&amp;Row<br />
2427-size</th>
2428-<th>Number<br />
2429-format</th>
2430-<th>Merged<br />
2431-cells</th>
2432-<th>Page<br />
2433-layout</th>
2434-<th>Print<br />
2435-ranges</th>
2436-<th>Header/footer<br />
2437-images</th>
2438-<th>Column/row<br />
2439-format</th>
2440-<th>Hide<br />
2441-cols/rows</th>
2442-<th>Page<br />
2443-breaks</th>
2444-</tr>
2445-</thead>
2446-<tbody>
2447-<tr>
2448-<td>CSV files</td>
2449-<td style="text-align: center;">N/A</td>
2450-<td style="text-align: center;">N/A</td>
2451-<td style="text-align: center;">N/A</td>
2452-<td style="text-align: center;">N/A</td>
2453-<td style="text-align: center;">N/A</td>
2454-<td style="text-align: center;">N/A</td>
2455-<td style="text-align: center;">N/A</td>
2456-<td style="text-align: center;">N/A</td>
2457-<td style="text-align: center;">N/A</td>
2458-<td style="text-align: center;">N/A</td>
2459-<td style="text-align: center;">N/A</td>
2460-<td style="text-align: center;">N/A</td>
2461-<td style="text-align: center;">N/A</td>
2462-<td style="text-align: center;">N/A</td>
2463-<td style="text-align: center;">N/A</td>
2464-<td style="text-align: center;">N/A</td>
2465-<td style="text-align: center;">N/A</td>
2466-</tr>
2467-<tr>
2468-<td>Excel 2.x</td>
2469-<td class="working">Working *</td>
2470-<td style="text-align: center;">N/A</td>
2471-<td class="working">Working</td>
2472-<td style="text-align: center;">N/A</td>
2473-<td class="working">Working</td>
2474-<td class="working">Working</td>
2475-<td class="working">Working**</td>
2476-<td style="text-align: center;">N/A</td>
2477-<td class="working">Working</td>
2478-<td class="working">Working</td>
2479-<td style="text-align: center;">N/A</td>
2480-<td class="working">Working</td>
2481-<td style="text-align: center;">N/A</td>
2482-<td style="text-align: center;">N/A</td>
2483-<td class="working">Working</td>
2484-<td style="text-align: center;">N/A</td>
2485-<td class="working">Working</td>
2486-</tr>
2487-<tr>
2488-<td>Excel 5.0<br />
2489-(Excel 5.0 and 95)</td>
2490-<td class="working">Working</td>
2491-<td class="working">Working</td>
2492-<td class="working">Working</td>
2493-<td class="working">Working</td>
2494-<td class="working">Working</td>
2495-<td class="working">Working</td>
2496-<td class="working">Working</td>
2497-<td class="working">Working</td>
2498-<td class="working">Working</td>
2499-<td class="working">Working</td>
2500-<td style="text-align: center;">N/A</td>
2501-<td class="working">Working</td>
2502-<td class="working">Working</td>
2503-<td style="text-align: center;">N/A</td>
2504-<td class="working">Working</td>
2505-<td class="working">Working</td>
2506-<td class="working">Working</td>
2507-</tr>
2508-<tr>
2509-<td>Excel 8.0<br />
2510-(Excel 97 - XP)</td>
2511-<td class="working">Working</td>
2512-<td class="working">Working</td>
2513-<td class="working">Working</td>
2514-<td class="working">Working</td>
2515-<td class="working">Working</td>
2516-<td class="working">Working</td>
2517-<td class="working">Working</td>
2518-<td class="working">Working</td>
2519-<td class="working">Working</td>
2520-<td class="working">Working</td>
2521-<td class="working">Working</td>
2522-<td class="working">Working</td>
2523-<td class="working">Working</td>
2524-<td class="not working">Not working</td>
2525-<td class="working">Working</td>
2526-<td class="working">Working</td>
2527-<td class="working">Working</td>
2528-</tr>
2529-<tr>
2530-<td>Excel 2003/XML</td>
2531-<td class="working">Working</td>
2532-<td class="working">Working</td>
2533-<td class="working">Working</td>
2534-<td class="working">Working</td>
2535-<td class="working">Working</td>
2536-<td class="working">Working</td>
2537-<td class="working">Working</td>
2538-<td class="working">Working</td>
2539-<td class="working">Working</td>
2540-<td class="working">Working</td>
2541-<td class="working">Working</td>
2542-<td class="working">Working</td>
2543-<td class="working">Working</td>
2544-<td style="text-align: center;">N/A</td>
2545-<td class="working">Working</td>
2546-<td class="working">Wworking</td>
2547-<td class="working">Working</td>
2548-</tr>
2549-<tr>
2550-<td>Excel OOXML (xlsx)</td>
2551-<td class="working">Working</td>
2552-<td class="working">Working</td>
2553-<td class="working">Working</td>
2554-<td class="working">Working</td>
2555-<td class="working">Working</td>
2556-<td class="working">Working</td>
2557-<td class="working">Working</td>
2558-<td class="working">Working</td>
2559-<td class="working">Working</td>
2560-<td class="working">Working</td>
2561-<td class="working">Working</td>
2562-<td class="working">Working</td>
2563-<td class="working">Working</td>
2564-<td class="working">Working</td>
2565-<td class="working">Working</td>
2566-<td class="working">Working</td>
2567-<td class="working">Working</td>
2568-</tr>
2569-<tr>
2570-<td>OpenDocument</td>
2571-<td class="working">Working</td>
2572-<td class="working">Working</td>
2573-<td class="working">Working</td>
2574-<td class="working">Working</td>
2575-<td class="working">Working</td>
2576-<td class="working">Working</td>
2577-<td class="working">Working***</td>
2578-<td class="working">Working</td>
2579-<td class="working">Working</td>
2580-<td class="working">Working</td>
2581-<td class="working">Working</td>
2582-<td class="working">Working</td>
2583-<td class="working">Working</td>
2584-<td class="working">Working</td>
2585-<td class="working">Working</td>
2586-<td class="working">Working</td>
2587-<td></td>
2588-</tr>
2589-<tr>
2590-<td>HTML (+)</td>
2591-<td class="working">Working</td>
2592-<td class="not working">bugs</td>
2593-<td class="working">Working</td>
2594-<td class="working">Working</td>
2595-<td class="not working">bugs</td>
2596-<td class="working">Working</td>
2597-<td class="working">Working ****</td>
2598-<td class="partial">Writing only</td>
2599-<td class="partial">Writing only</td>
2600-<td style="text-align: center;">N/A</td>
2601-<td class="working">Working</td>
2602-<td style="text-align: center;">N/A</td>
2603-<td style="text-align: center;">N/A</td>
2604-<td class="not working">Not working</td>
2605-<td class="partial">Writing only</td>
2606-<td class="not working">to be done</td>
2607-<td style="text-align: center;">N/A</td>
2608-</tr>
2609-<tr>
2610-<td>Wikitable (Mediawiki)</td>
2611-<td class="partial">Writing only</td>
2612-<td style="text-align: center;">N/A</td>
2613-<td class="partial">Writing only</td>
2614-<td class="not working">Not working</td>
2615-<td class="partial">Writing only</td>
2616-<td class="partial">Writing only</td>
2617-<td></td>
2618-<td class="partial">Writing only</td>
2619-<td class="partial">Writing only</td>
2620-<td style="text-align: center;">N/A</td>
2621-<td class="partial">Writing only</td>
2622-<td style="text-align: center;">N/A</td>
2623-<td style="text-align: center;">N/A</td>
2624-<td class="not working">Not working</td>
2625-<td class="partial">Writing only</td>
2626-<td class="not working">to be done</td>
2627-<td style="text-align: center;">N/A</td>
2628-</tr>
2629-<tr>
2630-<td></td>
2631-<td></td>
2632-<td></td>
2633-<td></td>
2634-<td></td>
2635-<td></td>
2636-<td></td>
2637-<td></td>
2638-<td></td>
2639-<td></td>
2640-<td></td>
2641-<td></td>
2642-<td></td>
2643-<td></td>
2644-<td></td>
2645-<td></td>
2646-<td></td>
2647-<td></td>
2648-</tr>
2649-</tbody>
2650-</table>
2651-
2652-(N/A) Feature is not available for this format intrinsically.\
2653-(*) BIFF2 supports only horizontal text alignment, vertical alignment is ignored.\
2654-(**) BIFF2 does not support a background color; a dotted black&white background is used instead.\
2655-(***) OpenDocument supports only uniform backgrounds; a fill color interpolated between foreground and background colors is written instead.\
2656-(****) Only uniform background color, no fill styles.\
2657-(+) HTML reader does not support styles. Since the writer does use styles these files are not read back correctly.
2658-
2659-### Progress of workbook/worksheet user-interface options
2660-
2661-Some additional options were added to interface the file contents with the `TsWorksheetGrid`:
2662-
2663-| Format | Hide grid lines | Hide headers | Frozen Panes | Active sheet/cell | Zooming | BiDi mode | Tab color |
2664-|----|----|----|----|----|----|----|----|
2665-| Excel 2.x | Working | Working | not working | N/A | N/A | N/A | N/A |
2666-| Excel 5.0 (Excel 5.0 and 95) | Working | Working | Working | Working | Working | N/A | N/A |
2667-| Excel 8.0 (Excel 97 - XP) | Working | Working | Working | Working | Working | Working | Working |
2668-| Excel2003/XML | Working | Working | Working | Working | Working \|\| class="working\|Working | N/A | |
2669-| Excel OOXML | Working | Working | Working | Working | Working | Working | Working |
2670-| OpenDocument | Working | Working | Working | Working | Working | Working | Working |
2671-| HTML | Writing only | Writing only | N/A | N/A | N/A | not working | N/A |
2672-
2673-### To do list
2674-
2675-Note: this list is provisional, maintained by developers and can change without notice. If you are interested in contributing, please feel free to get in touch and submit a patch - thanks!
2676-
2677-- Find out why BIFF2 files are corrupt when saved with frozen rows/cols activated.
2678-- <s>Add row and column formats</s>
2679-- Add reading support for wikitable (Mediawiki) files
2680-- xls reader crashes for some incorrectly written xls files (which Excel can read), see [<http://forum.lazarus.freepascal.org/index.php/topic,25624.0.html>](http://forum.lazarus.freepascal.org/index.php/topic,25624.0.html).
2681-- <s>Improve color support: due to palette support colors may change from file to file currently.</s>
2682-- Add embedded images.
2683-- Fix writing of cell comments to BIFF8 files.
2684-
2685-**Long-term:**
2686-
2687-- Provide a more common user interface to fpspreadsheet (setter/getter and properties instead of Read*/Write* methods, MyWorksheet.Cells\[ARow, ACol\]), make TCell a class, avoid the pointers PCell.
2688-- <s>Store formatting in a format list of the workbook, not in the cell, to reduce memory usage.</s>
2689-- Use BIFF8 file-wide string storage instead of storing strings in cells (should reduce memory usage in case of many duplicate strings)
2690-- Redo ooxml and ods readers based upon SAX/TXmlReader instead of DOM to reduce memory usage of large files.
2691-- <s>Add an fpspreadsheetexport unit and component on "Data Export" tab similar to [[fpdbfexport]] FPSpreadsheetexport demo preferably with all export formats component.</s> Find a way to register export format to all formats (look into how lazreport pdf export performs a similar procedure).
5+![](/wiki-images/b/b7/Fpsgrid.png)
6+
7+## Documentation
8+
9+This wiki page covers the latest development/trunk version of FPSpreadsheet available via subversion. Please see section Stable releases for documentation on the stable version that you can download.
10+
11+## API Documentation
12+
13+### API Reference
14+
15+A help file in CHM format can be found in the FPSpreadsheet installation folder *docs*. If you did not yet install the package follow [<http://lazarus-ccr.svn.sourceforge.net/viewvc/lazarus-ccr/components/fpspreadsheet/docs/fpspreadsheet-api.chm>](http://lazarus-ccr.svn.sourceforge.net/viewvc/lazarus-ccr/components/fpspreadsheet/docs/fpspreadsheet-api.chm) to *fpspreadsheet-api.chm*.
16+
17+The second CHM file available in the folder *docs*, *fpspreadsheet-wiki.chm*, is a snapshot of the FPSpreadsheet-related wiki pages bundled into a single help file.
18+
19+### Basics
20+
21+The smallest entities in a spreadsheet are the **cells** which contain the data. Cells can hold various data types, like strings, numbers, dates, times, boolean values, or formulas. In addition, cells can contain information on formatting, i.e. font style, background color, text alignment etc.
22+
23+The cells are arranged in a grid-like structure, called **worksheet**, or **spreadsheet**, consisting of **rows** and **columns**. Each cell has a unique address given by the row and column index.
24+
25+Worksheets are bound together to form a **workbook** which represents the document of the spreadsheet application. The workbook also stores information that is needed from all worksheets, i.e. font list, cell and number format lists, etc.
26+
27+FPSpreadsheet follows this same structure - there is a `TCell`, a `TsWorksheet`, and a `TsWorkbook`.
28+
29+#### Workbook
30+
31+The class `TsWorkbook` is the main class visible to the user. It provides methods for reading data from and writing to files. The versatile structure of the library provides access to various popular file formats, like Excel *.xls* or *.xlsx*, or OpenOffice/LibreOffice *.ods*.
32+
33+The file format is specified by the type `TsSpreadsheetFormat` defined in the unit `fpstypes`
34+
35+``` pascal
36+type
37+ TsSpreadsheetFormat = (sfExcel2, sfExcel5, sfExcel8, sfExcelXML, sfOOXML,
38+ sfOpenDocument, sfCSV, sfHTML, sfWikiTable_Pipes, sfWikiTable_WikiMedia, sfUser);
39+```
40+
41+where
42+
43+- `sfExcel2, sfExcel5, sfExcel8` stands for versions of the binary xls format used by Excel ("BIFF" = "Binary Interchange File Format") with `sfExcel8` being the most modern one.
44+- `sfOOXML` corresponds to the newer xlsx format introduced by Excel2007
45+- `sfExcelXML` is the xml format which was introduced by Microsoft for Office XP and 2003. Not very popular.
46+- `sfOpenDocument` is the spreadsheet format used by OpenOffice/LibreOffice; by default, the files have the extension *.ods*.
47+- `sfCSV` refers to comma-delimited text files (default extension *.csv*); they can be understood by any text editor and all spreadsheet programs, but do not contain formatting information.
48+- `sfHTML` denotes the standard HTML format as used in web browsers.
49+- `sfWikiTable_Pipes` and `sfWikiTable_WikiMedia` is the format used by tables in wiki websites.
50+- `sfUser` is needed to register a user-defined format. There are no plans to implement "ancient" file formats like Excel3.0/4.0 or Lotus. It is possible, however, to provide your own reading and writing classes to extend the functionality of FPSpreadsheet - see the section below on Adding new file formats
51+
52+When applying fpspreadsheet the first task is to create an instance of the workbook:
53+
54+``` pascal
55+var
56+ MyWorkbook: TsWorkbook;
57+begin
58+ MyWorkbook := TsWorkbook.Create;
59+ ...
60+```
61+
62+Reading of spreadsheet files is accomplished (among others) by the workbook methods
63+
64+- `procedure ReadFromFile(AFileName: string):`\
65+ Reads the file with the given name and automatically determines the correct file format.
66+- `procedure ReadFromFile(AFileName: string; AFormat: TsSpreadsheetFormat):`\
67+ Reads the file, but assumes that the file format is as specified by `AFormat`.
68+
69+The following workbook methods can be used for saving to file:
70+
71+- `procedure WriteToFile(const AFileName: string; const AFormat: TsSpreadsheetFormat; const AOverwriteExisting: Boolean = False)`:\
72+ Writes the workbook to the given file using the given spreadsheet format. If the file already exists it is automatically overwritten if `AOverwriteExisting` is `true`:
73+- `procedure WriteToFile(const AFileName: String; const AOverwriteExisting: Boolean = False)`:\
74+ ditto, but the file format is determined from the file extension provided (in case of Excel's xls the most recent version, `sfExcel8`, is used).
75+
76+After calling these methods it is advantageous to look at the workbook's property `ErrorMsg` in which messages due to errors or warnings are collected that might have occured during reading/writing. This property returns a multi-lined string which is displayed best in a memo component; if everything was fine it is an empty string.
77+
78+Note: FPSpreadsheets provides specialized units for reading from and writing to each file format. These units are not available automatically, you have to add them to the uses clause explicitly. FPSpreadsheet will complain about "unsupported file format" if the requested reader/writer is not found. Here is a list of the unit names:
79+
80+- *xlsbiff2*, *xlsbiff5* and *xlsbiff8* for the binary xls file formats `sfExcel2`, `sfExcel5` and `sfExcel8`, respectively,
81+- *xlsxOOXML* for the xlsx file format `sfOOXML` of Excel 2007 and later,
82+- *xlsXML* for the xml format of Excel XP and 2003,
83+- *fpsopendocument* for the file format `sfOpenDocument` of OpenOffice/LibreOffice,
84+- *fpsCSV* for text files with comma-separated values (csv),
85+- *fpsHTML* for HTML files,
86+- *wikitables* for `sfWikiTable_Pipes` and `sfWikiTable_WikiMedia`,
87+- or, simply add *fpsallformats* to get read/write support for all file formats supported.
88+
89+#### Worksheet
90+
91+The workbook contains a list of `TsWorksheet` instances. They correspond to the tabs that you see in Excel or Open/LibreOffice. When reading a spreadsheet file the worksheets are created automatically according to the file contents. When a spreadsheet is created manually to be stored on file a worksheet has to be created by *adding* it to the workbook:
92+
93+``` pascal
94+var
95+ MyWorkbook: TsWorkbook;
96+ MyWorksheet: TsWorksheet;
97+begin
98+ MyWorkbook := TsWorkbook.Create;
99+ MyWorksheet := MyWorkbook.AddWorksheet('My_Table');
100+ // 'My_Table' is the "name" of the worksheet
101+ ...
102+```
103+
104+Already existing worksheets can be accessed by using the `TsWorkbook` methods
105+
106+- `function GetFirstWorksheet: TsWorksheet`: retrieves the first worksheet of the workbook.
107+- `function GetWorksheetByIndex(AIndex: Cardinal): TsWorksheet`: returns the worksheet with the given index (starting at 0).
108+- `function GetWorksheetByName(AName: String): TsWorksheet`: returns the worksheet with the given name which was used when the worksheet was added.
109+
110+The count of already existing worksheets can be queried by calling `GetWorksheetCount`.
111+
112+#### Cell
113+
114+The worksheet, finally, gives access to the cells. A newly created worksheet, as in above example, is empty and does not contain any cells. Cells are added by assigning data or attributes to them by one of the `WriteXXXX` methods of the worksheet. As already mentioned, a cell is addressed by the index of the row and column to which it belongs. As usual, row and column indexes start at 0. Therefore, cell "A1" belongs to row 0 and column 0. It should be noted that row and column index are always specified in this order, this is *different from the convention of*`TStringGrid`. The following example creates a cell at address A1 and puts the number `1.0` in it.
115+
116+``` pascal
117+var
118+ MyWorkbook: TsWorkbook;
119+ MyWorksheet: TsWorksheet;
120+begin
121+ MyWorkbook := TsWorkbook.Create;
122+ MyWorksheet := MyWorkbook.AddWorksheet('My_Table');
123+ MyWorksheet.WriteNumber(0, 0, 1.0); // "A1" has row=0 and col=0
124+ ...
125+```
126+
127+It is also possible to access cells directly by means of the methods `FindCell(ARow, ACol)` or `GetCell(ARow, ACol)` of the workbook. Both funtions exist also in an overloaded version to which the cell address can be passed in Excel notation: `FindCell(ACellStr: String)` or `GetCell(ACellStr: String)`. Please be aware that these functions return a `pointer` to the cell data (type `PCell`). Don't forget to dereference the pointers! The difference between `FindCell` and `GetCell` is that the former one returns `nil`, if a cell does not yet exist, while the latter one creates an empty cell in this case.
128+
129+``` pascal
130+if MyWorksheet.FindCell('A1') = nil then
131+ WriteLn('Cell A1 does not exist.');
132+```
133+
134+##### The basic TCell record
135+
136+This is the declaration of the cell's data type:
137+
138+``` pascal
139+type
140+ TCell = record
141+ { Location of the cell }
142+ Worksheet: TsWorksheet;
143+ Col: Cardinal; // zero-based
144+ Row: Cardinal; // zero-based
145+
146+ { Index of format record }
147+ FormatIndex: Integer;
148+
149+ { Status flags }
150+ Flags: TsCellFlags; // (cfHasComment, cfMerged, cfHyperlink, ...)
151+
152+ { Cell content }
153+ UTF8StringValue: String; // strings cannot be part of a variant record
154+ case ContentType: TCellContentType of // must be at the end of the declaration
155+ cctEmpty : (); // has no data at all
156+ cctFormula : (); // UTF8StringValue is outside the variant record
157+ cctNumber : (Numbervalue: Double);
158+ cctUTF8String : (); // FormulaValue is outside the variant record
159+ cctDateTime : (DateTimevalue: TDateTime);
160+ cctBool : (BoolValue: boolean);
161+ cctError : (ErrorValue: TsErrorValue);
162+ end;
163+ PCell = ^TCell;
164+```
165+
166+The field `ContentType` indicates which data type is stored in the cell:
167+
168+``` pascal
169+type
170+ TCellContentType = (cctEmpty, cctFormula, cctNumber, cctUTF8String, cctDateTime, cctBool, cctError);
171+```
172+
173+According to this field the corresponding data can be found in the fields
174+
175+- `NumberValue` (for `ContentType=cctNumber`), or
176+- `UTF8StringValue` (for `ContentType=cctUTF8String`), or
177+- `DateTimeValue` (for `ContentType=cctDateTime`), or
178+- `BoolValue` (for `ContentType=cctBool`), i.e. `TRUE` or `FALSE`, or
179+- `ErrorValue` (for `ContentType=cctError`).
180+
181+Due to usage of a variant record most of these values are overlapping, i.e. modification of `NumberValue` affects also the other values. Therefore, always respect the `ContentType` when accessing the `TCell` record directly (the worksheet methods discussed below consider this automatically).
182+
183+The field `Flags` tells whether additional data are associated with the cell which are not included in the cell record usually to save memory:
184+
185+``` pascal
186+type
187+ TsCellFlag = (cfHasComment, cfHyperlink, cfMerged, cfHasFormula, cf3dFormula);
188+ TsCellFlags = set of TsCellFlag;
189+```
190+
191+- `cfHasComment`: A comment record can be found in the `Comments` of the worksheet.
192+- `cfHyperlink`: The cell is contains a hyperlink stored in the `Hyperlinks` of the worksheet.
193+- `cfMerged`: The cell belongs to a merged block and extends across several cells.
194+- `cfHasFormula`: The cell is associated with a formula which is stored in the `Formulas` of the worksheet.
195+- `cf3dFormula`: The formula associated with the cell contains elements referencing other sheets of the same workbook.
196+
197+> **Note:** After calculation of a formula or after reading of a file, the `ContentType` of the formula cell is converted to that of the result. Then the presence of a formula can only be detetected by calling the function `HasFormula(cell)` for the cell to be queried (`cell: PCell`) in unit *fpsUtils*; this function checks the presence of the element `cfHasFormula` in the cell flags.
198+
199+##### How to add and read data to/from a cell
200+
201+Adding values to a cell is most easily accompished by using one of the `WriteXXXX` methods of the worksheet. The most important ones are:
202+
203+``` pascal
204+type
205+ TsWorksheet = class
206+ ...
207+ { Writing of currency values }
208+ function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
209+ ANumFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = 2;
210+ ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
211+ ANegCurrFormat: Integer = -1): PCell; overload;
212+ procedure WriteCurrency(ACell: PCell; AValue: Double;
213+ ANumFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = -1;
214+ ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
215+ ANegCurrFormat: Integer = -1); overload;
216+ function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
217+ ANumFormat: TsNumberFormat; ANumFormatString: String): PCell; overload;
218+ procedure WriteCurrency(ACell: PCell; AValue: Double;
219+ ANumFormat: TsNumberFormat; ANumFormatString: String); overload;
220+
221+ { Writing of date/time values }
222+ function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime): PCell; overload;
223+ procedure WriteDateTime(ACell: PCell; AValue: TDateTime); overload;
224+ function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
225+ ANumFormat: TsNumberFormat; ANumFormatStr: String = ''): PCell; overload;
226+ procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
227+ ANumFormat: TsNumberFormat; ANumFormatStr: String = ''); overload;
228+ function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
229+ ANumFormatStr: String): PCell; overload;
230+ procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
231+ ANumFormatStr: String); overload;
232+
233+ { Writing of number values }
234+ function WriteNumber(ARow, ACol: Cardinal; ANumber: double): PCell; overload;
235+ procedure WriteNumber(ACell: PCell; ANumber: Double); overload;
236+ function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
237+ ANumFormat: TsNumberFormat; ADecimals: Byte = 2): PCell; overload;
238+ procedure WriteNumber(ACell: PCell; ANumber: Double;
239+ ANumFormat: TsNumberFormat; ADecimals: Byte = 2); overload;
240+ function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
241+ ANumFormat: TsNumberFormat; ANumFormatString: String): PCell; overload;
242+ procedure WriteNumber(ACell: PCell; ANumber: Double;
243+ ANumFormat: TsNumberFormat; ANumFormatString: String); overload;
244+
245+ { Writing of string values }
246+ function WriteText(ARow, ACol: Cardinal; AText: ansistring;
247+ ARichTextParams: TsRichTextParams = nil): PCell; overload;
248+ procedure WriteText(ACell: PCell; AText: String;
249+ ARichTextparams: TsRichTextParams = nil); overload;
250+
251+ // the old string methods "WriteUTF8Text" are deprecated now
252+ ...
253+```
254+
255+Some of these methods exist in overloaded versions in which cell formatting parameters can be added together with the cell value. Correspondingly to writing, there is also a number of `worksheet` methods for reading the cell values:
256+
257+``` pascal
258+type
259+ TsWorksheet = class
260+ ...
261+ { Reading cell content as a string }
262+ function ReadAsText(ARow, ACol: Cardinal): string; overload;
263+ function ReadAsText(ACell: PCell): string; overload;
264+ function ReadAsText(ACell: PCell; AFormatSettings: TFormatSettings): string; overload;
265+
266+ { Reading cell content as a number }
267+ function ReadAsNumber(ARow, ACol: Cardinal): Double; overload;
268+ function ReadAsNumber(ACell: PCell): Double; overload;
269+ function ReadNumericValue(ACell: PCell; out AValue: Double): Boolean;
270+
271+ { Reading cell content as a date/time value }
272+ function ReadAsDateTime(ARow, ACol: Cardinal; out AResult: TDateTime): Boolean; overload;
273+ function ReadAsDateTime(ACell: PCell; out AResult: TDateTime): Boolean; overload;
274+ ...
275+```
276+
277+##### Index to Cell format
278+
279+`FormatIndex` is the index of the cell format record. It describes the formatting attributes of a cell. These records are collected by an internal list of the workbook and are defined like this:
280+
281+``` pascal
282+type
283+ TsCellFormat = record
284+ FontIndex: Integer;
285+ TextRotation: TsTextRotation;
286+ HorAlignment: TsHorAlignment;
287+ VertAlignment: TsVertAlignment;
288+ Border: TsCellBorders;
289+ BorderStyles: TsCellBorderStyles;
290+ Background: TsFillPattern;
291+ NumberFormatIndex: Integer;
292+ NumberFormat: TsNumberFormat;
293+ NumberFormatStr: String;
294+ BiDiMode: TsBiDiMode; // bdDefault, bdLTR {left-to-right}, bdRTL {right-to-left)
295+ Protection: TsCellProtection; // cpLockCell, cpHideFormulas
296+ UsedFormattingFields: TsUsedFormattingFields;
297+ //uffTextRotation, uffFont, uffBold, uffBorder, uffBackground, uffNumberFormat, uffWordWrap, uffHorAlign, uffVertAlign, uffBiDi, uffProtection, uffDoNotPrint
298+ end;
299+```
300+
301+- `FontIndex`: text font by specifying the index in the workbook's font list
302+- `TextRotation`: specifies whether the cell text is written horizontally or vertically
303+- `HorAlignment`: left-aligned, horizontally centered, or right-aligned text
304+- `VertAlignment`: top, bottom or vertically centered text
305+- `Border`: a set of flags indicating that - if set - a border line is drawn at the left, top, right, or bottom cell edge. The lines are drawn according to the `BorderStyles` which define the linestyle and color of the border.
306+- `Background`: a record defining the background fill of a cell (pattern style, pattern color, and background color - see chapter on cell background below).
307+- `NumberFormat` and `NumberFormatStr` specify how number or date/time values are formatted (e.g., number of decimal places, long or short date format, etc.).
308+- Only those format attributes for which a flag is set in the `UsedFormattingFields` are considered when formatting a cell. If a flag is not included then the corresponding attribute is ignored and replaced by its default value.
309+
310+For specifying a format for a given cell call the corresponding the worksheet method `WriteXXXX`, for retrieving a format call `ReadXXXX`. These methods usually get a pointer to the cell as a parameter, but there are also overloaded versions which accept the row and column index. Moreover, formatting styles can also be applied directly to the cell by using a record helper implemented in unit *fpsCell*.
311+
312+See cell formatting below for a more detailed description.
313+
314+#### Columns and rows
315+
316+Column and row records are added for each column and row having a non-default properties:
317+
318+``` pascal
319+type
320+ TCol = record
321+ Col: Cardinal;
322+ Width: Single;
323+ ColWidthType: TsColWidthType; // = (cwtDefault, cwtCustom)
324+ FormatIndex: Integer;
325+ Options: TsColRowOptions; // set of [croHidden, croPageBreak]
326+ end;
327+ PCol = ^TCol;
328+
329+ TRow = record
330+ Row: Cardinal;
331+ Height: Single;
332+ RowHeightType: TsRowHeightType; // = (rhtDefault, rhtCustom, rhtAuto)
333+ FormatIndex: Integer;
334+ Options: TsColRowOptions; // set of [croHidden, croPageBreak]
335+ Hidden: Boolean;
336+ PageBreak: Boolean;
337+ end;
338+ PRow = ^TRow;
339+```
340+
341+##### Column width / row height
342+
343+**Column widths** and **row heights** can be specified in a variety of units defined by the type `TsSizeUnits = (suChars, suLines, suMillimeters, suCentimeters, suPoints, suInches)`. `suChars` refers to the count of `0` characters fitting into the column width - this is the way how Excel defines column widths. `suLines` is the number of lines fitting into the row height. Both units are based on the character size of the workbook's default font. The other units are conventional physical length units (1 cm = 10 mm, 1 inch = 25.4 mm = 72 pt). Fractional values are accepted. The workbook and worksheets store lengths internally in millimeters (`MyWorkbook.Units`).
344+
345+The Office applications usually adjust the row heights automatically according to the font or text rotation of the cell content. This case is identified by `RowHeightType` having the value `rhtAuto`. Since the worksheet cannot calculate text size very accurately automatic row heights are not written by FPSpreadsheet; they are replaced by the **default row height**. The default row height is also used if a row is empty, i.e. does not contain any data cells. Its value can be changed by calling the worksheet's `WriteDefaultRowHeight()` or by using the worksheet property `DefaultRowHeight`. In `WriteDefaultRowHeight`, the units must be specified while in `DefaultRowHeight` they are assumed to be lines. Similarly, the **default column width** can be specified by `WriteDefaultColWidth()` or the property `DefaultColWidth` (in characters).
346+
347+In order to overrun automatic and default row heights call the worksheet method `WriteRowHeight()`. These row records are identified by `RowHeightType` having the value `rhtCustom`. In the same way the width of columns can be set to a specific value by calling `WriteColWidth()`. `ColWidthType` of these columns is `cwtCustom`.
348+
349+The height/width of a particular row/column can be retrieved by means of the methods `GetRowHeight` or `GetColWidth`. Note that these methods return the default row heights/column widths if there are no `TRow`/`TCol` records.
350+
351+``` pascal
352+type TsWorksheet = class
353+ ...
354+ { Set row height }
355+ procedure WriteRowHeight(ARowIndex: Cardinal; AHeight: Single; AUnits: TsSizeUnits);
356+ { Set column width }
357+ procedure WriteColWidth(AColIndex: Cardinal; AWidth: Single; AUnits: TsSizeUnits);
358+ { Set default row height }
359+ procedure WriteDefaultRowHeight(AHeight: Single; AUnits: TsSizeUnits);
360+ {Set default cokumn width }
361+ procedure WriteDefaultColWidth(AWidth: Single; AUnits: TsSizeUnits);
362+
363+ { Return row height }
364+ function GetRowHeight(ARowIndex: Cardinal; AUnits: TsSizeUnits): Single;
365+ { Return column width }
366+ function GetColWidth(AColIndex: Cardinal; AUnits: TsSizeUnits): Single;
367+ { Return default row height }
368+ function ReadDefaultRowHeight(AUnits: TsSizeUnits): Single;
369+ { Return default column width }
370+ function ReadDefaultColWidth(AUnits: TsSizeUnits): Single;
371+
372+ property DefaultRowHeight: Single; // in lines
373+ property DefaultColWidht: Single; // in characters
374+```
375+
376+There are also overloaded versions of these methods which do not require the `AUnits` parameter. In this case, row heights are defined in terms of line count, and column widths are defined in terms of character count. Note that these variants are from previos versions and are deprecated now.
377+
378+##### Column and row formats
379+
380+The `FormatIndex` element of the row and column records format applied to the entire row or column. Together with cells, these formats are stored as `TsCellFormat` records in an internal workbook list, `FormatIndex` is the index of the format properties into this list. See details in section Cell formatting. **Row and column formats** are primarily applied to empty cells, but if a new cell is added it will automatically get the format of the row or column. (If both row and column have different formats then the row format will be used).
381+
382+Here is a listing of the worksheet methods available for column and row formatting:
383+
384+``` Pascal
385+type TsWorksheet = class
386+ // Assign a format to a column or row
387+ procedure WriteColFormatIndex(ACol: Cardinal; AFormatIndex: Integer);
388+ procedure WriteRowFormatIndex(ARow: Cardinal; AFormatIndex: Integer);
389+
390+ // Query the format of a column or row
391+ function GetColFormatIndex(ACol: Cardinal): Integer;
392+ function GetRowFormatIndex(ARow: Cardinal): Integer;
393+
394+ // Returns the font assigned to a column or row
395+ function ReadColFont(ACol: PCol): TsFont;
396+ function ReadRowFont(ARow: PRow): TsFont;
397+
398+ // Check whether any column or row uses a special format
399+ function HasRowFormats: Boolean;
400+ function HasColFormats: Boolean;
401+```
402+
403+##### Hidden columns / rows
404+
405+Adding the flag `croHidden` to the row's or column's `Options` hides the row or column in the Office application (or in TsWorksheetGrid). The following worksheet methods are helpers to handle **row/column visibility**:
406+
407+``` pascal
408+type TsWorksheet = class
409+ ...
410+ { Hide column/row }
411+ procedure HideCol(ACol: Cardinal);
412+ procedure HideRow(ARow: Cardinal);
413+
414+ { Show a previously hidden column/row }
415+ procedure ShowCol(ACol: Cardinal);
416+ procedure ShowRow(ARow: Cardinal);
417+
418+ { Check whether column/row is hidden }
419+ function ColHidden(ACol: Cardinal): Boolean;
420+ function RowHidden(ARow: Cardinal): Boolean;
421+```
422+
423+##### Page breaks
424+
425+The flag `croPageBreak` can be added to the row's or column's `Options` in order to force a **page break** before the corresponding row or column when the worksheet is printed by the Office applications. Note that FPSpreadsheet itself does not support printing. The following worksheet methods help with page breaks:
426+
427+``` pascal
428+type TsWorksheet = class
429+ ...
430+ { Enforce a page break before the specified column/row }
431+ procedure AddPageBreakToCol(ACol: Cardinal);
432+ procedure AddPageBreakToRow(ARow: Cardinal);
433+
434+ { Removes a page break previously added to a column/row }
435+ procedure RemovePageBreakFromCol(ACol: Cardinal);
436+ procedure RemovePageBreakFromRow(ARow: Cardinal);
437+
438+ { Checks whether a page break is forced before the specified column/row }
439+ function IsPageBreakCol(ACol: Cardinal): Boolean;
440+ function IsPageBreakRow(ARow: Cardinal): Boolean;
441+```
442+
443+#### Events
444+
445+Worksheets and workbooks fire a series of events such as OnChangeCell, OnChangeFont, etc. The events usually are intended for interaction with the [[FPSpreadsheet tutorial: Writing a mini spreadsheet application|visual spreadsheet controls]]. If you need to attach your own handlers you should make sure that the original handler is called, at least in a gui program using the spreadsheet controls. Or you use the events provided by the visual controls themselves, e.g. [[TsWorksheetGrid|WorksheetGrid]]`.OnEditingDone` instead of `WorksheetGrid.Worksheet.OnChangeCell`.
446+
447+### Formulas
448+
449+Two kinds of formulas are supported by FPSpreadsheet:
450+
451+- **String formulas**: These are written in strings just like in the office applications, for example `"=ROUND(A1+B1,0)"`. They are used internally in the files of Open/LibreOffice and Excel *.xlsx*.
452+- **RPN formulas** are used internally by the binary *.xls* Excel files. They are written in Reverse Polish Notation (RPN), for example: `A1, B1, Add, 0, ROUND`. If a spreadsheet containing formulas is to be saved in a binary Excel format, the RPN formulas required are generated automatically.
453+
454+FPSpreadsheet can convert between string and rpn formulas. Formulas in both types can be calculated.
455+
456+In older versions of FPSpreadsheet, formulas were stored directly in the cell record. This was given up to have parsed formulas available for faster calculation. The formulas are stored in the tree `Formulas` of the worksheet. The formula record contains the row and column index of the cell to which the formula belongs, the string representation of the formula, as well as the parser tree for quick evaluation.
457+
458+FPSpreadsheet supports the majority of the formulas provided by the common spreadsheet applications. However, when reading a file created by these applications, there is always a chance that an unsupported formula is contained. To avoid crashing of fpspreadsheet, reading of formulas is disabled by default; the cell displays only the result of the formula written by the Office application. To activate reading of formulas add the element `boReadformulas` to the workbook's `Options` before opening the file. If an error occurs in this case the reader normally catches the exception, writes the exception message into the workbook's errorlog and continues reading. If you want reading to stop you must add the `boAbortReadingOnFormulaError` to the workbook `Options`.
459+
460+Formulas can link to data in other sheets of the same workbook ("3d formulas") by applying the Excel syntax (see below). External links to spreadsheets in other files are not supported.
461+
462+Calculation of formulas is normally not needed when a file is written by FPSpreadsheet for opening in an Office application because that automatically calculates the formula results. If the same file, however, is openend by an application based on FPSpreadsheet the calculated cells would be empty because the formulas are not automatically calculated by default. To activate calculation of formulas before writing a spreadsheet to file you have to add the option `boCalcBeforeSaving` to the workbook's `Options`.
463+
464+If FPSpreadshet is used in an interactive application (such as the *spready* demo found in the *examples* folder of the FPSpreadsheet installation) it is desirable to calculate formulas automatically whenever formula strings or cell values are changed by the user. This can be achieved by the option `boAutoCalc` in the workbook's `Options`.
465+
466+The most general setting regarding formulas, therefore, is
467+
468+``` pascal
469+ MyWorkbook.Options := MyWorkbook.Options + [boReadFormulas, boCalcBeforeSaving, boAutoCalc];
470+```
471+
472+Calculation of formulas can be triggered manually by calling the method `CalcFormulas` of the worksheet or workbook. The latter is absolutely required when the workbook contains 3d formulas where the result of one cell can affect cells in other sheets. If there are only within-sheet formulas then the worksheet's `CalcFormulas` is sufficient.
473+
474+#### String formulas
475+
476+String formulas are written in the same way as in the Office applications. The worksheet method for creating a string formula is `WriteFormula`:
477+
478+``` pascal
479+var
480+ MyWorksheet: TsWorksheet;
481+//...
482+ MyWorksheet.WriteFormula(0, 1, '=ROUND(A1+B2+1.215,0)');
483+ // By default, use dot as decimal and comma as list separator!
484+```
485+
486+A few notes on **syntax**:
487+
488+- The leading `=` character which identifies formulas in the Office applications is not absolutely necessary here and can be dropped. The formula is stored in the cell record without it.
489+- The case of the formula name is ignored.
490+- Spaces can be added for better readability, but they will be lost when saving.
491+- Strings must be enclosed in double quotes.
492+- The corner points of a cell range must be separated by a colon (":"), e.g. `A1:C3`. Unordered ranges will be rearranged when the formula is parsed, i.e. `C3:A1` becomes `A1:C3`.
493+- Links to other worksheets must follow the Excel syntax which separates the sheetname and cell address by a "!". An single cell, for example, can be linked by `Sheet1!A1`. An range of sheets must be placed before the cell or cell range, e.g. `Sheet1:Sheet2!A1:C3`. Note that the Open/LibreOffice syntax with a separating point and reference to the corner points of the 3d box (i.e., `Sheet1.A1:Sheet2.C3`) is not supported. Note also that the worksheet(s) to which the formula links must exist at the time when the formula is added; otherwise the link will be replaced by the error code `#REF!`, and the formula will not be usable even if the missing sheet is added later.
494+- Normally, floating point numbers must be entered with a dot as decimal separator, and a comma must be used to separate function arguments.
495+- Setting the optional parameter `ALocalized` of the worksheet methods `WriteFormula` to `TRUE`, however, allows to use localized decimal and list separators taken from the workbook's `FormatSettings` - see *spready* demo.
496+
497+``` pascal
498+var
499+ MyWorksheet: TsWorksheet;
500+//...
501+ MyWorksheet.WriteFormula(0, 1, '=ROUND(A1+B2+1,215;0)', true);
502+ // Because of the "true" the formula parser accepts the comma as decimal and the
503+ // semicolon as list separator if the workbook's FormatSettings are set up like this.
504+```
505+
506+Use the worksheet methods `ReadFormula` or `ReadFormulaAsString` to retrieve the string formula assigned to the cell. The pointer to the cell must be given as a parameter. The latter function accepts an additional (boolean) parameter `ALocalized` to use the decimal and list separators of the workbook's `FormatSettings` for creation of the formula string.
507+
508+``` pascal
509+var
510+ MyWorksheet: TsWorksheet;
511+ cell: PCell;
512+//...
513+ cell := MyWorksheet.FindCell(0, 1);
514+ WriteLn('The formula in internal format is ', MyworkSheet.ReadFormula(cell));
515+ WriteLn('The localized formula is ', MyWorksheet.ReadFormulaAsString(cell, true));
516+//-------------------------------------------------------------------
517+// For the previous example, this will result in the following output
518+The formula in internal format is ROUND(A1+B2+1.215,0)
519+The localized formula is ROUND(A1+B2+1,215;0)
520+```
521+
522+#### RPN formulas
523+
524+At application level, string formulas are mainly used, and RPN formulas are of little practical importance. Therefore, documentation of RPN formulas has been removed from this main FPSpreadsheet wiki and can be found in the article [[RPN Formulas in FPSpreadsheet|"RPN Formulas in FPSpreadsheet"]].
525+
526+#### Shared formulas and array formulas
527+
528+- **Shared formulas** are only supported for reading (from Excel files).
529+- **Array formulas** are not supported, currently.
530+
531+#### List of built-in formulas
532+
533+FPSpreadsheet supports more than 80 built-in formulas. In order not to blow up this wiki page too much documentation of these formulas has been moved to the [[FPSpreadsheet: List of formulas|separate document "List of formulas"]].
534+
535+To learn more about the functions available, look at file *testcases_calcrpnformula.inc* in the *tests* folder of the FPSpreadsheet installation where every function is included with at least one sample.
536+
537+#### Extending FPSpreadsheet by user-defined formulas
538+
539+Although the built-in formulas cover most of the applications there may be a need to access a formula which is available in the Office application, but not in FPSpreadsheet. For this reason, the library supports a registration mechanism which allows to add user-defined functions to the spreadsheets. This can be done by calling the procedure `RegisterFunction` from the unit *fpsExprParser*:
540+
541+``` pascal
542+procedure RegisterFunction(const AName: ShortString; const AResultType: Char;
543+ const AParamTypes: String; const AExcelCode: Integer; ACallBack: TsExprFunctionCallBack); overload;
544+
545+procedure RegisterFunction(const AName: ShortString; const AResultType: Char;
546+ const AParamTypes: String; const AExcelCode: Integer; ACallBack: TsExprEventCallBack); overload;
547+```
548+
549+- `AName` specifies the name under which the function will be called in the spreadsheet. It must match the name of the formula in the Office application.
550+- `AResultType` is a character which identifies the data type of the function result:
551+ - `'F'` - floating point number
552+ - `'I'` - integer
553+ - `'D'` - date/time
554+ - `'B'` - boolean
555+ - `'S'` - string
556+ - `'C'` - cell address, e.g. 'A1'
557+ - `'R'` - cell range address, e.g. 'A1:C3'
558+- `AParamTypes` is a string in which each character identifies the data type of the corresponding argument. In addition to the list shown above the following symbols can be used:
559+ - `'?'` - any type
560+ - `'+'` - must be the last character. It means that the preceding character is repeated indefinitely. This allows for an arbitrary argument count. Please note, however, that Excel supports only up to 30 arguments.
561+ - lowercase `'f', 'i', 'd', 'b', 's'` indicate optional parameters of the type explained above. Of course, uppercase symbols cannot follow lower-case symbols.
562+- `AExcelCode` is the identifier of the function in xls files. See "OpenOffice Documentation of the Microsoft Excel File Format", section 3.11, for a list.
563+- `ACallback` identifies which function is called by FPSpreadsheet for calculation of the formula. It can either be a procedure or an event handler.
564+
565+``` pascal
566+type
567+ TsExprFunctionCallBack = procedure (var Result: TsExpressionResult; const Args: TsExprParameterArray);
568+ TsExprFunctionEvent = procedure (var Result: TsExpressionResult; const Args: TsExprParameterArray) of object;
569+```
570+
571+The `TsExpressionResult` is a variant record containing result or argument data of several types:
572+
573+``` pascal
574+type
575+ TsResultType = (rtEmpty, rtBoolean, rtInteger, rtFloat, rtDateTime, rtString,
576+ rtCell, rtCellRange, rtError, rtAny);
577+
578+ TsExpressionResult = record
579+ Worksheet : TsWorksheet;
580+ ResString : String;
581+ case ResultType : TsResultType of
582+ rtEmpty : ();
583+ rtError : (ResError : TsErrorValue);
584+ rtBoolean : (ResBoolean : Boolean);
585+ rtInteger : (ResInteger : Int64);
586+ rtFloat : (ResFloat : TsExprFloat);
587+ rtDateTime : (ResDateTime : TDatetime);
588+ rtCell : (ResRow, ResCol : Cardinal);
589+ rtCellRange : (ResCellRange : TsCellRange);
590+ rtString : ();
591+ end;
592+
593+ TsExprParameterArray = array of TsExpressionResult;
594+```
595+
596+As an example we show here the code for the `CONCATENATE()` formula which joins two or more strings:
597+
598+``` pascal
599+const
600+ INT_EXCEL_SHEET_FUNC_CONCATENATE = 336;
601+...
602+ RegisterFunction('CONCATENATE', 'S', 'S+', INT_EXCEL_SHEET_FUNC_CONCATENATE, @fpsCONCATENATE);
603+
604+procedure fpsCONCATENATE(var Result: TsExpressionResult; const Args: TsExprParameterArray);
605+// CONCATENATE( text1, text2, ... text_n )
606+var
607+ s: String;
608+ i: Integer;
609+begin
610+ s := '';
611+ for i:=0 to Length(Args)-1 do
612+ begin
613+ if Args[i].ResultType = rtError then
614+ begin
615+ Result := ErrorResult(Args[i].ResError);
616+ exit;
617+ end;
618+ s := s + ArgToString(Args[i]);
619+ // "ArgToString" simplifies getting the string from a TsExpressionResult as
620+ // a string may be contained in the ResString and in the ResCell fields.
621+ // There is such a function for each basic data type.
622+ end;
623+ Result := StringResult(s);
624+ // "StringResult" stores the string s in the ResString field of the
625+ // TsExpressionResult and sets the ResultType to rtString.
626+ // There is such a function for each basic data type.
627+end;
628+```
629+
630+There is a worked-out example (*demo_formula_func.pas*) in the folder *examples/other* of the FPSpreadsheet installation. In this demo, four financial functions (`FV()`, `PV()`, `PMT()`, `RATE()`) are added to FPSpreadsheet.
631+
632+#### Unsupported formulas
633+
634+Sometimes it is required to create files for the Office applications with formulas not supported by fpspreadsheet. This is possible to some extent when the workbook option `boIgnoreFormulas` is active. Then any arbitrary formula can be written to a cell, and the formula is not checked and not evaluated. The workbook can be written to an .ods or .xlsx file. The old xls file format cannot be used because the formula would have to be parsed to create the rpn formula needed.
635+
636+In folder *examples/other* you can find the sample project *demo_ignore_formula* which creates an ods file with references to another data file - external references normally are not supported by fpspreadsheet, and thus the ignore-formulas workaround must be used. Note that this example does not work with xlsx because Excel writes information on the external links to separate xml files within the xlsx container.
637+
638+### Cell formatting
639+
640+#### Number and date/time formats
641+
642+Numbers and date/time values can be displayed in a variety of formats. In FPSpreadsheet this can be achieved in two ways:
643+
644+- using **built-in number formats** by specifiying a value for the `NumberFormat` of the cell
645+- using a custom **format string**.
646+
647+Number formats can be specified by these worksheet methods:
648+
649+``` pascal
650+type
651+ TsWorksheet = class
652+ public
653+ // Set number formats alone
654+ function WriteNumberFormat(ARow, ACol: Cardinal; ANumberFormat: TsNumberFormat;
655+ const AFormatString: String = ''): PCell; overload;
656+ procedure WriteNumberFormat(ACell: PCell; ANumberFormat: TsNumberFormat;
657+ const AFormatString: String = ''); overload;
658+
659+ function WriteNumberFormat(ARow, ACol: Cardinal; ANumFormat: TsNumberFormat;
660+ ADecimals: Integer; ACurrencySymbol: String = ''; APosCurrFormat: Integer = -1;
661+ ANegCurrFormat: Integer = -1): PCell; overload;
662+ procedure WriteNumberFormat(ACell: PCell; ANumFormat: TsNumberFormat;
663+ ADecimals: Integer; ACurrencySymbol: String = '';
664+ APosCurrFormat: Integer = -1; ANegCurrFormat: Integer = -1); overload;
665+
666+ function WriteFractionFormat(ARow, ACol: Cardinal; AMixedFraction: Boolean;
667+ ANumeratorDigits, ADenominatorDigits: Integer): PCell; overload;
668+ procedure WriteFractionFormat(ACell: PCell; AMixedFraction: Boolean;
669+ ANumeratorDigits, ADenominatorDigits: Integer); overload;
670+
671+ // Set date/time formats alone
672+ function WriteDateTimeFormat(ARow, ACol: Cardinal; ANumberFormat: TsNumberFormat;
673+ const AFormatString: String = ''): PCell; overload;
674+ procedure WriteDateTimeFormat(ACell: PCell; ANumberFormat: TsNumberFormat;
675+ const AFormatString: String = ''); overload;
676+
677+ // Set cell values and number formats in one call
678+
679+ // number values
680+ function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
681+ AFormat: TsNumberFormat = nfGeneral; ADecimals: Byte = 2;
682+ ACurrencySymbol: String = ''): PCell; overload;
683+ procedure WriteNumber(ACell: PCell; ANumber: Double; AFormat: TsNumberFormat = nfGeneral;
684+ ADecimals: Byte = 2; ACurrencySymbol: String = ''); overload;
685+ function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
686+ AFormat: TsNumberFormat; AFormatString: String): PCell; overload;
687+ procedure WriteNumber(ACell: PCell; ANumber: Double;
688+ AFormat: TsNumberFormat; AFormatString: String); overload;
689+
690+ // date/time values
691+ function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
692+ AFormat: TsNumberFormat = nfShortDateTime; AFormatStr: String = ''): PCell; overload;
693+ procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
694+ AFormat: TsNumberFormat = nfShortDateTime; AFormatStr: String = ''); overload;
695+ function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
696+ AFormatStr: String): PCell; overload;
697+ procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
698+ AFormatStr: String); overload;
699+
700+ // currency values
701+ function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
702+ AFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = 2;
703+ ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
704+ ANegCurrFormat: Integer = -1): PCell; overload;
705+ procedure WriteCurrency(ACell: PCell; AValue: Double;
706+ AFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = -1;
707+ ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
708+ ANegCurrFormat: Integer = -1); overload;
709+ function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
710+ AFormat: TsNumberFormat; AFormatString: String): PCell; overload;
711+ procedure WriteCurrency(ACell: PCell; AValue: Double;
712+ AFormat: TsNumberFormat; AFormatString: String); overload;
713+ ...
714+```
715+
716+##### Built-in number formats
717+
718+The **built-in formats** are defined by the enumeration `TsNumberFormat`. In spite of its name, the elements cover both number and date/time values:
719+
720+``` pascal
721+type
722+ TsNumberFormat = (
723+ // general-purpose for all numbers
724+ nfGeneral,
725+ // numbers
726+ nfFixed, nfFixedTh, nfExp, nfPercentage, nfFraction,
727+ // currency
728+ nfCurrency, nfCurrencyRed,
729+ // dates and times
730+ nfShortDateTime, nfShortDate, nfLongDate, nfShortTime, nfLongTime,
731+ nfShortTimeAM, nfLongTimeAM, nfDayMonth, nfMonthYear, nfTimeInterval,
732+ // other (using format string)
733+ nfCustom);
734+```
735+
736+- **nfGeneral** corresponds to the default formatting showing as many decimals as possible (the number `3.141592654` would be unchanged.)
737+- **nfFixed** limits the decimals. The number of decimal places has to be specified in the call to `WriteNumber`. Example: with 2 decimals, the number `3.141592654` becomes `3.14`.
738+- **nfFixedTh**: similar to `nfFixed`, but adds a thousand separator when the number is displayed as a string: The number `3.141592654` would remain like in the previous example because it is too small to show thousand separators. But the number `314159.2654` would become `314,159.26`, for 2 decimals.
739+- **nfExp** selects exponential presentation, i.e. splits off the exponent. The parameter `ADecimals` in `WriteNumber` determines how many decimal places are used. (The number `3.141592654` becomes `3.14E+00` in case of two decimals).
740+- **nfPercentage** displays the number as a percentage. This means that the value is multiplied by 100, and a percent sign is added. Again, specify in `ADecimals` how many decimal places are to be shown. (The number `3.141592654` is displayed as `314.92%`, in case of 2 decimals).
741+- **nfFraction** presents a number as a fraction. Details (mixed fraction?, maximum digit count for numerator or denominator) for can be specified in the worksheet method `WriteFractionFormat`.
742+- **nfCurrency** displays the number together with a currency symbol, and there are special rules how to display negative values (in brackets, or minus sign before or after the number). The FormatSettings of the workbook are used to define the currency sign and the way numbers are displayed (`FormatSettings.CurrencyString` for the currency symbol, `FormatSettings.CurrencyFormat` for positive, `FormatSettings.NegCurrFormat` for negative values). These settings can be overridden by specifying them in the call to `WriteCurrency` directly.
743+- **nfCurrendyRed** like `nfCurrency`, in addition negative values are displayed in red.
744+- **nfShortDateTime** presents the DateTimeValue of the cell in "short date/time format", i.e. days + two digit months + two digit year + hours + minutes, no seconds. The order of the date parts is taken from the workbook's `FormatSettings`. This applies also to the other date/time formats.
745+- **nfShortDate** creates a date string showing day + two-digit month + two-digit year
746+- **nfShortTime** creates a time string showing hours + minutes.
747+- **nfLongTime**, similar, but includes seconds as well
748+- **nfShortTimeAM**, similar to `nfShortTime`, but uses the AM/PM time format, i.e. hours go up to 12, and AM or PM is added to specify morning or evening/afternoon.
749+- **nfLongTimeAM**, like `nfShortTimeAM`, but includes seconds
750+- **nfTimeInterval**, like `nfLongTime`, but there can be more than 24 hours. The interval can also be expressed in minutes or seconds, if the format strings `[n]:ss`, or `[s]`, respectively, are used.
751+- **nfCustom** allows to specify a dedicated formatting string.
752+
753+As already noted the workbook has a property `FormatSettings` which provides additional information to control the resulting formatting. This is essentially a copy of the `DefaultFormatSettings` declared in the *sysutils* unit (the elements `LongDateFormat` and `ShortDateFormat` are slightly modified to better match the default settings in the main spreadsheet applications). The main purpose of the `FormatSettings` is to add a simple way of localization to the number formats.
754+
755+##### Number format strings
756+
757+In addition to these pre-defined formats, more specialized formatting can be achieved by using the format constant `nfCustom` along with a dedicated **format string**. The format string is constructed according to Excel syntax which is close to the syntax of fpc's `FormatFloat` and `FormatDateTime` commands (accepted as well, see the online-help for these functions).
758+
759+Here is a basic list of the symbols used:
760+
761+<thead>
762+
763+</thead>
764+<tbody>
765+
766+1.2345678 --&gt; <code>'1.2345678'</code></td>
767+
768+<code>'0.0'</code>: 1 --&gt; <code>'1.0'</code><br />
769+<code>'0.0'</code>: 1.2345678 --&gt; <code>'1.2'</code></td>
770+
771+<code>'0.*'</code>: 1.2345678 --&gt; <code>'1.2'</code></td>
772+
773+<code>'0.0??'</code>: 1 --&gt; <code>'1.0 '</code></td>
774+
775+<code>'0.00,'</code>: 1200 --&gt; <code>'1.20'</code></td>
776+
777+<code>'# #/#'</code>: 1.5 --&gt; <code>'1 1/2'</code><br />
778+<code>'# #/16'</code>: 1.5 --&gt; <code>'1 8/16'</code><br />
779+also: see date/time examples below</td>
780+
781+Jan 3, 2012 --&gt; <code>'2012-01-03'</code><br />
782+In this example, the <code>DateSeparator</code> is a dash character (<code>-</code>).</td>
783+
784+Jan 3, 2012 --&gt; <code>'12-01-03'</code></td>
785+
786+Please note that the <code>m</code> code can also be interpreted as the "minutes" of a time value (see below).</td>
787+
788+Jan 3, 2012 --&gt; <code>'2012-1-03'</code></td>
789+
790+Please note that the <code>mm</code> code can also be interpreted as the "minutes" of a time value (see below).</td>
791+
792+Jan 3, 2012 --&gt; <code>'2012-01-03'</code></td>
793+
794+Jan 3, 2012 --&gt; <code>'2012-Jan-03'</code></td>
795+
796+Jan 3, 2012 --&gt; <code>'2012-January-03'</code></td>
797+
798+Jan 3, 2012 --&gt; <code>'2012-01-3'</code></td>
799+
800+Jan 3, 2012 --&gt; <code>'2012-01-03'</code></td>
801+
802+Jan 03, 2012 --&gt; <code>'Tue 2012-01-03'</code></td>
803+
804+Jan 03, 2012 --&gt; <code>'Tuesday 2012-01-03'</code></td>
805+
806+0.25 --&gt; <code>'6:00'</code></td>
807+
808+0.25 --&gt; <code>'06:00'</code></td>
809+
810+1.25 --&gt; <code>'30:00'</code></td>
811+
812+0.25 --&gt; <code>'6:0'</code></td>
813+
814+0.25 --&gt; <code>'6:00'</code></td>
815+
816+1.25 --&gt; <code>'1800:00'</code></td>
817+
818+0.25 --&gt; <code>'06:00:0'</code></td>
819+
820+0.25 --&gt; <code>'06:00:00'</code></td>
821+
822+1.25 --&gt; <code>'108000'</code></td>
823+
824+0.25 --&gt; <code>'6:00:00 AM'</code></td>
825+
826+Jan 3, 2012 --&gt; <code>'2012/01/03'</code> (i.e. the <code>/</code> is not replaced by the <code>DateSeparator</code> of the workbook).</td>
827+
828+Jan 3, 2012 --&gt; <code>'2012/01/03'</code></td>
829+
830+1200 --&gt; <code>'1,200$'</code><br />
831+-1200 --&gt; <code>'1,200$'</code><br />
832+0 --&gt; <code>'-'</code></td>
833+
834+-1200 --&gt; <code>'(1200)$'</code></td>
835+
836+-1200 --&gt; '<code>($ 1200.00)</code>'</td>
837+
838+</tbody>
839+
840+##### A note on Excel dates
841+
842+There is a discrepancy between FPSpreadsheet and Excel presentation of dates: Excel incorrectly assumes that the year 1900 was a leap year and thus allows for the date Febr 29 1900. FPSpreadsheet does the date calculation correctly. As consequence, dates before March 1 1900 are off by one! BTW, FPSpreadsheet handles this issue in the same way as LibreOffice Calc.
843+
844+#### Colors
845+
846+FPSpreadsheet supports colors for text, cell background, and cell borders. The basic EGA colors are declared in unit *fpstypes* as constants:
847+
848+![](/wiki-images/7/7b/DefaultPalette.png)
849+
850+``` pascal
851+type
852+ TsColor = DWORD;
853+
854+const
855+ scBlack = $00000000;
856+ scWhite = $00FFFFFF;
857+ scRed = $000000FF;
858+ scGreen = $0000FF00;
859+ scBlue = $00FF0000;
860+ scYellow = $0000FFFF;
861+ scMagenta = $00FF00FF;
862+ scCyan = $00FFFF00;
863+ scDarkRed = $00000080;
864+ scDarkGreen = $00008000;
865+ scDarkBlue = $00800000;
866+ scOlive = $00008080;
867+ scPurple = $00800080;
868+ scTeal = $00808000;
869+ scSilver = $00C0C0C0;
870+ scGray = $00808080;
871+ scGrey = scGray; // redefine to allow different spelling
872+
873+ // Identifier for undefined color
874+ scNotDefined = $40000000;
875+
876+ // Identifier for transparent color
877+ scTransparent = $20000000;
878+```
879+
880+The `TsColor` represents the **rgb value** of a color, a single byte being used for the red, green, and blue components. The resulting number is in little endian notation, i.e. the red value comes first in memory: `$00BBGGRR`. (This is directly compatible with the color values as defined in the *graphics* unit.)
881+
882+The high order byte is usually zero but is used internally to identify special color values, such as for undefined or transparent colors.
883+
884+> **Note:** In older versions of the library colors were defined as indexes into a color palette. **THIS IS NO LONGER WORKING.**
885+
886+Unit *fpsutils* contains some useful functions for **modification of colors**:
887+
888+- `function GetColorName(AColor: TsColor): String;`\
889+ returns the name of the colors defined above, or a string showing the rgb components for other colors.
890+- `function HighContrastColor(AColor: TsColor): TsColor;`\
891+ returns `scBlack` for a "bright", `scWhite` for a "dark" input color.
892+- `function TintedColor(AColor: TsColor; tint: Double): TsColor;`\
893+ brightens or darkens a color by applying a factor `tint = -1..+1`, where `-1` means "100% darken", `+1` means "100% brighten", and `0` means "no change". The hue of the color is preserved.
894+
895+#### Cell background
896+
897+The cell background can be filled by predefined patterns which are identified by the record `TsFillPattern`:
898+
899+``` pascal
900+type
901+ TsFillPattern = record
902+ Style: TsFillStyle; // fill style pattern as defined below
903+ FgColor: TsColor; // forground color of the fill pattern
904+ BgColor: TsColor; // background color of the fill pattern
905+ end;
906+
907+ TsFillStyle = (fsNoFill, fsSolidFill, fsGray75, fsGray50, fsGray25, fsGray12, fsGray6,
908+ fsStripeHor, fsStripeVert, fsStripeDiagUp, fsStripeDiagDown,
909+ fsThinStripeHor, fsThinStripeVert, fsThinStripeDiagUp, fsThinStripeDiagDown,
910+ fsHatchDiag, fsThinHatchDiag, fsThickHatchDiag, fsThinHatchHor);
911+```
912+
913+- Use the worksheet method `WriteBackground` to assign a fill pattern to a specific cell. Besides the cell address, this method requires the type of the fill pattern (`TsFillStyle`), and the foreground and background colors as specified by their `TsColor` values.
914+- The fill pattern of a particular cell can be retrieved by calling the workbook method `ReadBackground`.
915+- The simplified method `WriteBackgroundColor` can be used to achieve a uniform background color.
916+- **Limitations:**
917+ - OpenDocument files support only uniform fills. The background color is a mixture of the foreground and background rgb components in a ratio defined by the fill pattern.
918+ - BIFF2 files support only a 12.5% black-and-white shaded pattern.
919+
920+``` pascal
921+type
922+ TsWorksheet = class
923+ public
924+ function WriteBackground(ARow, ACol: Cardinal; AStyle: TsFillStyle; APatternColor, ABackgroundColor: TsColor): PCell; overload;
925+ procedure WriteBackground(ACell: PCell; AStyle: TsFillStyle; APatternColor, ABackgroundColor: TsColor); overload;
926+
927+ function WriteBackgroundColor(ARow, ACol: Cardinal; AColor: TsColor): PCell; overload;
928+ procedure WriteBackgroundColor(ACell: PCell; AColor: TsColor); overload;
929+
930+ function ReadBackground(ACell: PCell): TsFillPattern;
931+ function ReadBackgroundColor(ACell: PCell): TsColor; overload;
932+ // ...
933+ end;
934+
935+var
936+ cell: PCell;
937+...
938+ // Example 1: Assign a pattern of thin, horizontal, yellow stripes on a blue background to empty cell A1 (row 0, column 0)
939+ MyWorksheet.WriteBackground(0, 0, fsThinStripeHor, scYellow, scBlue);
940+
941+ // Example 2: Uniform gray background color of cell B1 (row 0, column 1) containing the number 3.14
942+ cell := MyWorksheet.WriteNumber(0, 1, 3.14);
943+ MyWorksheet.WriteBackgroundColor(cell, clSilver);
944+```
945+
946+#### Cell borders
947+
948+Cells can be emphasized by drawing border lines along their edges or diagonal lines. There are four borders plus two diagonals enumerated in the data type `TsCellBorder`:
949+
950+``` pascal
951+type
952+ TsCellBorder = (cbNorth, cbWest, cbEast, cbSouth, cbDiagUp, cbDiagDown);
953+ TsCellBorders = set of TsCellBorder;
954+```
955+
956+In order to show a border line add the corresponding border to the cell's set `Borders` (type `TsCellBorders`, see above). In this way, each cell edge can be handled separately. Use the worksheet method `WriteBorders` for this purpose. This example adds top and bottom borders to the edges A1 and B1:
957+
958+``` pascal
959+ MyWorksheet.WriteBorders(0, 0, [cbNorth, cbSouth]); // A1: row 0, column 0
960+ MyWorksheet.WriteBorders(0, 1, [cbNorth, cbSourth]); // B1: row 0, column 1
961+```
962+
963+Lines usually are drawn as thin, solid, black lines. But it is possible to modify **line style** and **color** of each line. For this purpose, the cell provides an array of `TsCellBorderStyle` records:
964+
965+``` pascal
966+type
967+ TsLineStyle = (lsThin, lsMedium, lsDashed, lsDotted, lsThick, lsDouble, lsHair,
968+ lsMediumDash, lsDashDot, lsMediumDashDot, lsDashDotDot, lsMediumDashDotDot, lsSlantDashDot);
969+
970+ TsCellBorderStyle = record
971+ LineStyle: TsLineStyle;
972+ Color: TsColor;
973+ end;
974+
975+ TsCellBorderStyles = array[TsCellBorder] of TsCellBorderStyle;
976+
977+ TsWorksheet = class
978+ public
979+ function WriteBorderStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; AStyle: TsCellBorderStyle): PCell; overload;
980+ procedure WriteBorderStyle(ACell: PCell; ABorder: TsCellBorder; AStyle: TsCellBorderStyle); overload;
981+
982+ function WriteBorderStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; ALineStyle: TsLineStyle; AColor: TsColor): PCell; overload;
983+ procedure WriteBorderStyle(ACell: PCell; ABorder: TsCellBorder; ALineStyle: TsLineStyle; AColor: TsColor); overload;
984+
985+ function WriteBorderColor(ARow, ACol: Cardinal; ABorder: TsCellBorder; AColor: TsColor): PCell; overload;
986+ procedure WriteBorderColor(ACell: PCell; ABorder: TsCellBorder; AColor: TsColor): PCell; overload;
987+
988+ function WriteBorderLineStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; ALineStyle: TsLineStyle): PCell; overload;
989+ procedure WriteBorderLineStyle(ACell: PCell; ABorder: TsCellBorder; ALineStyle: TsLineStyle): PCell; overload;
990+
991+ function WriteBorderStyles(ARow, ACol: Cardinal; const AStyles: TsCellBorderStyles): PCell; overload;
992+ procedure WriteBorderStyles(ACell: PCell; const AStyles: TsCellBorderStyles); overload;
993+
994+ function WriteBorders(ARow, ACol: Cardinal; ABorders: TsCellBorders): PCell; overload
995+ procedure WriteBorders(ACell: PCell; ABorders: TsCellBorders); overload
996+
997+ function ReadCellBorders(ACell: PCell): TsCellBorders;
998+ function ReadCellBorderStyle(ACell: PCell; ABorder: TsCellBorder): TsCellBorderStyle;
999+ function ReadCellBorderStyles(ACell: PCell): TsCellBorderStyles;
1000+ ...
1001+ end;
1002+```
1003+
1004+The style of a given cell border can be specified by the following methods provided by the worksheet:
1005+
1006+- **WriteBorderStyle** assigns a cell border style record to one border of the cell. There are two overloaded versions of this method: one takes an entire `TsCellBorderStyle` record, the other one takes the individual record elements.
1007+- **WriteBorderColor** changes the color of a given border without affecting the line style of this border.
1008+- **WriteBorderLineStyle** sets the line style of the border only, but leaves the color unchanged.
1009+- **WriteBorderStyles** sets the border style of all borders of a given cell at once. Useful for copying border styles from one cell to other cells.
1010+
1011+This example adds a thin black border to the top, and a thick blue border to the bottom of cells A1 and B1:
1012+
1013+``` pascal
1014+var
1015+ cellA1, cellB1: PCell;
1016+...
1017+ cellA1 := MyWorksheet.WriteBorders(0, 0, [cbNorth, cbSouth]); // cell A1: row 0, column 0
1018+ MyWorksheet.WriteBorderStyle(cellA1, cbNorth, lsThin, scBlack);
1019+ MyWorksheet.WriteBorderStyle(cellA1, cbSouth, lsThick, scBlue);
1020+
1021+ cellB1 := MyWorksheet.WriteBorders(0, 1, [cbNorth, cbSouth]); // cell B1: row 0, column 1
1022+ MyWorksheet.WriteBorderStyles(cellB1, cellA1^.BorderStyles); // copy all border styles from cell A1 to B1
1023+```
1024+
1025+> **Note:** Diagonal lines are not supported by *sfExcel2* and *sfExcel5* - they are just omitted. *sfExcel8* and *sfOOXML* use the same linestyle and color for both diagonals; when writing the border style of the diagonal-up line is assumed to be valid also for the diagonal-down line. Some writers do not support all the line styles of the `TsLineStyle` enumeration. In this case, appropriate replacement line styles are used.
1026+
1027+#### Fonts
1028+
1029+The cell text can displayed in various fonts. For this purpose, the workbook provides a list of `TsFont` items:
1030+
1031+``` pascal
1032+type
1033+ TsFont = class
1034+ FontName: String;
1035+ Size: Single;
1036+ Style: TsFontStyles;
1037+ Color: TsColor;
1038+ Position: TsFontPosition;
1039+ end;
1040+```
1041+
1042+- The **FontName** corresponds to the name of the font as used by the operational system. In Windows, an example would be "Times New Roman".
1043+- The **FontSize** is given in "points", i.e. units 1/72 inch which are commonly used in Office applications.
1044+- The **FontStyle** is a set of the items `fssBold`, `fssItalic`, `fssStrikeout`, and `fssUnderline` which form the enumeration type `TsFontStyle`. The "normal" font corresponds to an empty set.
1045+- The **Color** determines the foreground color of the text characters given in rgb presentation as discussed above.
1046+- The **Position** is either `fpNormal`, `fpSuperscript`, or `fpSubscript` and indicates whether the font size should be decreased by about 1/3 and the characters should be displaced up (superscript) or down (subscript).
1047+
1048+Every cell is provided with an **index into the font list**.
1049+
1050+In order to assign a particular font to a cell, use one of the following methods of `TsSpreadsheet`:
1051+
1052+``` pascal
1053+type
1054+ TsSpreadsheet = class
1055+ public
1056+ function WriteFont(ARow, ACol: Cardinal; const AFontName: String;
1057+ AFontSize: Single; AFontStyle: TsFontStyles; AFontColor: TsColor): Integer; overload;
1058+ procedure WriteFont(ARow, ACol: Cardinal; AFontIndex: Integer); overload;
1059+ function WriteFontColor(ARow, ACol: Cardinal; AFontColor: TsColor): Integer;
1060+ function WriteFontSize(ARow, ACol: Cardinal; ASize: Integer): Integer;
1061+ function WriteFontStyle(ARow, ACol: Cardinal; AStyle: TsFontStyles): Integer;
1062+ // plus: overloaded versions accepting a pointer to a cell record instead of the row and column index as parameter
1063+ // ...
1064+ end;
1065+```
1066+
1067+- **WriteFont** assigns a font to the cell. If the font does not yet exist in the font list a new entry is created. The function returns the index of the font in the font list. In addition, there is an overloaded version which only takes the font index as a parameter.
1068+- **WriteFontColor** replaces the color of the font that is currently assigned to the cell by a new one. Again, a new font list item is created if the font with the new color does not yet exist. The function returns the index of the font in the list.
1069+- **WriteFontSize** replaces the size of the currently used font of the cell.
1070+- **WriteFontStyle** replaces the style (normal, bold, italic, etc.) of the currently used cell font.
1071+
1072+The workbook's font list contains at least one item which is the **default font** for cells with unmodified fonts. By default, this is 10-point "Arial". Use the workbook method `SetDefaultFont` to assign a different font to the first list item.
1073+
1074+The font at a given index of the font list can be looked up by calling the workbook function `GetFont`. The count of available fonts is returned by `GetFontCount`.
1075+
1076+Here is an **example** which decreases the size of all 10-point "Arial" fonts to 9-point:
1077+
1078+``` pascal
1079+var
1080+ i: Integer;
1081+ font: TsFont;
1082+begin
1083+ for i := 0 to MyWorkbook.GetFontCount-1 do
1084+ begin
1085+ font := MyWorkbook.GetFont(i);
1086+ if (font.FontName = 'Arial') and (font.Size = 10.0) then
1087+ font.Size := 9.0;
1088+ end;
1089+end;
1090+```
1091+
1092+#### Rich-text formatting
1093+
1094+In addition to using a specific font for each cell it is also possible to specify particular font attributes for individual characters or groups of characters in each cell text. Following the Excel notation, we call this feature **Rich-text formatting** (although is has nothing in common with the "rich-text" file format).
1095+
1096+For this purpose, unit *fpstypes* declares the type `TsRichTextParams` which is an array of `TsRichTextParam` records:
1097+
1098+``` pascal
1099+type
1100+ TsRichTextParam = record
1101+ FontIndex: Integer;
1102+ FirstIndex: Integer;
1103+ end;
1104+
1105+ TsRichTextParams = array of TsRichTextParam;
1106+```
1107+
1108+`FontIndex` refers to the index of the font in the workbook's FontList to be used for formatting of the characters beginning at the index `FirstIndex`. Being a string character index the `FirstIndex` is 1-based.
1109+
1110+There are two ways to add "rich-text" formatting to a cell text:
1111+
1112+- Embed corresponding HTML format codes into the cell text. This can be done using the method `WriteTextAsHTML` of the worksheet. In order to add the text "Area (m<sup>2</sup>)" to cell A1, pass the following HTML-coded string to this function
1113+
1114+``` pascal
1115+ MyWorksheet.WriteTextAsHTML(0, 0, 'Area (m<sup>2</sup>');
1116+```
1117+
1118+- Alternatively, the standard text writing method, `WriteText` can be called with an additional parameter specifiying the rich-text formatting parameters to be used directly:
1119+
1120+``` pascal
1121+var
1122+ richTextParams: TsRichTextParams;
1123+ fnt: TsFont;
1124+ cell: PCell;
1125+begin
1126+ SetLength(rtp, 2);
1127+ cell := MyWorksheet.GetFont(0, 0);
1128+ fnt := MyWorksheet.ReadCellFont(cell);
1129+ richTextParams[0].FirstIndex := 8; // The superscript groups begins with "2" which is the (1-based) character #8 of the cell text.
1130+ richTextParams[0].FontIndex := MyWorkbook.AddFont(fnt.FontName, fnt.Size, fnt.Style, fnt.Color, fpSuperscript);
1131+ richTextParams[1].FirstIndex := 9; // Normal font again beginning with character #9.
1132+ richTextParams[1].FontIndex := MyWorksheet.ReadCellFontIndex(0, 0);
1133+ MyWorksheet.WriteUTF8Text(cell, 'Area (m2)', richTextParams);
1134+end;
1135+```
1136+
1137+Use the worksheet method `DeleteRichTextParams` to remove rich-text formatting from a previously formatted cell.
1138+
1139+> **Note:** If the cell is supposed to have a font different from the worksheet's default font then this font must be written to the cell **before** writing the rich-text formatted text. Otherwise the font in the unformatted regions will not be up-to-date.
1140+
1141+#### Text rotation
1142+
1143+Usually text is displayed in the cells horizontally. However, it is also possible to rotate it by 90 degrees in clockwise or counterclockwise directions. In addition, there is also an option to stack horizontal characters vertically above each other.
1144+
1145+If you need this feature use the worksheet method `WriteTextRotation` and specify the text direction by an element of the enumeration type `TsTextRotation`:
1146+
1147+``` pascal
1148+type
1149+ TsTextRotation = (trHorizontal, rt90DegreeClockwiseRotation,
1150+ rt90DegreeCounterClockwiseRotation, rtStacked);
1151+
1152+ TsWorksheet = class
1153+ public
1154+ function WriteTextRotation(ARow, ACol: Cardinal; ARotation: TsTextRotation): PCell; overload;
1155+ procedure WriteTextRotation(ACell: PCell; ARotation: TsTextRotation); overload;
1156+
1157+ function ReadTextRotation(ACell: PCell): TsTextRotation;
1158+ // ...
1159+ end;
1160+
1161+ // example for counter-clockwise rotated text in cell A1:
1162+ WriteTextRotation(0, 0, rt90DegreeCounterClockwiseRotation);
1163+```
1164+
1165+> **Warning:** Finer degrees of rotation which may be supported by some spreadsheet file formats are ignored.
1166+
1167+#### Text alignment
1168+
1169+By default, cell texts are aligned to the left and bottom edges of the cell, except for numbers which are right-aligned. This behavior can be changed by using the worksheet methods `WriteHorAlignment` and `WriteVertAlignment`:
1170+
1171+``` pascal
1172+type
1173+ TsHorAlignment = (haDefault, haLeft, haCenter, haRight, haJustified, haDistributed, haFilled);
1174+ TsVertAlignment = (vaDefault, vaTop, vaCenter, vaBottom);
1175+
1176+ TsWorksheet = class
1177+ public
1178+ function WriteHorAlignment(ARow, ACol: Cardinal; AValue: TsHorAlignment): PCell; overload;
1179+ procedure WriteHorAlignment(ACell: PCell; AValue: TsHorAlignment); overload;
1180+ function ReadHorAlignment(ACell: PCell): TsHorAlignment;
1181+
1182+ function WriteVertAlignment(ARow, ACol: Cardinal; AValue: TsVertAlignment): PCell; overload;
1183+ procedure WriteVertAlignment(ACell: PCell; AValue: TsVertAlignment); overload;
1184+ function ReadVertAlignment(ACell: PCell): TsVertAlignment;
1185+ // ...
1186+ end;
1187+
1188+ // Example: Center the text in cell A1 both horizontally and vertically
1189+ MyWorksheet.WriteHorAlignment(0, 0, haCenter);
1190+ MyWorksheet.WriteVertAlignment(0, 0, vaCenter);
1191+```
1192+
1193+Explanation of special horizontal alignments:
1194+
1195+- `haDistributed`: The cell text is word-wrapped and its spaces are expanded so that the entire width of the cell is occupied. The text is both left- and right-justified.
1196+- `haJustified`: like `haDistributed`, expect for the last line which remains left-justified.
1197+- `haFilled`: the text is repeated to fill the entire cell.
1198+
1199+#### Word wrap
1200+
1201+Text which is longer than the width of a cell can wrap into several lines by calling the method `WriteWordwrap` of the spreadsheet:
1202+
1203+``` pascal
1204+type
1205+ TsWorksheet = class
1206+ public
1207+ function WriteWordwrap(ARow, ACol: Cardinal; AValue: Boolean): PCell; overload;
1208+ procedure WriteWordwrap(ACell: PCell; AValue: Boolean); overload;
1209+ function ReadWordwrap(ACell: PCell): Boolean;
1210+ //...
1211+ end;
1212+
1213+ // Example: activate wordwrap in cell A1
1214+ MyWorksheet.WriteWordwrap(0, 0, true);
1215+```
1216+
1217+#### Merged cells
1218+
1219+Like the Office applications, FPSpreadsheet supports also to feature of merging cells to a single large cell which is often used as a common header above simlar columns. Simply call `MergeCells` and pass a parameter to specify the cell range to be merged, either an Excel range string (such as `A1:D5`), or the first and last rows and columns:
1220+
1221+``` pascal
1222+ MyWorksheet.MergeCells('A1:D5');
1223+ // or: MyWorksheet.MergeCells(0, 0, 4, 3); // first row, first column, last row, last column
1224+```
1225+
1226+The content and format displayed for a merged range is taken from the upper left corner of the range, cell `A1` in above example. This cell is called the `MergeBase` in the library. Except for this corner cell, there must not be any other cells in the range. If there are their contents and format will be hidden.
1227+
1228+In order to break up a merged range back up into individual cells, use the command `Unmerge` and pass any cell that is within the merged range:
1229+
1230+``` pascal
1231+ MyWorksheet.UnmergeCells('B1');
1232+ // or: MyWorksheet.UnmergeCells(0, 1); // row, column of any cell within the range
1233+```
1234+
1235+Merged cells can be read from/written to all file formats except for `sfCSV`, `sfExcel2` and `sfExcel5` which do not support this feature natively.
1236+
1237+The information which cells are merged is stored in an internal list. Unlike in earlier versions it is no longer possible to access the `MergeBase` from the cell directly. Use the following functions to extract information on merged cells:
1238+
1239+``` pascal
1240+var
1241+ cell, base: PCell;
1242+ r1,c1,r2,c2: Cardinal;
1243+...
1244+ cell := MyWorksheet.FindCell('B1');
1245+ if MyWorksheet.IsMerged(cell) then
1246+ begin
1247+ WriteLn('Cell B1 is merged.');
1248+
1249+ MyWorksheet.FindMergedRange(cell, r1, c1, r2, c2);
1250+ WriteLn('The merged range is ' + GetCellRangeString(r1, c1, r2, c2));
1251+
1252+ base := MyWorksheet.FindMergeBase(cell);
1253+ WriteLn('The merge base is cell ' + GetCellString(base^.Row, base^.Col));
1254+ end;
1255+```
1256+
1257+#### Cell protection
1258+
1259+This is described in a separate section below.
1260+
1261+#### Miscellaneous
1262+
1263+##### Disable printing of specific cells
1264+
1265+Specific cells can be disabled from printing:
1266+
1267+``` pascal
1268+type
1269+ TsWorksheet = class
1270+ public
1271+ function WriteDoNotPrintCell(ARow, ACol: Cardinal; AValue: boolean): PCell; overload;
1272+ procedure WriteDoNotPrintCell(ACell: PCell; AValue: Boolean); overload;
1273+ function ReadDoNotPrintCell(ACell: PCell): Boolean;
1274+```
1275+
1276+### Additional data
1277+
1278+#### Cell comments
1279+
1280+Comments can be attached to any cell by calling
1281+
1282+``` pascal
1283+ MyWorksheet.WriteComment(0, 0, 'This is a comment for cell A1');
1284+```
1285+
1286+They are stored in an internal list of the worksheet. Use the corresponding worksheet methods to access comments:
1287+
1288+- If you want to know whether a particular cell contains a comment call the worksheet method `HasComment(cell)`.
1289+- For retrieving a cell comment use the method `ReadComment(cell)`, or its overloaded companion `ReadComment(ARow, ACol)`.
1290+- The total number of comments can be retrieved from `worksheet.Comments.Count`.
1291+
1292+#### Hyperlinks
1293+
1294+Hyperlinks can be attached to cells in order to link cells to other documents or other cells in the same workbook. The general syntax for creating hyperlinks is
1295+
1296+``` pascal
1297+ procedure TWorksheet.WriteHyperlink(ARow, ACol: Cardinal; ATarget: String; ATooltip: String = '');
1298+```
1299+
1300+- The hyperlink target, passed as parameter `ATarget`, must be a fully qualified [URI (Uniform resource identifier)](http://en.wikipedia.org/wiki/Uniform_Resource_Identifier) consisting of a protocol phrase (e.g., [`http://`](http://), [`file:///`](file:///), `mailto:`, etc.) followed by specific information such as web URL, filename, or e-mail address and an optional bookmark identification separated by the character `'#'`. An exception are internal hyperlinks which enable to jump to a cell in the current workbook; they consist of the optional worksheet name and the cell address separated by the character `'!'`.
1301+- The optional `Tooltip` parameter is evaluated by Excel to display it in a hint window if the mouse if above the hyperlink.
1302+
1303+> **Note:** Hyperlinks can be added to empty cells or to cells with content. In the latter case, the displayed content is not changed by the hyperlink; in the former case the cell is converted to a label cell showing the hyperlink target. Be aware that OpenOffice/LibreOffice only does accept hyperlinks with non-text cells.
1304+
1305+**Examples:**
1306+
1307+``` pascal
1308+ // Open the web site www.google.com
1309+ MyWorksheet.WriteText(0, 0, 'Open google');
1310+ MyWorksheet.WriteHyperlink(0, 0, 'http://www.google.com');
1311+
1312+ // Open the local file with the absolute path "C:\readme.txt" (assuming Windows)
1313+ MyWorksheet.WriteHyperlink(1, 0, 'file:///c:\readme.txt');
1314+
1315+ // Open the mail client to send a mail
1316+ MyWorksheet.WriteText('Send mail');
1317+ MyWorksheet.WriteHyperlink(3, 0, 'mailto:somebody@gmail.com?subject=Test');
1318+
1319+ // Jump to a particular cell
1320+ MyWorksheet.WriteText(5, 0, 'Jump to cell A10 on sheet2');
1321+ MyWorksheet.WriteHyperlink(5, 0, '#Sheet2!A10');
1322+
1323+ // Jump to cell A10 on the current sheet and display a popup hint
1324+ MyWorksheet.WriteHyperlink(5, 0, '#A10', 'Go to cell A10');
1325+```
1326+
1327+> **Note:** FPSpreadsheet does not "follow" the links, it only provides a mechanism to get access to the link data. TsWorksheetGrid from the *laz_fpspreadsheet_visual* package, however, fires the event `OnClickHyperlink` if a cell with an external hyperlink is clicked for fractions of a second. In the corresponding event handler, you can, for example, load a target spreadsheet, or open a web browser to display the linked web site. If the link is an internal link to another cell within the same workbook then the grid jumps to the related cell.
1328+
1329+#### Images
1330+
1331+FPSpreadsheet supports embedding of images in worksheets. Use one of the worksheet methods `WriteImage()` to add an image to the worksheet:
1332+
1333+``` pascal
1334+ MyWorksheet.WriteImage(row, col, filename, offsetX, offsetY, scaleX, scaleY);
1335+ MyWorksheet.WriteImage(row, col, stream, offsetX, offsetY, scaleX, scaleY);
1336+ MyWorksheet.WriteImage(row, col, imageindex, offsetX, offsetY, scaleX, scaleY);
1337+```
1338+
1339+The upper/left corner of the image is placed at the upper/left corner of the cell in the specified row and column. The floating point parameters `offsetX`, `offsetY`, `scaleX` and `scaleY` are optional: they define an offset of this image anchor point from the cell corner and a magnification factor. The path to the image file is given as parameter `filename`. Alternatively, overloaded versions can be used which accept a stream in place of the file name or an image index in the workbook's EmbeddedObj list - use `MyWorkbook.FindEmbeddedObj(filename)` to get this index for a previously loaded image file.
1340+
1341+Note that FPSpreadsheet needs to know the image type for successfull picture import. Currently, the types *png*, *jpg*, *tiff*, *bmp*, *gif*, *svg*, *wmf*, *emf*, and *pcx* are supported (Excel2007 cannot read imported *svg* and *pcx* images). Other formats can be registered by writing a function which determines the image size and pixel density, and by registering the new format using the procedure `RegisterImageType` - see unit *fpsImages* for examples:
1342+
1343+``` pascal
1344+type
1345+ TsImageType = integer;
1346+ TGetImageSizeFunc = function (AStream: TStream; out AWidth, AHeight: DWord; out dpiX, dpiY: Double): Boolean;
1347+
1348+function RegisterImageType(AMimeType, AExtension: String; AGetImageSize: TGetImageSizeFunc): TsImageType;
1349+```
1350+
1351+Due to differences in row height and column width calculation between FPSpreadsheet and Office applications it is not possible to position images correctly. If exact image positions are important you should follow these rules:
1352+
1353+- Predefine the widths of all columns at least up to the one containing the right edge of the image.
1354+- Predefine the heights of all rows at least up to the one containing the lower edge of the image.
1355+- If the workbook is to be saved in OpenDocument format add the image after changing column widths and row heights because ods anchors the image to the sheet, not to the cell (like Excel and FPSpreadsheet).
1356+- If the exact size of the image is important make sure that it fits into a single cell.
1357+
1358+### Sorting
1359+
1360+Cells in a worksheet can be sorted for a variety of criteria by calling the `Sort` method of the worksheet. This method takes a `TsSortParams` record and the edges of the cell rectangle to be sorted as parameters; in an overloaded version, the cell rectangle can also be specified by means of an Excel-type range string (e.g. `'A1:G10'`):
1361+
1362+``` pascal
1363+type
1364+ TsWorksheet = class
1365+ // ...
1366+ procedure Sort(const ASortParams: TsSortParams;
1367+ ARowFrom, AColFrom, ARowTo, AColTo: Cardinal); overload;
1368+ procedure Sort(ASortParams: TsSortParams; ARange: String); overload;
1369+ // ...
1370+ end;
1371+```
1372+
1373+The sorting criteria are defined by a record of type `TsSortParams`:
1374+
1375+``` pascal
1376+type
1377+ TsSortParams = record
1378+ SortByCols: Boolean;
1379+ Priority: TsSortPriority; // spNumAlpha ("Numbers first"), or spAlphaNum ("Text first")
1380+ Keys: TsSortKeys;
1381+ end;
1382+
1383+ TsSortKey = record
1384+ ColRowIndex: Integer;
1385+ Options: TsSortOptions; // set of [spDescending, spCaseInsensitive]
1386+ end;
1387+```
1388+
1389+- The boolean value `SortByCols` determines wether sorting occurs along columns (`true`) or rows (`false`). The `ColRowIndex` specified in the sorting keys, accordingly, corresponds to a column or row index, respectively (see below).
1390+- `Priority` determines in mixed content cell ranges whether an ascending sort puts numerical values in front of text values or not. Empty cells are always moved to the end of the sorted column or row. In Excel, the priority is "numbers first" (`spNumAlpha`).
1391+- The array `Keys` specifies multiple sorting parameters. They consist of the index of the column or row to be sorted (`ColRowIndex`) and a set of `Options` for sorting direction (`spoDescending`) and character case (`spCaseInsensitive`). If `Options` is empty, cell comparison is case-sensitive, and cells are arranged in ascending order. If two cells are found to be "equal" on the basis of the first key (`sortParams.Keys[0]`) comparison proceeds with the next conditions in the `Keys` array until a difference is found or all conditions are used up.
1392+
1393+`InitSortParams` is a handy utility to initialize the sorting parameters:
1394+
1395+``` pascal
1396+function InitSortParams(ASortByCols: Boolean = true; ANumSortKeys: Integer = 1;
1397+ ASortPriority: TsSortPriority = spNumAlpha): TsSortParams;
1398+```
1399+
1400+The next code fragment shows a typical sorting call:
1401+
1402+``` pascal
1403+var
1404+ sortParams: TsSortParams;
1405+begin
1406+ sortParams := InitSortParams(true, 2); // sorting along columns, 2 sorting keys
1407+
1408+ // primary sorting key: column 3, ascending, case-insensitive
1409+ sortParams.Keys[0].ColRowIndex := 3;
1410+ sortParams.Keys[0].Options := [ssoCaseInsensitive];
1411+
1412+ // secondary sorting key: colum 1, descending
1413+ sortParams.Keys[1].ColRowIndex := 1;
1414+ sortParams.Keys[1].Options := [ssoDescending];
1415+
1416+ // The sorted block extends between cells A1 (row=0, col=0) and F10 (row=9, col=5)
1417+ MyWorksheet.Sort(sortParams, 0, 0, 9, 5);
1418+ // or: MyWorksheet.Sort(sortParams, 'A1:F10');
1419+end;
1420+```
1421+
1422+### Searching and replacing
1423+
1424+Unit *fpsSearch* implements a **search engine** which can be used to look for specific cell content within a workbook, or to replace the found cell content by some other string.
1425+
1426+**Example:**
1427+
1428+``` pascal
1429+uses
1430+ fpsTypes, fpSpreadsheet, fpsUtils, fpsSearch, fpsAllFormats;
1431+var
1432+ MyWorkbook: TsWorkbook;
1433+ foundWorksheet: TsWorksheet;
1434+ foundRow, foundCol: Cardinal;
1435+ MySearchParams: TsSearchParams;
1436+begin
1437+ MyWorkbook := TsWorkbook.Create;
1438+ try
1439+ MyWorkbook.ReadFromFile(AFileName);
1440+
1441+ // Specify search criteria
1442+ MySearchParams.SearchText := 'Hallo';
1443+ MySearchParams.Options := [soEntireDocument];
1444+ MySearchParams.Within := swWorkbook;
1445+
1446+ // or: MySearchParaams := InitSearchParams('Hallo', [soEntireDocument], swWorkbook);
1447+
1448+ // Create search engine and execute search
1449+ with TsSearchEngine.Create(MyWorkbook) do begin
1450+ if FindFirst(MySearchParams, foundWorksheet, foundRow, foundCol) then begin
1451+ WriteLn('First "', MySearchparams.SearchText, '" found in cell ', GetCellString(foundRow, foundCol), ' of worksheet ', foundWorksheet.Name);
1452+ while FindNext(MySeachParams, foundWorksheet, foundRow, foundCol) do
1453+ WriteLn('Next "', MySearchParams.SearchText, '" found in cell ', GetCellString(foundRow, foundCol), ' of worksheet ', foundWorksheet.Name);
1454+ end;
1455+ Free;
1456+ end;
1457+ finally
1458+ MyWorkbook.Free;
1459+ end;
1460+end;
1461+```
1462+
1463+The search engine provides two methods for **searching**: `FindFirst` and `FindNext`. They are very similar, they only differ in where the search begins. In case of `FindFirst`, the starting cell is determined from the `Options` described below. In case of `FindNext` the search begins at the cell adjacent to the previously found cell. Both methods return the worksheet and row and column indexes of the cell in which the search text is found. If the search is not successful then the function result is `FALSE`, and the `foundWorksheet` is nil. It is clear that the `foundWorksheet` cannot be used for anything else while the search is running.
1464+
1465+The record `TsSearchParams` specifies the criteria used for searching:
1466+
1467+``` pascal
1468+type
1469+ TsSearchParams = record
1470+ SearchText: String;
1471+ Options: TsSearchOptions;
1472+ Within: TsSearchWithin;
1473+ end;
1474+```
1475+
1476+Besides the text to be searched (`SearchText`) it provides a set of options to narrow the search:
1477+
1478+- `soCompareEntireCell`: Compares the `SearchText` with the entire cell content. If not contained in the `Options` then the cell text is compared only partially.
1479+- `soMatchCase`: Perform a case-sensitive search
1480+- `soRegularExpr`: The `SearchText` is considered as a regular expression
1481+- `soAlongRows`: The search engine proceeds first along the rows. If not contained in the `Options` then the search proceeds along the columns.
1482+- `soBackward`: The search begins at the end of the document, or runs backward from the active cell. If not contained in the `Options` then the search starts at the beginning of the document, or runs forward from the active cell.
1483+- `soWrapDocument`: If a search has reached the end of the document the search is resumed at its beginning (or vice versa, if `soBackward` is used).
1484+- `soEntireDocument`: Search begins at the first cell (or last cell if `soBackward` is used). If not contained in the `Options` then the search begins at the active cell of the worksheet. Ignored by `FindNext`.
1485+
1486+The record field `Within` identifies the part of the spreadsheet to be searched:
1487+
1488+- `swWorkbook`: The entire workbook is searched. If the search phrase is not found on the first worksheet (or last worksheet if `soBackward` is used) then the search continues with the next (previous) sheet.
1489+- `swWorksheet`: The search is limited to the currently active worksheet
1490+- `swColumn`: Search is restricted to the column of the active cell
1491+- `swRow`: Search is restricted to the row of the active cell.
1492+
1493+The search params record can be initialized by calling `InitSearchParams` (in unit *fpsutils*) with the record elements as optional parameters. Use the methods `Workbook.ActiveWorksheet` and `Worksheet.SelectCell(ARow, ACol)` to define the active worksheet and the position of the active cell, respectively, if needed by the search.
1494+
1495+In addition to searching the search engine can also be used for **replacing** the found text by another string. Call the functions `ReplaceFirst` or `ReplaceNext` for this purpose. They act like their `FindXXXX` counterparts, therefore, they require a `TsSearchParams` record to specify the search criteria. But in addition to searching, these functions also perform the text replacement according to the specification in a `TsReplaceParams` record:
1496+
1497+``` pascal
1498+type
1499+ TsReplaceParams = record
1500+ ReplaceText: String;
1501+ Options: TsReplaceOptions;
1502+ end;
1503+```
1504+
1505+The `ReplaceText` identifies the string which will replace the found text pattern. The `Options` define a set of criteria how the replacement is done:
1506+
1507+- `roReplaceEntirecell`: Replaces the entire cell text by the `ReplaceText`. If not contained in the `Options` then only the part matching the `SearchText` is replaced.
1508+- `roReplaceAll`: Performs the replacement in all found cells (i.e., simply call `ReplaceFirst` to replace all automatically).
1509+- `roConfirm`: Calls an event handler for the `OnConfirmReplacement` event in which the user must specify whether the replacement is to be performed or not. Note that this event handler is mandatory if `roConfirm` is set.
1510+
1511+Use the function `InitReplaceParams` (in unit *fpsutils*) to initialize the replace parameters record with the provided (but optional) values.
1512+
1513+### Column and row operations
1514+
1515+The worksheet provides these methods for inserting, deleting, hiding or unhiding columns and rows:
1516+
1517+``` pascal
1518+type
1519+ TsWorksheet = class
1520+ ...
1521+ procedure DeleteCol(ACol: Cardinal);
1522+ procedure DeleteRow(ARow: Cardinal);
1523+
1524+ procedure InsertCol(ACol: Cardinal);
1525+ procedure InsertRow(ARow: Cardinal);
1526+
1527+ procedure RemoveCol(ACol: Cardinal);
1528+ procedure RemoveRow(ARow: Cardinal);
1529+
1530+ procedure RemoveAllCols;
1531+ procedure RemoveAllRows
1532+
1533+ procedure HideCol(ACol: Cardinal);
1534+ procedure HideRow(ARow: Cardinal);
1535+
1536+ procedure ShowCol(ACol: Cardinal);
1537+ procedure ShowRow(ARow: Cardinal);
1538+
1539+ function ColHidden(ACol: Cardinal): Boolean;
1540+ function RowHidden(ARow: Cardinal): Boolean;
1541+```
1542+
1543+- When a column or row is **deleted** by `DeleteCol` or `DeleteRow`, any data assigned to this column or row are removed, i., cells, comments, hyperlinks, TCol or TRow records. Data at the right of or below the deleted column/row move to the left or up.
1544+
1545+- `RemoveCol` and `RemoveRow`, in contract, **remove** only the column or row record, i.e. reset column width and row height to their default values. Cell, comment, and hyperlink data are not affected.
1546+
1547+- `RemoveAllCols` **removes all** column records, i.e. resets all column widths; `RemoveAllRows` does the same with the row records and row heights.
1548+
1549+- A column or row is **inserted** before the index specified as parameter of the `InsertXXX` method.
1550+
1551+### Page layout
1552+
1553+#### General
1554+
1555+So far, FPSpreadsheet does not support printing of worksheets, but the Office applications do, and they provide a section of information in their files for this purpose. In FPSpreadsheets this information is available in the `TsPageLayout` class which belongs to the `TsWorksheet` data structure. Its properties and methods combine the most important features from the Excel and OpenDocument worlds.
1556+
1557+``` pascal
1558+type
1559+ TsPageOrientation = (spoPortrait, spoLandscape);
1560+
1561+ TsPrintOption = (poPrintGridLines, poPrintHeaders, poPrintPagesByRows,
1562+ poMonochrome, poDraftQuality, poPrintCellComments, poDefaultOrientation,
1563+ poUseStartPageNumber, poCommentsAtEnd, poHorCentered, poVertCentered,
1564+ poDifferentOddEven, poDifferentFirst, poFitPages);
1565+
1566+ TsPrintOptions = set of TsPrintOption;
1567+
1568+ TsHeaderFooterSectionIndex = (hfsLeft, hfsCenter, hfsRight);
1569+
1570+ TsCellRange = record
1571+ Row1, Col1, Row2, Col2: Cardinal;
1572+ end;
1573+
1574+ TsPageLayout = class
1575+ ...
1576+ public
1577+ ...
1578+ { Methods }
1579+ // embedded header/footer images
1580+ procedure AddHeaderImage(AHeaderIndex: Integer;
1581+ ASection: TsHeaderFooterSectionIndex; const AFilename: String);
1582+ procedure AddFooterImage(AFooterIndex: Integer;
1583+ ASection: TsHeaderFooterSectionIndex; const AFilename: String);
1584+ procedure GetImageSections(out AHeaderTags, AFooterTags: String);
1585+ function HasHeaderFooterImages: Boolean;
1586+
1587+ // Repeated rows and columns
1588+ function HasRepeatedCols: Boolean;
1589+ function HasRepeatedRows: Boolean;
1590+ procedure SetRepeatedCols(AFirstCol, ALastCol: Cardinal);
1591+ procedure SetRepeatedRows(AFirstRow, ALastRow: Cardinal);
1592+
1593+ // print ranges
1594+ function AddPrintRange(ARow1, ACol1, ARow2, ACol2: Cardinal): Integer; overload;
1595+ function AddPrintRange(const ARange: TsCellRange): Integer; overload;
1596+ function GetPrintRange(AIndex: Integer): TsCellRange;
1597+ function NumPrintRanges: Integer;
1598+ procedure RemovePrintRange(AIndex: Integer);
1599+
1600+ { Properties }
1601+ property Orientation: TsPageOrientation read FOrientation write FOrientation;
1602+ property PageWidth: Double read FPageWidth write FPageWidth;
1603+ property PageHeight: Double read FPageHeight write FPageHeight;
1604+ property LeftMargin: Double read FLeftMargin write FLeftMargin;
1605+ property RightMargin: Double read FRightMargin write FRightMargin;
1606+ property TopMargin: Double read FTopMargin write FTopMargin;
1607+ property BottomMargin: Double read FBottomMargin write FBottomMargin;
1608+ property HeaderMargin: Double read FHeaderMargin write FHeaderMargin;
1609+ property FooterMargin: Double read FFooterMargin write FFooterMargin;
1610+ property StartPageNumber: Integer read FStartPageNumber write SetStartPageNumber;
1611+ property ScalingFactor: Integer read FScalingFactor write SetScalingFactor;
1612+ property FitHeightToPages: Integer read FFitHeightToPages write SetFitHeightToPages;
1613+ property FitWidthToPages: Integer read FFitWidthToPages write SetFitWidthToPages;
1614+ property Copies: Integer read FCopies write FCopies;
1615+ property Options: TsPrintOptions read FOptions write FOptions;
1616+ property Headers[AIndex: Integer]: String read GetHeaders write SetHeaders;
1617+ property Footers[AIndex: Integer]: String read GetFooters write SetFooters;
1618+ property RepeatedCols: TsRowColRange read FRepeatedCols;
1619+ property RepeatedRows: TsRowColRange read FRepeatedRows;
1620+ property PrintRange[AIndex: Integer]: TsCellRange read GetPrintRange;
1621+ property FooterImages[ASection: TsHeaderFooterSectionIndex]: TsHeaderFooterImage read GetFooterImages;
1622+ property HeaderImages[ASection: TsHeaderFooterSectionIndex]: TsHeaderFooterImage read GetHeaderImages;
1623+ end;
1624+
1625+ TsWorksheet = class
1626+ ...
1627+ public
1628+ property PageLayout: TsPageLayout;
1629+ ...
1630+ end;
1631+```
1632+
1633+> **Note:** The fact that the `PageLayout` belongs to the worksheet indicates that there can be several page layouts in the same workbook, one for each worksheet.
1634+
1635+- **Orientation** defines the orientation of the printed paper, either portrait or landscape.
1636+
1637+- **Page width** and **page height** refer to the standard orientation of the paper, usually portrait orientation.
1638+
1639+- **Left**, **top**, **right** and **bottom margins** are self-explanatory and are given in millimeters.
1640+
1641+- **HeaderMargin** is understood - like in Excel - as the distance between the paper top edge and the top of the header, and **TopMargin** correspondingly is the distance between the top paper edge and the top of the first table row, i.e. if the header contains several line breaks it can reach into the the table part of the print-out. This is different from OpenDocument files where the header can grow accordingly.
1642+
1643+- **StartPageNumber** should be altered if the print-out should not begin with page 1. This setting requires to add the option `poUseStartPageNumber` to the PageLayout's `Options` - but this is normally done automatically.
1644+
1645+- The **ScalingFactor** is given in percent and can be used to reduce the number of printed pages. Modifying this property clear the option `poFitToPages` from the PageLayout's `Options`.
1646+
1647+- Alternatively to ScalingFactor, you can also use **FitHeightToPages** or **FitWidthToPages**. The option `poFitToPages` must be active in order to override the `ScalingFactor`setting. `FitHeightToPages` specifies the number of pages onto which the entire height of the printed worksheet should fit. Accordingly, `FitWidthToPages` can be used to define the number of pages on which the entire width of the worksheet has to fit. The value `0` has the special meaning of "use as many pages as needed". In this way, the setting "Fit all columns on one page" of Excel, for example, can be achieved by this code:
1648+
1649+``` pascal
1650+ MyWorksheet.PageLayout.Options := MyWorksheet.PageLayout.Options + [poFitPages];
1651+ MyWorksheet.PageLayout.FitWidthToPages := 1; // all columns on one page width
1652+ MyWorksheet.PageLayout.FitHeightToPages := 0; // use as many pages as needed
1653+```
1654+
1655+- **Header rows and columns repeated on every printed page** can be defined by the `RepeatedCols` and `RepeatedRows` records; their elements `FirstIndex` and `LastIndex` refer to the indexes of the first and last column or row, respectively, to be repeated. Use the methods `SetRepeatedCols` and `SetRepeatedRows` to define these numbers. Note that the second parameter for the last index can be omitted to use only a single header row or column.
1656+
1657+- **Print ranges** or **print areas** (using Excel terminology) can be used to restrict printing only to a range of cells. Use the methods `AddPrintRange` to define a cell range for printing: specify the indexes of the left column, top row, right column and bottom row of the range to be printed. A worksheet can contain several print ranges.
1658+
1659+- **Copies** specifies how often the worksheet will be printed.
1660+
1661+- The **Options** define further printing properties, their names are self-explaining. They were defined according to Excel files, some of them do not exist in ODS files and are ignored there.
1662+
1663+#### Headers and footers
1664+
1665+**Header and footer texts** can be composed of left-aligned, centered and right-aligned strings. Add the symbol `&L` to indicate that the following string is to be printed as the left-aligned part; use `&C` accordingly for the centered and `&R` for the right-aligned parts. There are other symbols which will be replaced by their counterparts during printing:
1666+
1667+- `&L`: begins the **left-aligned section** of a header or a footer text definition
1668+- `&C`: begins the **centered section** of a header or a footer text definition
1669+- `&R`: begins the **right-aligned section** of a header or a footer text definition
1670+- `&P`: **page number**
1671+- `&N`: **page count**
1672+- `&D`: current **date** of printing
1673+- `&T`: current **time** of printing
1674+- `&A`: **worksheet name**
1675+- `&F`: **file name** without path
1676+- `&Z`: **file path** without file name
1677+- `&G`: embedded **image** - use the methods `AddHeaderImage` or `AddFooterImage` to specify the image file; this also appends the `&G` to the other codes of the current header/footer section. Note that not all image types known by the Office application may be accepted. Currently the image can be *jpeg*, *png*, *gif*, *bmp*, *tiff*, *pcx*, *svg*, *wmf* or *emf*.
1678+- `&B`: **bold** on/off
1679+- `&I`: **italic** on/off
1680+- `&U`: **underlining** on/off
1681+- `&E`: **double-underlining** on/off
1682+- `&S`: **strike-out** on/off
1683+- `&H`: **shadow** on/off
1684+- `&O`: **outline** on/off
1685+- `&X`: **superscript** on/off
1686+- `&Y`: **subscript** on/off
1687+- `&"font"`: begin using of the **font** with the specified name, e.g. `&"Arial"`
1688+- `&number`: begin using of the specified **font size** (in points), e.g. `&16`
1689+- `&Krrggbb`: switch to the **font color** specified to the binary value of the specified color, e.g. use `&KFF0000` for red.
1690+
1691+The arrays `Headers[]`/`Footers[]` provide space for usage of three different headers or footers:
1692+
1693+- `Headers[0]` refers to the header used on the **first page** only, similarly for `Footers[0]`. Instead of index `0` you can use the constant `HEADER_FOOTER_INDEX_FIRST`. Leave this string empty if there is no special first-page header/footer.
1694+- `Headers[1]` refers to the header on pages with **odd page numbers**, similarly for `Footers[1]`. Instead of index `1` you may want to use the constant `HEADER_FOOTER_INDEX_ODD`.
1695+- `Headers[2]` refers to the header on lages with **even page nubmers**, similarly for `Footers[2]`. Instead of index `2` you may want to use the constant `HEADER_FOOTER_INDEX_EVEN`.
1696+
1697+Leave the strings at index 0 and 2 empty if the print-out should always have the same header/footer. You can use the constant `HEADER_FOOTER_INDEX_ALL` for better clarity. Example:
1698+
1699+``` pascal
1700+ MyWorksheet.PageLayout.Headers[HEADER_FOOTER_INDEX_ALL] := '&C&D &T'; // centered "date time" on all pages as header
1701+ MyWorksheet.PageLayout.Footers[HEADER_FOOTER_INDEX_ODD] := '&RPage &P of &N'; // right-aligned "Page .. of ..." on odd pages as footer
1702+ MyWorksheet.PageLayout.Footers[HEADER_FOOTER_INDEX_EVEN] := '&LPage &P of &N'; // dto, but left-aligned on even pages
1703+```
1704+
1705+### Protection
1706+
1707+In the Office applications, workbooks can be protected from unintentional changes by the user. fpspreadsheet is able to read and write the data structures related to protection, but does not enforce them. This means, for example, that cells can be modified by the user although the worksheet is specified as being locked.
1708+
1709+Protection is handled at three levels: workbook protection, worksheet protection and cell protection.
1710+
1711+#### Workbook protection
1712+
1713+`TsWorkbook` contains a set of workbook or document protection options:
1714+
1715+- `bpLockRevision`: specifies that the workbook is locked for revisions
1716+- `bpLockStructure`: if this option is set then worksheets in the workbook cannot be moved, deleted, hidden, unhidden, or renamed, and new worksheets cannot be inserted.
1717+- `bpLockWindows`: indicates that the workbook windows in the Office application are locked. Windows are the same size and position each time the workbook is opened by the Office application.
1718+
1719+In relation to workbook protection is the worksheet option `soPanesProtection` which prevents the panes of a worksheet from being modified if the workbook is protected.
1720+
1721+Depending on the file format, only some of these options might be supported. In these cases, the non-supported options are commonly accepted default values.
1722+
1723+Office applications are able to encrypt their spreadsheet files. The readers of FPSpreadsheet basically are not able to open these files. However, there exists a related package, **laz_fpspreadsheet_crypto.lpk**, which has access to decryption routines and is able to read xlsx and ods files. These readers are in the units *xlsxOOXML_crypto* and *fpsOpendocument_crypto*, respectively. Adding them to the uses clause of the application installs user-provided readers with `FormatID` `sfidOOXML_crypto` and `sfidOpenDocument_crypto`, respectively. If the password is known it can be specified as a parameter to the workbook's `LoadFromFile`/`ReadFromStream` methods. If no password is specified the workbook fires the event `OnQueryPassword` in which the user can provide the password, e.g. like this:
1724+
1725+``` pascal
1726+function TForm1.QueryPasswordHandler: String;
1727+begin
1728+ Result := InputBox('Password required', 'Password', '');
1729+end;
1730+
1731+procedure TForm1.LoadWorkbook(AFileName: String);
1732+var
1733+ workbook: TsWorkbook;
1734+begin
1735+ workbook := TsWorkbook.Create;
1736+ try
1737+ workbook.OnQueryPassword := @QueryPasswordHandler;
1738+ workbook.ReadFromFile(AFileName);
1739+ ...
1740+ finally
1741+ workbook.Free;
1742+ end;
1743+end;
1744+
1745+// or
1746+
1747+procedure TForm1.LoadWorkbookWithPassword(AFileName, APassword: STring);
1748+var
1749+ workbook: TsWorkbook;
1750+begin
1751+ workbook := TsWorkbook.Create;
1752+ try
1753+ workbook.ReadFromFile(AFileName, APassword);
1754+ ...
1755+```
1756+
1757+#### Worksheet protection
1758+
1759+`TsWorksheet` houses a similar set of protection options. Whenever an option is included in the set `Protection` of the workbook the corresponding action is not allowed and locked:
1760+
1761+- `spCells`: the cells in the sheet are protected. It depends on the level of cell protection whether a particular cell can be changed or not. By default, no cell can be changed.
1762+- `spDeleteColumns`: deleting of columns is not be allowed
1763+- `spDeleteRows`: it is not possible to delete rows
1764+- `spFormatCells`: formatting of cells is not allowed
1765+- `spFormatColumns`: columns cannot be formatted.
1766+- `spFormatRows`: rows cannot be formatted
1767+- `spInsertColumns`: it is not allowed to insert columns
1768+- `spInsertRows`: rows cannot be inserted
1769+- `spInsertHyperlinks`: it is not possible to insert new hyperlinks
1770+- `spSort`: the worksheet is not allowed to be sorted.
1771+- `spSelectLockedCells`: Cells which are locked cannot be selected any more.
1772+- `spSelectUnlockedCells`: Even cells which are unlocked cannot be selected. Together with `spSelectLockedCells` this means that the selection in the worksheet is frozen.
1773+
1774+These levels of protection become active if the option `soProtected` is added to the worksheet's `Options`, or by calling the worksheet method `Protect(true)`.
1775+
1776+#### Cell protection
1777+
1778+Cell protection becomes active when the worksheet protection is enabled. It is controlled by a set of `TsCellProtection` elements which belong to the cell format record:
1779+
1780+- `cpLockCell`: This option determines whether cell content can be modified by the user. Since it is on by default cells of a protected worksheet normally cannot be edited. In order to unlock some cells for user input the option `cpLockCell` must be removed from the protection of these cells.
1781+- `cpHideFormulas`: prevents formulas from being shown in the Office application.
1782+
1783+Cell protection can be changed by calling the worksheet method `WriteCellProtection`. Conversely, `ReadCellProtection` can be used to retrieve the protection state of a particular cell:
1784+
1785+``` pascal
1786+// query and modifiy the protection state of cell A1 (row=0, col=0)
1787+var
1788+ cell: PCell;
1789+ cellprot: TsCellProtections;
1790+...
1791+ // Find the cell
1792+ cell := worksheet.FindCell(0, 0);
1793+ // query cell protection
1794+ cellprot := worksheet.ReadCellProtection(cell);
1795+ // Unlock the cell for editing, don't change the visibility of formulas
1796+ worksheet.WriteCellProtection(cell, cellprot - [cpLockCell]);
1797+ // Hide formula of the cell and unlock the cell.
1798+ worksheet.WriteCellProtection(cell, [cpHideFormulas]);
1799+ // Activate protection
1800+ worksheet.Protect(true);
1801+```
1802+
1803+#### Passwords
1804+
1805+Workbook and worksheet protection can be secured by passwords. Note that these passwords do not encrypt the file (except for workbook protection in Excel 2007). In the Office applications the user must enter this password to turn off protection or to change protection items. The encrypted password is stored in the `CryptoInfo` record of the wordbook and the worksheets, respectively:
1806+
1807+``` pascal
1808+type
1809+ TsCryptoInfo = record
1810+ PasswordHash: String;
1811+ Algorithm: TsCryptoAlgorithm; // caExcel, caSHA1, caSHA256, etc.
1812+ SaltValue: String;
1813+ SpinCount: Integer;
1814+ end;
1815+```
1816+
1817+> **Warning:** FPSpreadsheet does not perform any hashing calculations, the `CryptoInfo` record is just passed through from reading to writing. This causes problems when different file formats are involved in reading and writing. It is attempted to detect **incompatible combinations**. In these cases, the **password protection is removed**, and an error is logged by the workbook.
1818+
1819+### Loading and saving
1820+
1821+#### Adding new file formats
1822+
1823+FPSpreadsheet is open to any spreadsheet file format. In addition to the built-in file formats which are specified by one of the `sfXXXX` declarations, it is possible to provide dedicated reader and writer units to get access to special file formats.
1824+
1825+- Write a unit implementing a reader and a writer for the new file format. They must inherit from the basic `TsCustomSpreadReader` and `TsCustomWriter`, respectively, - both are implemented in unit *fpsReaderWriter* -, or from one of the more advanced ones belonging to the built-in file formats.
1826+- Register the new reader/writer by calling the function `RegisterSpreadFileFormat` in the `initialization` section of this unit (implemented in unit *fpsRegFileFormats*):
1827+
1828+``` pascal
1829+function RegisterSpreadFormat(AFormat: TsSpreadsheetFormat; AReaderClass: TsSpreadReaderClass; AWriterClass: TsSpreadWriterClass;
1830+ AFormatName, ATechnicalName: String; const AFileExtensions: array of String): TsSpreadFormatID;
1831+```
1832+
1833+- `AFormat` must have the value `sfUser` to register an external file format.
1834+- `AReaderClass` is the class of the reader (or nil, if reading functionality is not implemented).
1835+- `AWriterClass` is the class of the writer (or nil, if writing functionality is not implemented).
1836+- `AFormatName` defines the name of the format as used for example in the filter list of file-open dialogs.
1837+- `ATechnicalName` defines a shorter format name.
1838+- `AFileExtensions` is an array of file extensions used in the files. The first array element denotes the default extension. The extensions must begin with a period as in `.xls`.
1839+- The registration function returns a numerical value (`TsSpreadFormatID`) which can be used as format identifier in the workbook reading and writing functions which exist in overloaded version accepting a numerical value for the format specifier. In contract to the built-in formats the FormatID is negative.
1840+- Finally, in your application, add the new unit to the `uses` clause. This will call the registrations function when the unit is loaded and make the new file format available to FPSpreadsheet.
1841+
1842+#### Stream selection
1843+
1844+Workbooks are loaded and saved by means of the `ReadFromFile` and `WriteToFile` methods, respectively (or by their stream counterparts, `ReadFromStream` and `WriteToStream`).
1845+
1846+By default, the data files are accessed by means of **memory streams** which yields the fastest access to the files. In case of very large files (e.g. tens of thousands of rows), however, the system may run out of memory. There are two methods to defer the memory overflow by some extent.
1847+
1848+- Add the element `boBufStream` to the workbook's `Options`. In this case, a **"buffered" stream** is used for accessing the data. This kind of stream holds a memory buffer of a given size and swaps data to file if the buffer becomes too small.
1849+- Add the element `boFileStream` to the workbook's `Options`. This option avoids memory streams altogether and creates temporary **files** if needed. This is, however, the slowest method of data access.
1850+- If both options are set then `boBufStream` is ignored.
1851+- In practice, however, the effect of the selected streams is not very large if memory is to be saved.
1852+
1853+#### Virtual mode
1854+
1855+Beyond the transient memory usage during reading/writing the main memory consumptions originates in the internal structure of FPSpreadsheet which holds all data in memory. To overcome this limitation, a "virtual mode" has been introduced. In this mode, data are received from a data source (such as a database table) and are passed through to the writer without being collected in the worksheet. It is clear that data loaded in virtual mode cannot be displayed in the visual controls. Virtual mode is good for conversion between different data formats.
1856+
1857+These are the steps required to use this mode:
1858+
1859+- Activate virtual mode by adding the option `boVirtualMode` to the `Options` of the workbook.
1860+- Tell the spreadsheet writer how many rows and columns are to be written. The corresponding worksheet properties are `VirtualRowCount` and `VirtualColCount`.
1861+- Write an event handler for the event `OnWriteCellData` of the worksheet. This handler gets the index of row and column of the cell currently being saved. You have to return the value which will be saved in this cell. You can also specify a template cell that physically exists in the workbook from which the formatting style is copied to the destination cell. Please be aware that when exporting a database, you are responsible for advancing the dataset pointer to the next database record when writing of a row is complete.
1862+- Call the `WriteToFile` method of the workbook.
1863+
1864+Virtual mode also works for reading spreadsheet files.
1865+
1866+The folder *example/other* contains a worked out sample project demonstrating virtual mode using random data. More realistic database examples are in *example/db_import_export* and in the chapter on converting a large database table using virtual mode.
1867+
1868+### Dataset export
1869+
1870+FPC contains a set of units that allow you to export datasets to various formats (XML, SQL statements, DBF files,...). There is a master package that allows you to choose an export format at design time or run time (Lazarus package lazdbexport).
1871+
1872+FPSpreadsheet has `TFPSExport` which plugs into this system. It allows you to export the contents of a dataset to a new spreadsheet (*.xls*, *.xlsx*, *.ods*, wikitable format) file into a table on the first sheet by default. In addition, if `MultipleSheets` is set to `TRUE` it is possible to combine several sheets into individual worksheets in the same file. You can optionally include the field names as header cells on the first row using the `HeaderRow` properties in the export settings. The export component tries to find the number format of the cells according to the dataset field types.
1873+
1874+For more complicated exports, you need to manually code a solution (see examples below) but for simple data transfer/dynamic exports at user request, this unit will probably be sufficient.
1875+
1876+A simple example of how this works:
1877+
1878+``` pascal
1879+uses
1880+...
1881+fpsexport
1882+...
1883+var
1884+ Exp: TFPSExport;
1885+ ExpSettings: TFPSExportFormatSettings;
1886+ TheDate: TDateTime;
1887+begin
1888+ FDataset.First; //assume we have a dataset called FDataset
1889+ Exp := TFPSExport.Create(nil);
1890+ ExpSettings := TFPSExportFormatSettings.Create(true);
1891+ try
1892+ ExpSettings.ExportFormat := efXLS; // choose file format
1893+ ExpSettings.HeaderRow := true; // include header row with field names
1894+ Exp.FormatSettings := ExpSettings; // apply settings to export object
1895+ Exp.Dataset:=FDataset; // specify source
1896+ Exp.FileName := 'c:\temp\datadump.xls';
1897+ Exp.Execute; // run the export
1898+ finally
1899+ Exp.Free;
1900+ ExpSettings.Free;
1901+ end;
1902+```
1903+
1904+#### Export to DBF
1905+
1906+You can save the information from Excel to dbf rather easily. Here is the example from forum. Please note that this example is supposed to work with Win1251 encoding by default. To get more information please refer to this thread [1](http://forum.lazarus.freepascal.org/index.php/topic,41636.0.html)
1907+
1908+``` pascal
1909+procedure TForm1.ExportToDBF(AWorksheet: TsWorksheet; AFileName: String);
1910+var
1911+ i: Integer;
1912+ f: TField;
1913+ r, c: Cardinal;
1914+ cell: PCell;
1915+begin
1916+ DbfGlobals.DefaultCreateCodePage := 1251; //default encoding of the dbf
1917+ DbfGlobals.DefaultOpenCodePage := 1251; //default encoding of the dbf
1918+ if Dbf1.Active then Dbf1.Close;
1919+ if FileExists(AFileName) then DeleteFile(AFileName);
1920+
1921+ Dbf1.FilePathFull := ExtractFilePath(AFileName);
1922+ Dbf1.TableName := ExtractFileName(AFileName);
1923+ Dbf1.TableLevel := 25; // DBase IV: 4 - most widely used; or 25 = FoxPro supports nfCurrency
1924+ Dbf1.LanguageID := $C9; //russian language by default
1925+ Dbf1.FieldDefs.Clear;
1926+ //below are the fields in excel
1927+ Dbf1.FieldDefs.Add('fam', ftString);
1928+ //add other fields you want to save
1929+
1930+ Dbf1.CreateTable;
1931+ Dbf1.Open;
1932+
1933+ for f in Dbf1.Fields do
1934+ f.OnGetText := @DbfGetTextHandler;
1935+
1936+ // Skip row 0 which contains the headers
1937+ for r := 1 to AWorksheet.GetLastRowIndex do begin
1938+ Dbf1.Append;
1939+ for c := 0 to Dbf1.FieldDefs.Count-1 do begin
1940+ f := Dbf1.Fields[c];
1941+ cell := AWorksheet.FindCell(r, c);
1942+ if cell = nil then
1943+ f.Value := NULL
1944+ else
1945+ case cell^.ContentType of
1946+ cctUTF8String: f.AsString := UTF8ToCP1251(cell^.UTF8StringValue);
1947+ cctNumber: f.AsFloat := cell^.NumberValue;
1948+ cctDateTime: f.AsDateTime := cell^.DateTimeValue;
1949+ else f.AsString := UTF8ToCP1251(AWorksheet.ReadAsText(cell));
1950+ end;
1951+ end;
1952+ Dbf1.Post;
1953+ end;
1954+end;
1955+
1956+//This procedure is called so the text in the cells could be correctly dispayed on WorkSheetGrid on the form, otherwise '?' symbols showing
1957+procedure TForm1.DbfGetTextHandler(Sender: TField; var AText: string; DisplayText: Boolean);
1958+begin
1959+ if DisplayText then
1960+ AText := CP1251ToUTF8(Sender.AsString);
1961+end;
1962+```
1963+
1964+## Visual controls for FPSpreadsheet
1965+
1966+The package **laz_fpspreadsheet_visual** implements a series of controls which simiplify creation of visual GUI applications:
1967+
1968+- **TsWorkwookSource** links the controls to a workbook and notifies the controls of changes in the workbook.
1969+- **[[TsWorksheetGrid]]** implements a grid control with editing and formatting capabilities; it can be applied in a similar way to TStringGrid.
1970+- **TsWorkbookTabControl** provides a tab sheet for each worksheet of the workbook. It is the ideal container for a [[TsWorksheetGrid]].
1971+- **TsWorksheetIndicator**: a combobox which lists all worksheets of the workbook.
1972+- **TsCellEdit** corresponds to the editing line in Excel or Open/LibreOffice. Direct editing in the grid, however, is possible as well.
1973+- **TsCellIndicator** displays the name of the currently selected cell; it can be used for navigation purposes by entering a cell address string.
1974+- **TsCellCombobox** offers to pick cell properties for a selection of formatting attributes: font name, font size, font color, background color.
1975+- **TsSpreadsheetInspector** is a tool mainly for debugging; it displays various properties of workbook, worksheet, cell value and cell formatting, similar to the ObjectInspector of Lazarus. It is read-only, though.
1976+- Various standard actions are provided in the unit **fpsActions**. Applied to menu or toolbar, they simplify typical formatting and editing tasks without having to write a line of code.
1977+- **TsWorkbookChartSource** interfaces a workbook with the [[TAChart]] library. It defines the cell ranges from which a Chart series can get its data. There is also an older component, [[TsWorksheetChartSource]], which requires all cells to be from the same worksheet. For this reason, it has not been fully integrated into the environment of FPSpreadsheet controls and will be removed from the library in the future.
1978+
1979+See the [[FPSpreadsheet tutorial: Writing a mini spreadsheet application]] for more information and a tutorial, and see demo projects for examples of the application of these components.
1980+
1981+## Examples
1982+
1983+Please see [[FPSpreadsheet: Examples]] for a variety of code examples.
1984+
1985+## Download
1986+
1987+### Subversion
1988+
1989+You can download FPSpreadsheet using the subversion software and the following command line:
1990+
1991+``` bash
1992+svn checkout https://svn.code.sf.net/p/lazarus-ccr/svn/components/fpspreadsheet fpspreadsheet
1993+```
1994+
1995+### Stable releases
1996+
1997+The most current release is distributed by the Online-Package-Manger which is integrated in the Lazarus IDE (menu "Package" \> "Online package manager"): Scroll down the list of available packages, check the entry "FPSpreadsheet" and click "Install". Confirm the prompt to rebuild the IDE. When the process is complete you find the new components in palette "FPSpreadsheet".
1998+
1999+Older releases of FPSpreadsheet cann still be found on [sourceforge](https://sourceforge.net/projects/lazarus-ccr/files/FPSpreadsheet/).
2000+
2001+## Installation
2002+
2003+- If you only need non-GUI components: in Lazarus: Package/Open Package File, select **laz_fpspreadsheet.lpk**, click Compile. Now the package is known to Lazarus (and should e.g. show up in Package/Package Links). Now you can add a dependency on `laz_fpspreadsheet` in your project options and `fpspreadsheet` to the uses clause of the project units that need to use it.
2004+- If you also want GUI components ([[TsWorksheetGrid]] and [[TsWorksheetChartSource]]): Package/Open Package File, select **laz_fpspreadsheet_visual.lpk**, click Compile, then click Use, Install and follow the prompts to rebuild Lazarus with the new package. Drop needed grid/chart components on your forms as usual.
2005+- If you want to have a GUI component for dataset export: Package/Open Package File, select **laz_fpspreadsheetexport_visual.lpk**, click Compile, then click, Use, Install and follow the prompts to rebuild Lazarus with the new package. Drop needed export components from the **Data Export** tab on your forms as usual.
2006+- FPSpreadsheet is developed with the latest stable fpc version (currently fpc 3.0.2). We only occasionally check older versions.
2007+- The basic spreadsheet functionality works with Lazarus versions back to version 1.0. Some visual controls or demo programs, however, require newer versions. Please update your Lazarus if you have an older version and experience problems.
2008+
2009+### Conditional defines
2010+
2011+Here is a list of **conditional defines** which can be activated in order to tweak some operating modes of the packages and/or make it compilable with older Lazarus/FPC versions:
2012+
2013+- `FPS_DONT_USE_CLOCALE`: In Unix systems, the unit `clocale` is automatically added to the uses clause of *fpspreadsheet.pas*. This unit sets up localization settings needed for locale-dependent number and date/time formats. However, this adds a dependence on the C library to the package [2](http://lazarus-ccr.sourceforge.net/docs/rtl/clocale/index.html). If this is not wanted, define `FPS_DONT_USE_CLOCALE`.
2014+- `FPS_VARISBOOL`: fpspreadsheet requires the function VarIsBool which was introduced by fpc 2.6.4. If an older FPC versions is used define `FPS_VARISBOOL`. Keep undefined for the current FPC version.
2015+- `FPS_LAZUTF8`: fpspreadsheet requires some functions from the unit LazUTF8 which were introduced by Lazarus 1.2. If an older Lazarus version is used define `FPS_LAZUTF8`. Keep undefined for the current Lazarus version.
2016+- `FPS_NO_GRID_MULTISELECT`: In order to allow selection of multiple ranges in the WorksheetGrid a sufficiently new version of the basic TCustomGrid is needed. The required property "RangeSelect" was introduced in Lazarus 1.4. In order to compile the package with older versions activate the define `FPS_NO_GRID_MULTISELECT`.
2017+- `FPS_PTRINT`: In order to provide safe casting of integers to pointers new version of FPC provide the types PtrInt and IntPtr. This is not yet available in fpc 2.6.0.
2018+- `FPS_NEED_STRINGHASHLIST`: Unit stringhashlist belongs to LCL before Lazarus 1.8. To avoid a requirement of LCL in laz_fpspreadsheet.lpk a copy in the fps directory is provided. This copy is used when the define FPS_NEED_STRINGHASHLIST is active. The define is not needed for Lazarus versions \>= 1.8.
2019+- `FPS_NO_NEW_UTF8_ROUTINES`: In Lazarus 2.0+ some UTF8 routines in unit LazUTF8 were renamed from UTF8CharacterXXX to UTF8CodePointXXX. Activate the following define when the new routines are not available, i.e. for Lazarus version \< 2.0.
2020+- `FPS_NO_LAZUTF16`: Lazarus 1.8+ has unit LazUTF16 for special access to widestring. This define must be active when this unit is not available, i.e. for Lazarus versions before 1.8.0.
2021+- `FPS_NO_STRING_SPLIT`: Activate the following define if FPS does not have the string Split helper, e.g. before v3.0
2022+
2023+All these defines are collected in the include file *fps.inc*.
2024+
2025+In the most recent test (Feb 2023), all fpspreadsheet packages compile fine with Laz 1.6+ / fpc 3.0+ (some defines in *fps.inc* may have to be adapted, though). With Laz 1.4 / fpc 2.6.4 or older, *fpspreadsheet_dataset.lpk* and *fpspreadsheet_crypto.lpk* cannot be used any more.
2026+
2027+## Support and Bug Reporting
2028+
2029+The recommended place to discuss FPSpreadsheet and obtain support is asking in the [Lazarus Forum](http://forum.lazarus.freepascal.org/index.php?board=49.0).
2030+
2031+Bug reports should be sent to the [Lazarus/Free Pascal Bug Tracker](http://bugs.freepascal.org/); please specify the "Lazarus-CCR" project.
2032+
2033+## Current Progress
2034+
2035+### Progress by supported cell content
2036+
2037+<thead>
2038+
2039+sheets</th>
2040+
2041+support</th>
2042+
2043+support</th>
2044+
2045+Formula</th>
2046+
2047+Formula</th>
2048+
2049+references</th>
2050+
2051+formats</th>
2052+
2053+</thead>
2054+<tbody>
2055+
2056+</tbody>
2057+
2058+(+) Depends on file.\
2059+(++) No "true" number format support because the file does not containg number formatting information. But the number format currently used in the spreadsheet understood.\
2060+(+++) Only very basic image support: no transformations, no cropping, no image manipulation.\
2061+(++++) Extended OOXML formatting options not supported.\
2062+(*) In formats which don't support Unicode the data is stored by default as ISO 8859-1 (Latin 1). You can change the encoding in TsWorkbook.Encoding. Note that FPSpreadsheet offers UTF-8 read and write routines, but the data might be converted to ISO when reading or writing to the disk. Be careful that characters which don't fit selected encoding will be lost in those operations. The remarks here are only valid for formats which don't support Unicode.\
2063+(**) Some cell could be returned blank due to missing or non ready implemented number and text formats.\
2064+(***) This is the format in which the formulas are written to file (determined by design of the file format).\
2065+(****) Writing of all formats is supported. Some rare custom formats, however, may not be recognized correctly. BIFF2 supports only built-in formats by design.
2066+
2067+### Progress of the formatting options
2068+
2069+The following formatting options are available:
2070+
2071+<thead>
2072+
2073+alignment</th>
2074+
2075+rotation</th>
2076+
2077+text</th>
2078+
2079+support</th>
2080+
2081+ground</th>
2082+
2083+wrap</th>
2084+
2085+size</th>
2086+
2087+format</th>
2088+
2089+cells</th>
2090+
2091+layout</th>
2092+
2093+ranges</th>
2094+
2095+images</th>
2096+
2097+format</th>
2098+
2099+cols/rows</th>
2100+
2101+breaks</th>
2102+
2103+</thead>
2104+<tbody>
2105+
2106+(Excel 5.0 and 95)</td>
2107+
2108+(Excel 97 - XP)</td>
2109+
2110+</tbody>
2111+
2112+(N/A) Feature is not available for this format intrinsically.\
2113+(*) BIFF2 supports only horizontal text alignment, vertical alignment is ignored.\
2114+(**) BIFF2 does not support a background color; a dotted black&white background is used instead.\
2115+(***) OpenDocument supports only uniform backgrounds; a fill color interpolated between foreground and background colors is written instead.\
2116+(****) Only uniform background color, no fill styles.\
2117+(+) HTML reader does not support styles. Since the writer does use styles these files are not read back correctly.
2118+
2119+### Progress of workbook/worksheet user-interface options
2120+
2121+Some additional options were added to interface the file contents with the `TsWorksheetGrid`:
2122+
2123+| Format | Hide grid lines | Hide headers | Frozen Panes | Active sheet/cell | Zooming | BiDi mode | Tab color |
2124+|----|----|----|----|----|----|----|----|
2125+| Excel 2.x | Working | Working | not working | N/A | N/A | N/A | N/A |
2126+| Excel 5.0 (Excel 5.0 and 95) | Working | Working | Working | Working | Working | N/A | N/A |
2127+| Excel 8.0 (Excel 97 - XP) | Working | Working | Working | Working | Working | Working | Working |
2128+| Excel2003/XML | Working | Working | Working | Working | Working \|\| class="working\|Working | N/A | |
2129+| Excel OOXML | Working | Working | Working | Working | Working | Working | Working |
2130+| OpenDocument | Working | Working | Working | Working | Working | Working | Working |
2131+| HTML | Writing only | Writing only | N/A | N/A | N/A | not working | N/A |
2132+
2133+### To do list
2134+
2135+Note: this list is provisional, maintained by developers and can change without notice. If you are interested in contributing, please feel free to get in touch and submit a patch - thanks!
2136+
2137+- Find out why BIFF2 files are corrupt when saved with frozen rows/cols activated.
2138+- Add row and column formats
2139+- Add reading support for wikitable (Mediawiki) files
2140+- xls reader crashes for some incorrectly written xls files (which Excel can read), see [<http://forum.lazarus.freepascal.org/index.php/topic,25624.0.html>](http://forum.lazarus.freepascal.org/index.php/topic,25624.0.html).
2141+- Improve color support: due to palette support colors may change from file to file currently.
2142+- Add embedded images.
2143+- Fix writing of cell comments to BIFF8 files.
2144+
2145+**Long-term:**
2146+
2147+- Provide a more common user interface to fpspreadsheet (setter/getter and properties instead of Read*/Write* methods, MyWorksheet.Cells\[ARow, ACol\]), make TCell a class, avoid the pointers PCell.
2148+- Store formatting in a format list of the workbook, not in the cell, to reduce memory usage.
2149+- Use BIFF8 file-wide string storage instead of storing strings in cells (should reduce memory usage in case of many duplicate strings)
2150+- Redo ooxml and ods readers based upon SAX/TXmlReader instead of DOM to reduce memory usage of large files.
2151+- Add an fpspreadsheetexport unit and component on "Data Export" tab similar to [[fpdbfexport]] FPSpreadsheetexport demo preferably with all export formats component. Find a way to register export format to all formats (look into how lazreport pdf export performs a similar procedure).
26922152
26932153## Changelog
26942154
26952155### SVN
26962156
26972157**Changes with respect to current release**
26982158
26992159- (currently none)
27002160
27012161**Incompatible changes**
27022162
27032163- (currently none)
27042164
27052165### Version 1.16
27062166
27072167This is the latest stable release.
27082168
27092169**Changes with respect to current release**
27102170
27112171- XLSX reader can handle embedded as well as header/footer images now.
27122172- Less strict format check by Excel2 reader since there are BIFF2 files with BOF record of Excel8 which Excel can read.
27132173- Reading support for the Excel3 and Excel4 formats (unit *xlsbiff34*)
27142174- ODS reader supports the \<text:s\> node
27152175- ODS reader is able to open encrypted files.
27162176
27172177**Incompatible changes**
27182178
27192179- (none)
27202180
27212181### Version 1.14
27222182
27232183**Changes with respect to v1.12**
27242184
27252185- Implementation of **conditional formats** for ods, xlsx and Excel xml.
27262186- Implementation of **meta data** for ods, xlsx and Excel xml.
27272187- Add a worksheet-based dataset in separate package (**TsWorksheetDataset**).
27282188
27292189**Incompatible changes**
27302190
27312191- Removed the deprecated worksheet properties DefaultRowHeight and DefaultColWidth. Use the corresponding Read/Write routines instead (ReadDefaultColWidth(units), WriteDefaultColWidth(units)).
27322192
27332193### Version 1.12
27342194
27352195**Changes with respect to v1.10x**
27362196
27372197- **Hide** (and unhide) rows and columns.
27382198- Enforce **Page breaks** before rows and columns during printing by the Office applications.
27392199- Full support (reading and writing) of the **ExcelXML** xml format (Excel 2003 and XP).
27402200- Support of the color of worksheet tabs (Worksheet.TabColor) in xls biff8, xlsx and ods formats. The property is ignored by the visual WorkbookTabControl, though.
27412201- Add TsWorksheetIndicator to visual controls.
27422202
27432203### Version 1.10.1
27442204
27452205**Changes with respect to v1.8x**
27462206
27472207- **Workbook, worksheet and cell protection** (read/write in BIFF2/BIFF5/BIFF8/OOXML/ODS, write in ExcelXML).
27482208- New package **laz_fpspreadsheet_crypto** to decipher the encryption for worksheet-protection in xls files. Requires DCPcrypt.
27492209- TsWorksheetGrid can **display embedded images**.
27502210- **Drag and drop** in TsWorksheetGrid
27512211- New, **highDPI-aware** component palette icons.
27522212- New workbook optiond **boAbortReadingOnFormulaError** and **boIgnoreFormulas**.
27532213- Formulas with **references to other sheets**, i.e. `'=Sheet1!A1+Sheet2!A2'`
27542214
27552215**Incompatible changes**
27562216
27572217- The field **FormulaValue** has been removed from the cell record. The cell formula now can be retrieved by calling `Worksheet.ReadFormula(cell)`.
27582218
27592219### Version 1.8
27602220
27612221**Changes with respect to v1.6x**
27622222
27632223- **"Rich-text" formatting** of label cells, i.e. assignment different fonts to groups of characters within the cell text. For this purpose, HTML codes (such as `<B>...</B>`) can be embedded in the cell text to identify the parts with different font (--\> `TsWorksheet.WriteTextAsHTML`).
27642224- **Searching** for cells with specified content in worksheet or workbook.
27652225- Support for reading and writing of **HTML format**
27662226- Support for writing of the **ExcelXML format** (Excel XP and 2003)
27672227- Ability to use **user-provided file reader/writer classes** to extend FPSpreadsheet to new file formats.
27682228- Readers and writers now support all the **line styles** of Excel8 and OOXML.
27692229- xls, xlsx and ods readers/writers now support the **active worksheet** and **selected cell**.
27702230- Ability to write to/read from the system's **clipboard** for copy & paste using the visual controls.
27712231- Support for **print ranges** and **repeated header rows and columns** in the Office applications.
27722232- Support for **embedded images** (currently only writing to xlsx and ods, no reading).
27732233- Improved compatibility of **TsWorksheetGrid** with TStringGrid (`Cells[Col,Row]` property). Standalone application as an advanced StringGrid replacement.
27742234- Support for **Right-to-left mode** in TsWorksheetGrid. In addition to the system-wide RTL mode, there are also parameters `BiDiMode` in the Worksheet and cells allowing to controls text direction at worksheet and cell level individually, like in Excel or LibreOffice Calc.
27752235- Support of several **units** for specification of column widths and row heights.
27762236- The library now supports **localization** using po files. Translations are welcome.
27772237- **Zoom factor** read and written by the worksheet, and applied by the TsWorksheetGrid.
27782238- Support of **column and row formats**
27792239- Support of **hidden** worksheets
27802240
27812241**Incompatible changes**
27822242
27832243- VirtualMode was changed in order to be able to treat worksheets of the same workbook differently. `VirtualRowCount` and `VirtualColCount` are now properties of the worksheet, and similarly, the event handler `OnWriteCellData`. In older versions, these properties had belonged to the workbook.
27842244- The worksheet methods `ReadAsUTF8Text` and `WriteUTF8Text` have been renamed to `ReadAsText` and `WriteText`, respectively. The old ones are still available and marked as deprecated; they will be removed in later versions.
27852245- The public properties of `TsWorksheetGrid` using a `TRect` as parameter were modified to use the Left, Top, Right, Bottom values separately.
27862246- The `PageLayout` is a class now, no longer a record. As a consequence, some array properties cannot be set directly any more, use the corresponding methods instead.
27872247- Most of the predefined color constants were marked as deprecated; only the basic EGA colors will remain.
27882248- Unit fpsNumFormatParser is integrated in fpsNumFormat. Old code which "uses" fpsNumFormatParser must "use" fpsNumFormat now.
27892249- The source files of the laz_fpspreadsheet, laz_fpspreadsheet_visual and laz_fpspreadsheetexport_visual packages have been moved to separate folders in order to resolve some occasional compilation issues. Projects which do not use the packages but the path to the sources must adapt the paths.
27902250
27912251### Version 1.6
27922252
27932253**Changes with respect to v1.4.x**
27942254
27952255- TsWorkbookChartSource is a new component which facilitates creation of charts from non-contiguous spreadsheet data in various worksheets. It interfaces to a workbook via tha WorkbookSource component. In the long run, it will replace the older TsWorksheetChartSource which required contiguous x/y data blocks in the same worksheet.
27962256- Major reconstruction of the cell record resulting in strong reduction of memory consumption per cell (from about 160 bytes per cell down to about 50)
27972257- Implementation of a record helper for the TCell which simplifies cell formatting (no need to set a bit in UsedFormattingFields any more, automatic notification of visual controls)
27982258- Comments in cells
27992259- Background fill patterns
28002260- Hyperlinks
28012261- Enumerators for worksheet's internal AVLTrees for faster iteration using a for-in loop.
28022262- Formatting of numbers as fractions.
28032263- Improved number format parser for better recognition of Excel-like number formats.
28042264- Page layout (page margins, headers, footer, used for only when printing in the Office applications - no direct print support in fpspreadsheet!)
28052265- Improved color management: no more palettes, but direct rgb colors. More pre-defined colors.
28062266- A snapshot of the wiki documentation is added to the library as chm help file.
28072267
28082268**Incompatible changes**
28092269
28102270- All type declarations and constants are moved from fpspreadsheet.pas to the new unit **fpstypes.pas**. Therefore, most probably, this unit has to be added to the uses clause.
28112271- Because fpspreadsheet supports now **background** fill patterns the cell property `BackgroundColor` has been replaced by `Background`. Similarly, the `UsedFormattingFields` flag `uffBackgroundColor` is called `uffBackground` now.
28122272- Another `UsedFormattingFields` flag has been dropped: **`uffBold`**. It is from the early days of fpspreadsheet and has become obsolete since the introduction of full font support. For achieving a bold type-face, now call `MyWorksheet.WriteFont(row, col, BOLD_FONTINDEX)`, or `Myworksheet.WriteFontStyle(row, col, [fssBold])`.
28132273- **Iteration through cells** using the worksheet methods `GetFirstCell` and `GetNextCell` has been removed - it failed if another iteration of this kind was called within the loop. Use the new for-in syntax instead.
28142274- Support for **shared formulas** has been reduced. The field `SharedFormulaBase` has been deleted from the TCell record, and methods related to shared formulas have been removed from TsWorksheet. Files containing shared formulas can still be read, the shared formulas are converted to multiple normal formulas.
28152275- The **color palettes** of previous versions have been abandoned. `TsColor` is now a `DWord` representing the rgb components of a color (just like TColor does in the *graphics* unit), it is not an index into a color palette any more. The values of pre-defined colors, therefore, have changed, their names, however, are still existing. The workbook functions for palette access have become obsolete and were removed.
28162276
28172277### Version 1.4
28182278
28192279**Changes with respect to v1.2.x**
28202280
28212281- Full support for **string formulas**; calculation of RPN and string formulas for all built-in formulas either directly or by means of registration mechanism. Calculation occurs when a workbook is saved (activate workbook option `boCalcBeforeSaving`) or when cell content changes (active workbook option `boAutoCalc`).
28222282- **Shared formulas** (reading for sfExcel5, sfExcel8, sfOOXML; writing for sfExcel2, sfExcel5, sfExcel8).
28232283- Significant **speed-up** of writing of large spreadsheets for the xml-based formats (ods and xlsx), speed up for biff2; **speedtest demo** program
28242284- **VirtualMode** allowing to read and write very large spreadsheet files without loading entire document representation into memory. Formatting of cells in VirtualMode.
28252285- Demo program for database export using virtual mode and TFPSExport.
28262286- Added db export unit allowing programmatic exporting datasets using **TFPSExport**. Similar export units are e.g. [[fpdbfexport]], [[fpXMLXSDExport]].
28272287- Reader for **xlsx** files, now fully supporting the same features as the other readers.
28282288- Reader/writer for **CSV files** based on [[CsvDocument]].
28292289- **Wikitables writer** supports now most of the fpspreadsheet formatting options (background color, font style, font color, text alignment, cell borders/line styles/line colors, merged cells, column widths, row heights); new "wikitablemaker" demo
28302290- **Insertion and deletion of rows and columns** into a worksheet containing data.
28312291- Implementation of **sorting** of a worksheet.
28322292- Support of **diagonal "border" lines**
28332293- **Logging of non-fatal error messages** during reading/writing (TsWorksheet.ErrorMsg)
28342294- **Merged** cells
28352295- **Registration** of currency strings for automatic conversion of strings to **currency values**
28362296- A set of **visual controls** (TsWorkbookSource, TsWorkbookTabControl, TsSpreadsheetInspector, TsCellEdit, TsCellIndicator, TsCellCombobox, in addition to the already-existing TsWorksheetGrid) and pre-defined standard actions to facilitate [[FPSpreadsheet tutorial: Writing a mini spreadsheet application|creation of GUI applications]].
28372297- **Overflow cells** in TsWorksheetGrid: label cells with text longer than the cell width extend into the neighboring cell(s).
28382298
28392299**Incompatible changes**
28402300
28412301- The option `soCalcBeforeSaving` now belongs to the workbook, no longer to the worksheet, and has been renamed to `boCalcBeforeSaving` (it controls automatic calculation of formulas when a workbook is saved).
28422302- The workbook property `ReadFormulas` is replaced by the option flag `boReadFormulas`. This means that you have to add this flag to the workbook's `Options` in order to activate reading of formulas.
28432303- With full support of string formulas some features related to RPN formulas were removed:
28442304 - The field `RPNFormulaResult` of TCell was dropped, as well as the element `cctRPNFormula` in the `TsContentType` set.
28452305 - Sheet function identifiers were removed from the `TsFormulaElement` set, which was truncated after `fekParen`.
28462306 - To identify a sheet function, its name must be passed to the function `RPNFunc` (instead of using the now removed `fekXXXX` token). In the array notation of the RPN formula, a sheet function is identified by the new token `fekFunc`.
28472307 - The calling convention for registering user-defined functions was modified. It now also requires the Excel ID of the function (see "OpenOffice Documentation of Microsoft Excel Files", section 3.11, or unit *xlsconst* containing all token up to ID 200 and some above).
28482308 - Code related to RPN formulas was moved to a separate unit, `fpsRPN`. Add this unit to the uses clause if you need RPN features.
28492309
28502310## License
28512311
28522312LGPL with static linking exception. This is the same license as is used in the Lazarus Component Library.
28532313
28542314## References
28552315
28562316### Documentation
28572317
28582318FPSpreadsheet is documented in this wiki file.
28592319
28602320Every release of FPSpreadsheet is accompanied by a snapshot of the current wiki files. There is also an api documentation created from the embedded comments in the source files. Both files are in the chm format.
28612321
28622322This wiki page is work in progress and updated whenever a new feature is added; therefore, its state corresponds to the svn trunk version of the package. If you work with an older stable version please use these "historic" wiki versions:
28632323
28642324- Version 1.16: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=157438](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=157438)
28652325- Version 1.14: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=149828](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=149828)
28662326- Version 1.12: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=136886](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118771)
28672327- Version 1.10.1: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118771](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118771)
28682328- Version 1.10: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118441](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118441)
28692329- Version 1.8: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=107616](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=107616)
28702330- Version 1.6.2: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=100723](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=100723)
28712331- Version 1.6: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=91469](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=91469)
28722332- Version 1.4: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=85299](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=85299)
28732333- Version 1.2 and 1.2.1: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=81375](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=81375)
28742334
28752335### Wiki links
28762336
28772337- [[Office Automation]]
28782338- [[CsvDocument]]
28792339- [[FPSpreadsheet: Examples]]
28802340- [[RPN Formulas in FPSpreadsheet|RPN formulas in FPSpreadsheet]]
28812341- [[FPSpreadsheet: List of formulas]]
28822342- [[FPSpreadsheet tutorial: Writing a mini spreadsheet application]]
28832343
28842344### External Links
28852345
28862346- [Microsoft OLE Document Format](http://sc.openoffice.org/compdocfileformat.pdf)
28872347- [Excel file format description](http://sc.openoffice.org/excelfileformat.pdf)
28882348- Excel xls and PowerPoint ppt file dumper written in Python - very handy to list all contents of BIFF files (e.g. ./xls-dump.py file.xls) - [<http://cgit.freedesktop.org/libreoffice/contrib/mso-dumper/>](http://cgit.freedesktop.org/libreoffice/contrib/mso-dumper/). A similar application is the "BIFFExplorer" which can be found in the *applications* folder of ccr.
28892349- Icons used in the demo programs:
28902350 - [silk icons](http://www.famfamfam.com/lab/icons/silk/)
28912351 - [fugue icons](http://p.yusukekamiyamane.com/)
28922352
28932353---
28942354*From the Free Pascal wiki, page "FPSpreadsheet", as it stood on 2024-05-10 after a change by Wp, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
28952355Category: Components
28962356Category: Data import and export
28972357Category: FPSpreadsheet
28982358Category: Grids
28992359Category: Lazarus-CCR

Back to history