Sign in Join
Wiki copytemporary

FPSpreadsheet: what changed

Revision 2 to 3. 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
55![](/wiki-images/b/b7/Fpsgrid.png)
66
77## Documentation
88
99This 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.
1010
1111## API Documentation
1212
1313### API Reference
1414
1515A 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*.
1616
1717The 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.
1818
1919### Basics
2020
2121The 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.
2222
2323The 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.
2424
2525Worksheets 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.
2626
2727FPSpreadsheet follows this same structure - there is a `TCell`, a `TsWorksheet`, and a `TsWorkbook`.
2828
2929#### Workbook
3030
3131The 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*.
3232
3333The file format is specified by the type `TsSpreadsheetFormat` defined in the unit `fpstypes`
3434
3535``` pascal
3636type
3737 TsSpreadsheetFormat = (sfExcel2, sfExcel5, sfExcel8, sfExcelXML, sfOOXML,
3838 sfOpenDocument, sfCSV, sfHTML, sfWikiTable_Pipes, sfWikiTable_WikiMedia, sfUser);
3939```
4040
4141where
4242
4343- `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.
4444- `sfOOXML` corresponds to the newer xlsx format introduced by Excel2007
4545- `sfExcelXML` is the xml format which was introduced by Microsoft for Office XP and 2003. Not very popular.
4646- `sfOpenDocument` is the spreadsheet format used by OpenOffice/LibreOffice; by default, the files have the extension *.ods*.
4747- `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.
4848- `sfHTML` denotes the standard HTML format as used in web browsers.
4949- `sfWikiTable_Pipes` and `sfWikiTable_WikiMedia` is the format used by tables in wiki websites.
5050- `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
5151
5252When applying fpspreadsheet the first task is to create an instance of the workbook:
5353
5454``` pascal
5555var
5656 MyWorkbook: TsWorkbook;
5757begin
5858 MyWorkbook := TsWorkbook.Create;
5959 ...
6060```
6161
6262Reading of spreadsheet files is accomplished (among others) by the workbook methods
6363
6464- `procedure ReadFromFile(AFileName: string):`\
6565 Reads the file with the given name and automatically determines the correct file format.
6666- `procedure ReadFromFile(AFileName: string; AFormat: TsSpreadsheetFormat):`\
6767 Reads the file, but assumes that the file format is as specified by `AFormat`.
6868
6969The following workbook methods can be used for saving to file:
7070
7171- `procedure WriteToFile(const AFileName: string; const AFormat: TsSpreadsheetFormat; const AOverwriteExisting: Boolean = False)`:\
7272 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`:
7373- `procedure WriteToFile(const AFileName: String; const AOverwriteExisting: Boolean = False)`:\
7474 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).
7575
7676After 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.
7777
7878Note: 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:
7979
8080- *xlsbiff2*, *xlsbiff5* and *xlsbiff8* for the binary xls file formats `sfExcel2`, `sfExcel5` and `sfExcel8`, respectively,
8181- *xlsxOOXML* for the xlsx file format `sfOOXML` of Excel 2007 and later,
8282- *xlsXML* for the xml format of Excel XP and 2003,
8383- *fpsopendocument* for the file format `sfOpenDocument` of OpenOffice/LibreOffice,
8484- *fpsCSV* for text files with comma-separated values (csv),
8585- *fpsHTML* for HTML files,
8686- *wikitables* for `sfWikiTable_Pipes` and `sfWikiTable_WikiMedia`,
8787- or, simply add *fpsallformats* to get read/write support for all file formats supported.
8888
8989#### Worksheet
9090
9191The 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:
9292
9393``` pascal
9494var
9595 MyWorkbook: TsWorkbook;
9696 MyWorksheet: TsWorksheet;
9797begin
9898 MyWorkbook := TsWorkbook.Create;
9999 MyWorksheet := MyWorkbook.AddWorksheet('My_Table');
100100 // 'My_Table' is the "name" of the worksheet
101101 ...
102102```
103103
104104Already existing worksheets can be accessed by using the `TsWorkbook` methods
105105
106106- `function GetFirstWorksheet: TsWorksheet`: retrieves the first worksheet of the workbook.
107107- `function GetWorksheetByIndex(AIndex: Cardinal): TsWorksheet`: returns the worksheet with the given index (starting at 0).
108108- `function GetWorksheetByName(AName: String): TsWorksheet`: returns the worksheet with the given name which was used when the worksheet was added.
109109
110110The count of already existing worksheets can be queried by calling `GetWorksheetCount`.
111111
112112#### Cell
113113
114114The 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.
115115
116116``` pascal
117117var
118118 MyWorkbook: TsWorkbook;
119119 MyWorksheet: TsWorksheet;
120120begin
121121 MyWorkbook := TsWorkbook.Create;
122122 MyWorksheet := MyWorkbook.AddWorksheet('My_Table');
123123 MyWorksheet.WriteNumber(0, 0, 1.0); // "A1" has row=0 and col=0
124124 ...
125125```
126126
127127It 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.
128128
129129``` pascal
130130if MyWorksheet.FindCell('A1') = nil then
131131 WriteLn('Cell A1 does not exist.');
132132```
133133
134134##### The basic TCell record
135135
136136This is the declaration of the cell's data type:
137137
138138``` pascal
139139type
140140 TCell = record
141141 { Location of the cell }
142142 Worksheet: TsWorksheet;
143143 Col: Cardinal; // zero-based
144144 Row: Cardinal; // zero-based
145145
146146 { Index of format record }
147147 FormatIndex: Integer;
148148
149149 { Status flags }
150150 Flags: TsCellFlags; // (cfHasComment, cfMerged, cfHyperlink, ...)
151151
152152 { Cell content }
153153 UTF8StringValue: String; // strings cannot be part of a variant record
154154 case ContentType: TCellContentType of // must be at the end of the declaration
155155 cctEmpty : (); // has no data at all
156156 cctFormula : (); // UTF8StringValue is outside the variant record
157157 cctNumber : (Numbervalue: Double);
158158 cctUTF8String : (); // FormulaValue is outside the variant record
159159 cctDateTime : (DateTimevalue: TDateTime);
160160 cctBool : (BoolValue: boolean);
161161 cctError : (ErrorValue: TsErrorValue);
162162 end;
163163 PCell = ^TCell;
164164```
165165
166166The field `ContentType` indicates which data type is stored in the cell:
167167
168168``` pascal
169169type
170170 TCellContentType = (cctEmpty, cctFormula, cctNumber, cctUTF8String, cctDateTime, cctBool, cctError);
171171```
172172
173173According to this field the corresponding data can be found in the fields
174174
175175- `NumberValue` (for `ContentType=cctNumber`), or
176176- `UTF8StringValue` (for `ContentType=cctUTF8String`), or
177177- `DateTimeValue` (for `ContentType=cctDateTime`), or
178178- `BoolValue` (for `ContentType=cctBool`), i.e. `TRUE` or `FALSE`, or
179179- `ErrorValue` (for `ContentType=cctError`).
180180
181181Due 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).
182182
183183The field `Flags` tells whether additional data are associated with the cell which are not included in the cell record usually to save memory:
184184
185185``` pascal
186186type
187187 TsCellFlag = (cfHasComment, cfHyperlink, cfMerged, cfHasFormula, cf3dFormula);
188188 TsCellFlags = set of TsCellFlag;
189189```
190190
191191- `cfHasComment`: A comment record can be found in the `Comments` of the worksheet.
192192- `cfHyperlink`: The cell is contains a hyperlink stored in the `Hyperlinks` of the worksheet.
193193- `cfMerged`: The cell belongs to a merged block and extends across several cells.
194194- `cfHasFormula`: The cell is associated with a formula which is stored in the `Formulas` of the worksheet.
195195- `cf3dFormula`: The formula associated with the cell contains elements referencing other sheets of the same workbook.
196196
197197> **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.
198198
199199##### How to add and read data to/from a cell
200200
201201Adding values to a cell is most easily accompished by using one of the `WriteXXXX` methods of the worksheet. The most important ones are:
202202
203203``` pascal
204204type
205205 TsWorksheet = class
206206 ...
207207 { Writing of currency values }
208208 function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
209209 ANumFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = 2;
210210 ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
211211 ANegCurrFormat: Integer = -1): PCell; overload;
212212 procedure WriteCurrency(ACell: PCell; AValue: Double;
213213 ANumFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = -1;
214214 ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
215215 ANegCurrFormat: Integer = -1); overload;
216216 function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
217217 ANumFormat: TsNumberFormat; ANumFormatString: String): PCell; overload;
218218 procedure WriteCurrency(ACell: PCell; AValue: Double;
219219 ANumFormat: TsNumberFormat; ANumFormatString: String); overload;
220220
221221 { Writing of date/time values }
222222 function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime): PCell; overload;
223223 procedure WriteDateTime(ACell: PCell; AValue: TDateTime); overload;
224224 function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
225225 ANumFormat: TsNumberFormat; ANumFormatStr: String = ''): PCell; overload;
226226 procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
227227 ANumFormat: TsNumberFormat; ANumFormatStr: String = ''); overload;
228228 function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
229229 ANumFormatStr: String): PCell; overload;
230230 procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
231231 ANumFormatStr: String); overload;
232232
233233 { Writing of number values }
234234 function WriteNumber(ARow, ACol: Cardinal; ANumber: double): PCell; overload;
235235 procedure WriteNumber(ACell: PCell; ANumber: Double); overload;
236236 function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
237237 ANumFormat: TsNumberFormat; ADecimals: Byte = 2): PCell; overload;
238238 procedure WriteNumber(ACell: PCell; ANumber: Double;
239239 ANumFormat: TsNumberFormat; ADecimals: Byte = 2); overload;
240240 function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
241241 ANumFormat: TsNumberFormat; ANumFormatString: String): PCell; overload;
242242 procedure WriteNumber(ACell: PCell; ANumber: Double;
243243 ANumFormat: TsNumberFormat; ANumFormatString: String); overload;
244244
245245 { Writing of string values }
246246 function WriteText(ARow, ACol: Cardinal; AText: ansistring;
247247 ARichTextParams: TsRichTextParams = nil): PCell; overload;
248248 procedure WriteText(ACell: PCell; AText: String;
249249 ARichTextparams: TsRichTextParams = nil); overload;
250250
251251 // the old string methods "WriteUTF8Text" are deprecated now
252252 ...
253253```
254254
255255Some 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:
256256
257257``` pascal
258258type
259259 TsWorksheet = class
260260 ...
261261 { Reading cell content as a string }
262262 function ReadAsText(ARow, ACol: Cardinal): string; overload;
263263 function ReadAsText(ACell: PCell): string; overload;
264264 function ReadAsText(ACell: PCell; AFormatSettings: TFormatSettings): string; overload;
265265
266266 { Reading cell content as a number }
267267 function ReadAsNumber(ARow, ACol: Cardinal): Double; overload;
268268 function ReadAsNumber(ACell: PCell): Double; overload;
269269 function ReadNumericValue(ACell: PCell; out AValue: Double): Boolean;
270270
271271 { Reading cell content as a date/time value }
272272 function ReadAsDateTime(ARow, ACol: Cardinal; out AResult: TDateTime): Boolean; overload;
273273 function ReadAsDateTime(ACell: PCell; out AResult: TDateTime): Boolean; overload;
274274 ...
275275```
276276
277277##### Index to Cell format
278278
279279`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:
280280
281281``` pascal
282282type
283283 TsCellFormat = record
284284 FontIndex: Integer;
285285 TextRotation: TsTextRotation;
286286 HorAlignment: TsHorAlignment;
287287 VertAlignment: TsVertAlignment;
288288 Border: TsCellBorders;
289289 BorderStyles: TsCellBorderStyles;
290290 Background: TsFillPattern;
291291 NumberFormatIndex: Integer;
292292 NumberFormat: TsNumberFormat;
293293 NumberFormatStr: String;
294294 BiDiMode: TsBiDiMode; // bdDefault, bdLTR {left-to-right}, bdRTL {right-to-left)
295295 Protection: TsCellProtection; // cpLockCell, cpHideFormulas
296296 UsedFormattingFields: TsUsedFormattingFields;
297297 //uffTextRotation, uffFont, uffBold, uffBorder, uffBackground, uffNumberFormat, uffWordWrap, uffHorAlign, uffVertAlign, uffBiDi, uffProtection, uffDoNotPrint
298298 end;
299299```
300300
301301- `FontIndex`: text font by specifying the index in the workbook's font list
302302- `TextRotation`: specifies whether the cell text is written horizontally or vertically
303303- `HorAlignment`: left-aligned, horizontally centered, or right-aligned text
304304- `VertAlignment`: top, bottom or vertically centered text
305305- `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.
306306- `Background`: a record defining the background fill of a cell (pattern style, pattern color, and background color - see chapter on cell background below).
307307- `NumberFormat` and `NumberFormatStr` specify how number or date/time values are formatted (e.g., number of decimal places, long or short date format, etc.).
308308- 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.
309309
310310For 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*.
311311
312312See cell formatting below for a more detailed description.
313313
314314#### Columns and rows
315315
316316Column and row records are added for each column and row having a non-default properties:
317317
318318``` pascal
319319type
320320 TCol = record
321321 Col: Cardinal;
322322 Width: Single;
323323 ColWidthType: TsColWidthType; // = (cwtDefault, cwtCustom)
324324 FormatIndex: Integer;
325325 Options: TsColRowOptions; // set of [croHidden, croPageBreak]
326326 end;
327327 PCol = ^TCol;
328328
329329 TRow = record
330330 Row: Cardinal;
331331 Height: Single;
332332 RowHeightType: TsRowHeightType; // = (rhtDefault, rhtCustom, rhtAuto)
333333 FormatIndex: Integer;
334334 Options: TsColRowOptions; // set of [croHidden, croPageBreak]
335335 Hidden: Boolean;
336336 PageBreak: Boolean;
337337 end;
338338 PRow = ^TRow;
339339```
340340
341341##### Column width / row height
342342
343343**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`).
344344
345345The 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).
346346
347347In 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`.
348348
349349The 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.
350350
351351``` pascal
352352type TsWorksheet = class
353353 ...
354354 { Set row height }
355355 procedure WriteRowHeight(ARowIndex: Cardinal; AHeight: Single; AUnits: TsSizeUnits);
356356 { Set column width }
357357 procedure WriteColWidth(AColIndex: Cardinal; AWidth: Single; AUnits: TsSizeUnits);
358358 { Set default row height }
359359 procedure WriteDefaultRowHeight(AHeight: Single; AUnits: TsSizeUnits);
360360 {Set default cokumn width }
361361 procedure WriteDefaultColWidth(AWidth: Single; AUnits: TsSizeUnits);
362362
363363 { Return row height }
364364 function GetRowHeight(ARowIndex: Cardinal; AUnits: TsSizeUnits): Single;
365365 { Return column width }
366366 function GetColWidth(AColIndex: Cardinal; AUnits: TsSizeUnits): Single;
367367 { Return default row height }
368368 function ReadDefaultRowHeight(AUnits: TsSizeUnits): Single;
369369 { Return default column width }
370370 function ReadDefaultColWidth(AUnits: TsSizeUnits): Single;
371371
372372 property DefaultRowHeight: Single; // in lines
373373 property DefaultColWidht: Single; // in characters
374374```
375375
376376There 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.
377377
378378##### Column and row formats
379379
380380The `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).
381381
382382Here is a listing of the worksheet methods available for column and row formatting:
383383
384384``` Pascal
385385type TsWorksheet = class
386386 // Assign a format to a column or row
387387 procedure WriteColFormatIndex(ACol: Cardinal; AFormatIndex: Integer);
388388 procedure WriteRowFormatIndex(ARow: Cardinal; AFormatIndex: Integer);
389389
390390 // Query the format of a column or row
391391 function GetColFormatIndex(ACol: Cardinal): Integer;
392392 function GetRowFormatIndex(ARow: Cardinal): Integer;
393393
394394 // Returns the font assigned to a column or row
395395 function ReadColFont(ACol: PCol): TsFont;
396396 function ReadRowFont(ARow: PRow): TsFont;
397397
398398 // Check whether any column or row uses a special format
399399 function HasRowFormats: Boolean;
400400 function HasColFormats: Boolean;
401401```
402402
403403##### Hidden columns / rows
404404
405405Adding 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**:
406406
407407``` pascal
408408type TsWorksheet = class
409409 ...
410410 { Hide column/row }
411411 procedure HideCol(ACol: Cardinal);
412412 procedure HideRow(ARow: Cardinal);
413413
414414 { Show a previously hidden column/row }
415415 procedure ShowCol(ACol: Cardinal);
416416 procedure ShowRow(ARow: Cardinal);
417417
418418 { Check whether column/row is hidden }
419419 function ColHidden(ACol: Cardinal): Boolean;
420420 function RowHidden(ARow: Cardinal): Boolean;
421421```
422422
423423##### Page breaks
424424
425425The 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:
426426
427427``` pascal
428428type TsWorksheet = class
429429 ...
430430 { Enforce a page break before the specified column/row }
431431 procedure AddPageBreakToCol(ACol: Cardinal);
432432 procedure AddPageBreakToRow(ARow: Cardinal);
433433
434434 { Removes a page break previously added to a column/row }
435435 procedure RemovePageBreakFromCol(ACol: Cardinal);
436436 procedure RemovePageBreakFromRow(ARow: Cardinal);
437437
438438 { Checks whether a page break is forced before the specified column/row }
439439 function IsPageBreakCol(ACol: Cardinal): Boolean;
440440 function IsPageBreakRow(ARow: Cardinal): Boolean;
441441```
442442
443443#### Events
444444
445445Worksheets 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`.
446446
447447### Formulas
448448
449449Two kinds of formulas are supported by FPSpreadsheet:
450450
451451- **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*.
452452- **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.
453453
454454FPSpreadsheet can convert between string and rpn formulas. Formulas in both types can be calculated.
455455
456456In 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.
457457
458458FPSpreadsheet 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`.
459459
460460Formulas 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.
461461
462462Calculation 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`.
463463
464464If 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`.
465465
466466The most general setting regarding formulas, therefore, is
467467
468468``` pascal
469469 MyWorkbook.Options := MyWorkbook.Options + [boReadFormulas, boCalcBeforeSaving, boAutoCalc];
470470```
471471
472472Calculation 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.
473473
474474#### String formulas
475475
476476String formulas are written in the same way as in the Office applications. The worksheet method for creating a string formula is `WriteFormula`:
477477
478478``` pascal
479479var
480480 MyWorksheet: TsWorksheet;
481481//...
482482 MyWorksheet.WriteFormula(0, 1, '=ROUND(A1+B2+1.215,0)');
483483 // By default, use dot as decimal and comma as list separator!
484484```
485485
486486A few notes on **syntax**:
487487
488488- 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.
489489- The case of the formula name is ignored.
490490- Spaces can be added for better readability, but they will be lost when saving.
491491- Strings must be enclosed in double quotes.
492492- 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`.
493493- 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.
494494- Normally, floating point numbers must be entered with a dot as decimal separator, and a comma must be used to separate function arguments.
495495- 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.
496496
497497``` pascal
498498var
499499 MyWorksheet: TsWorksheet;
500500//...
501501 MyWorksheet.WriteFormula(0, 1, '=ROUND(A1+B2+1,215;0)', true);
502502 // Because of the "true" the formula parser accepts the comma as decimal and the
503503 // semicolon as list separator if the workbook's FormatSettings are set up like this.
504504```
505505
506506Use 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.
507507
508508``` pascal
509509var
510510 MyWorksheet: TsWorksheet;
511511 cell: PCell;
512512//...
513513 cell := MyWorksheet.FindCell(0, 1);
514514 WriteLn('The formula in internal format is ', MyworkSheet.ReadFormula(cell));
515515 WriteLn('The localized formula is ', MyWorksheet.ReadFormulaAsString(cell, true));
516516//-------------------------------------------------------------------
517517// For the previous example, this will result in the following output
518518The formula in internal format is ROUND(A1+B2+1.215,0)
519519The localized formula is ROUND(A1+B2+1,215;0)
520520```
521521
522522#### RPN formulas
523523
524524At 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"]].
525525
526526#### Shared formulas and array formulas
527527
528528- **Shared formulas** are only supported for reading (from Excel files).
529529- **Array formulas** are not supported, currently.
530530
531531#### List of built-in formulas
532532
533533FPSpreadsheet 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"]].
534534
535535To 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.
536536
537537#### Extending FPSpreadsheet by user-defined formulas
538538
539539Although 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*:
540540
541541``` pascal
542542procedure RegisterFunction(const AName: ShortString; const AResultType: Char;
543543 const AParamTypes: String; const AExcelCode: Integer; ACallBack: TsExprFunctionCallBack); overload;
544544
545545procedure RegisterFunction(const AName: ShortString; const AResultType: Char;
546546 const AParamTypes: String; const AExcelCode: Integer; ACallBack: TsExprEventCallBack); overload;
547547```
548548
549549- `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.
550550- `AResultType` is a character which identifies the data type of the function result:
551551 - `'F'` - floating point number
552552 - `'I'` - integer
553553 - `'D'` - date/time
554554 - `'B'` - boolean
555555 - `'S'` - string
556556 - `'C'` - cell address, e.g. 'A1'
557557 - `'R'` - cell range address, e.g. 'A1:C3'
558558- `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:
559559 - `'?'` - any type
560560 - `'+'` - 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.
561561 - lowercase `'f', 'i', 'd', 'b', 's'` indicate optional parameters of the type explained above. Of course, uppercase symbols cannot follow lower-case symbols.
562562- `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.
563563- `ACallback` identifies which function is called by FPSpreadsheet for calculation of the formula. It can either be a procedure or an event handler.
564564
565565``` pascal
566566type
567567 TsExprFunctionCallBack = procedure (var Result: TsExpressionResult; const Args: TsExprParameterArray);
568568 TsExprFunctionEvent = procedure (var Result: TsExpressionResult; const Args: TsExprParameterArray) of object;
569569```
570570
571571The `TsExpressionResult` is a variant record containing result or argument data of several types:
572572
573573``` pascal
574574type
575575 TsResultType = (rtEmpty, rtBoolean, rtInteger, rtFloat, rtDateTime, rtString,
576576 rtCell, rtCellRange, rtError, rtAny);
577577
578578 TsExpressionResult = record
579579 Worksheet : TsWorksheet;
580580 ResString : String;
581581 case ResultType : TsResultType of
582582 rtEmpty : ();
583583 rtError : (ResError : TsErrorValue);
584584 rtBoolean : (ResBoolean : Boolean);
585585 rtInteger : (ResInteger : Int64);
586586 rtFloat : (ResFloat : TsExprFloat);
587587 rtDateTime : (ResDateTime : TDatetime);
588588 rtCell : (ResRow, ResCol : Cardinal);
589589 rtCellRange : (ResCellRange : TsCellRange);
590590 rtString : ();
591591 end;
592592
593593 TsExprParameterArray = array of TsExpressionResult;
594594```
595595
596596As an example we show here the code for the `CONCATENATE()` formula which joins two or more strings:
597597
598598``` pascal
599599const
600600 INT_EXCEL_SHEET_FUNC_CONCATENATE = 336;
601601...
602602 RegisterFunction('CONCATENATE', 'S', 'S+', INT_EXCEL_SHEET_FUNC_CONCATENATE, @fpsCONCATENATE);
603603
604604procedure fpsCONCATENATE(var Result: TsExpressionResult; const Args: TsExprParameterArray);
605605// CONCATENATE( text1, text2, ... text_n )
606606var
607607 s: String;
608608 i: Integer;
609609begin
610610 s := '';
611611 for i:=0 to Length(Args)-1 do
612612 begin
613613 if Args[i].ResultType = rtError then
614614 begin
615615 Result := ErrorResult(Args[i].ResError);
616616 exit;
617617 end;
618618 s := s + ArgToString(Args[i]);
619619 // "ArgToString" simplifies getting the string from a TsExpressionResult as
620620 // a string may be contained in the ResString and in the ResCell fields.
621621 // There is such a function for each basic data type.
622622 end;
623623 Result := StringResult(s);
624624 // "StringResult" stores the string s in the ResString field of the
625625 // TsExpressionResult and sets the ResultType to rtString.
626626 // There is such a function for each basic data type.
627627end;
628628```
629629
630630There 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.
631631
632632#### Unsupported formulas
633633
634634Sometimes 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.
635635
636636In 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.
637637
638638### Cell formatting
639639
640640#### Number and date/time formats
641641
642642Numbers and date/time values can be displayed in a variety of formats. In FPSpreadsheet this can be achieved in two ways:
643643
644644- using **built-in number formats** by specifiying a value for the `NumberFormat` of the cell
645645- using a custom **format string**.
646646
647647Number formats can be specified by these worksheet methods:
648648
649649``` pascal
650650type
651651 TsWorksheet = class
652652 public
653653 // Set number formats alone
654654 function WriteNumberFormat(ARow, ACol: Cardinal; ANumberFormat: TsNumberFormat;
655655 const AFormatString: String = ''): PCell; overload;
656656 procedure WriteNumberFormat(ACell: PCell; ANumberFormat: TsNumberFormat;
657657 const AFormatString: String = ''); overload;
658658
659659 function WriteNumberFormat(ARow, ACol: Cardinal; ANumFormat: TsNumberFormat;
660660 ADecimals: Integer; ACurrencySymbol: String = ''; APosCurrFormat: Integer = -1;
661661 ANegCurrFormat: Integer = -1): PCell; overload;
662662 procedure WriteNumberFormat(ACell: PCell; ANumFormat: TsNumberFormat;
663663 ADecimals: Integer; ACurrencySymbol: String = '';
664664 APosCurrFormat: Integer = -1; ANegCurrFormat: Integer = -1); overload;
665665
666666 function WriteFractionFormat(ARow, ACol: Cardinal; AMixedFraction: Boolean;
667667 ANumeratorDigits, ADenominatorDigits: Integer): PCell; overload;
668668 procedure WriteFractionFormat(ACell: PCell; AMixedFraction: Boolean;
669669 ANumeratorDigits, ADenominatorDigits: Integer); overload;
670670
671671 // Set date/time formats alone
672672 function WriteDateTimeFormat(ARow, ACol: Cardinal; ANumberFormat: TsNumberFormat;
673673 const AFormatString: String = ''): PCell; overload;
674674 procedure WriteDateTimeFormat(ACell: PCell; ANumberFormat: TsNumberFormat;
675675 const AFormatString: String = ''); overload;
676676
677677 // Set cell values and number formats in one call
678678
679679 // number values
680680 function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
681681 AFormat: TsNumberFormat = nfGeneral; ADecimals: Byte = 2;
682682 ACurrencySymbol: String = ''): PCell; overload;
683683 procedure WriteNumber(ACell: PCell; ANumber: Double; AFormat: TsNumberFormat = nfGeneral;
684684 ADecimals: Byte = 2; ACurrencySymbol: String = ''); overload;
685685 function WriteNumber(ARow, ACol: Cardinal; ANumber: double;
686686 AFormat: TsNumberFormat; AFormatString: String): PCell; overload;
687687 procedure WriteNumber(ACell: PCell; ANumber: Double;
688688 AFormat: TsNumberFormat; AFormatString: String); overload;
689689
690690 // date/time values
691691 function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
692692 AFormat: TsNumberFormat = nfShortDateTime; AFormatStr: String = ''): PCell; overload;
693693 procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
694694 AFormat: TsNumberFormat = nfShortDateTime; AFormatStr: String = ''); overload;
695695 function WriteDateTime(ARow, ACol: Cardinal; AValue: TDateTime;
696696 AFormatStr: String): PCell; overload;
697697 procedure WriteDateTime(ACell: PCell; AValue: TDateTime;
698698 AFormatStr: String); overload;
699699
700700 // currency values
701701 function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
702702 AFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = 2;
703703 ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
704704 ANegCurrFormat: Integer = -1): PCell; overload;
705705 procedure WriteCurrency(ACell: PCell; AValue: Double;
706706 AFormat: TsNumberFormat = nfCurrency; ADecimals: Integer = -1;
707707 ACurrencySymbol: String = '?'; APosCurrFormat: Integer = -1;
708708 ANegCurrFormat: Integer = -1); overload;
709709 function WriteCurrency(ARow, ACol: Cardinal; AValue: Double;
710710 AFormat: TsNumberFormat; AFormatString: String): PCell; overload;
711711 procedure WriteCurrency(ACell: PCell; AValue: Double;
712712 AFormat: TsNumberFormat; AFormatString: String); overload;
713713 ...
714714```
715715
716716##### Built-in number formats
717717
718718The **built-in formats** are defined by the enumeration `TsNumberFormat`. In spite of its name, the elements cover both number and date/time values:
719719
720720``` pascal
721721type
722722 TsNumberFormat = (
723723 // general-purpose for all numbers
724724 nfGeneral,
725725 // numbers
726726 nfFixed, nfFixedTh, nfExp, nfPercentage, nfFraction,
727727 // currency
728728 nfCurrency, nfCurrencyRed,
729729 // dates and times
730730 nfShortDateTime, nfShortDate, nfLongDate, nfShortTime, nfLongTime,
731731 nfShortTimeAM, nfLongTimeAM, nfDayMonth, nfMonthYear, nfTimeInterval,
732732 // other (using format string)
733733 nfCustom);
734734```
735735
736736- **nfGeneral** corresponds to the default formatting showing as many decimals as possible (the number `3.141592654` would be unchanged.)
737737- **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`.
738738- **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.
739739- **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).
740740- **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).
741741- **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`.
742742- **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.
743743- **nfCurrendyRed** like `nfCurrency`, in addition negative values are displayed in red.
744744- **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.
745745- **nfShortDate** creates a date string showing day + two-digit month + two-digit year
746746- **nfShortTime** creates a time string showing hours + minutes.
747747- **nfLongTime**, similar, but includes seconds as well
748748- **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.
749749- **nfLongTimeAM**, like `nfShortTimeAM`, but includes seconds
750750- **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.
751751- **nfCustom** allows to specify a dedicated formatting string.
752752
753753As 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.
754754
755755##### Number format strings
756756
757757In 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).
758758
759759Here is a basic list of the symbols used:
760760
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>
761+| Symbol | Meaning | Format string: Number --> Output string |
762+|---|---|---|
763+| `General` | Displays all decimal places of the number | `'General'`: · 1.2345678 --> `'1.2345678'` |
764+| `0` | 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. | `'000'`: 1 --> `'001'` · `'0.0'`: 1 --> `'1.0'` · `'0.0'`: 1.2345678 --> `'1.2'` |
765+| `*` | Like "0" above, but does not display insignificant zeros. | `'0.*'`: 1 --> `'1.'` · `'0.*'`: 1.2345678 --> `'1.2'` |
766+| `?` | Like "0" above, but insignificant zeros are replaced by space characters. Good for aligning decimal points and fractions | `'??0'`: 1 --> `' 1'` · `'0.0??'`: 1 --> `'1.0 '` |
767+| `.` | Decimal separator; will be replaced by the value used in the `DecimalSeparator` of the workbook's `FormatSettings` | `'0.00'`: 8.9 --> `'8.90'` |
768+| `,` | Thousand separator; will be replaced by the value used in the `ThousandSeparator` of the workbook's `FormatSettings`. If at the end of a number formatting sequence the displayed value is divided by 1000. | `'#,##0.00'`: 1200 --> `'1,200.00'` · `'0.00,'`: 1200 --> `'1.20'` |
769+| `E+`, `e+` | 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. | `'0.00E+00'`: 1200 --> `1.20E+03` |
770+| `E-`, `e-` | 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. | `'0.00e-000'`: 1200 --> `1.20e003` |
771+| `%` | Displays the number as a "percentage", i.e. the number is multiplied by 100 and a `%` sign is added. | `'0.0%'`: 0.75 --> `75.0%` |
772+| `/` | 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 `DateSeparator` of the workbook's `FormatSettings` | `'#/#'`: 1.5 --> `'3/2'` · `'# #/#'`: 1.5 --> `'1 1/2'` · `'# #/16'`: 1.5 --> `'1 8/16'` · also: see date/time examples below |
773+| `:` | Separator between hours, minutes and seconds of a date/time value. Will be replaced by the `TimeSeparator` of the workbook's `FormatSettings`. | see examples below |
774+| `yyyy` | Place holder for the year of a date/time value. The year is displayed as a four-digit number. | `'yyyy/mm/dd'`: · Jan 3, 2012 --> `'2012-01-03'` · In this example, the `DateSeparator` is a dash character (`-`). |
775+| `yy` | Place holder for the year of a date/time value. The year is displayed as a two-digit number. | `'yy/mm/dd'`: · Jan 3, 2012 --> `'12-01-03'` |
776+| `m` | Place holder for the month of a date/time value. The month is shown as a number without extra digits. · Please note that the `m` code can also be interpreted as the "minutes" of a time value (see below). | `'yyyy/m/dd'`: · Jan 3, 2012 --> `'2012-1-03'` |
777+| `mm` | 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. · Please note that the `mm` code can also be interpreted as the "minutes" of a time value (see below). | `'yyyy/mm/dd'`: · Jan 3, 2012 --> `'2012-01-03'` |
778+| `mmm` | Place holder for the month of a date/time value. The month is displayed by its abbreviated name. | `'yyyy/mmm/dd'`: · Jan 3, 2012 --> `'2012-Jan-03'` |
779+| `mmmm` | Place holder for the month of a date/time value. The month is displayed by its full name. | `'yyyy/mmm/dd'`: · Jan 3, 2012 --> `'2012-January-03'` |
780+| `d` | 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. | `'yyyy/mm/d'`: · Jan 3, 2012 --> `'2012-01-3'` |
781+| `dd` | Place holder for the day of a date/time value to be displayed as a number. `dd` adds a leading zero to single-digit day numbers. | `'yyyy/mm/dd'`: · Jan 3, 2012 --> `'2012-01-03'` |
782+| `ddd` | Place holder for the day of a date/time value. The day is displayed as its abbreviated name. | `'dddd, yyyy/mm/ddd'`: · Jan 03, 2012 --> `'Tue 2012-01-03'` |
783+| `dddd` | Place holder for the day of a date/time value. The day is displayed as its full name. | `'dddd, yyyy/mmmm/dd'`: · Jan 03, 2012 --> `'Tuesday 2012-01-03'` |
784+| `h` | Place holder of the hour part of a date/time value. The hour is displayed as a simple number, without adding a leading zero. | `'h:mm'`: · 0.25 --> `'6:00'` |
785+| `hh` | 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. | `'hh:mm'`: · 0.25 --> `'06:00'` |
786+| `[hh]`, or `[h]` | Displays elapsed time such that the hour part can become greater than 23 | `'[h]:mm'`: · 1.25 --> `'30:00'` |
787+| `m` | 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 `m` codes are surrounded by date symbols (`y`, `d`) then they are interpreted as "month". | `'h:m'`: · 0.25 --> `'6:0'` |
788+| `mm` | Place holder of the minutes part of a date/time value. Single-digit minutes are displayed with a leading zero. Note that if the `mm` code is surrounded by date symbols (`y`, `d`) then it is interpreted as "month". | `'h:mm'`: · 0.25 --> `'6:00'` |
789+| `[mm]`, or `[m]` | Displays elapsed time such that the minute part can become greater than 59 | `'[mm]:ss'`: · 1.25 --> `'1800:00'` |
790+| `s` | Place holder of the seconds part of a date/time value. The seconds are displayed as a simple number, without adding a leading zero. | `'hh:mm:s'`: · 0.25 --> `'06:00:0'` |
791+| `ss` | Place holder of the seconds part of a date/time value. Single-digit seconds are displayed with a leading zero. | `'hh:mm:ss'`: · 0.25 --> `'06:00:00'` |
792+| `[ss]`, or `[s]` | Displays elapsed time such that the seconds part can become greater than 59 | `'[ss]'`: · 1.25 --> `'108000'` |
793+| `AM/PM`, `am/pm`, `A/P`, or `a/p` | Displays the time in the 12-hour format. | `'hh:mm:ss AM/PM'`: · 0.25 --> `'6:00:00 AM'` |
794+| `"` | The text enclosed by quotation marks is inserted into the formatted strings literally. | `'yyyy"/"mm"/"dd'`: · Jan 3, 2012 --> `'2012/01/03'` (i.e. the `/` is not replaced by the `DateSeparator` of the workbook). |
795+| `\` | The next character of the format string appears in the result string literally. The `\` itself does not show up. | `'yyyy\/mm\/dd'`: · Jan 3, 2012 --> `'2012/01/03'` |
796+| `;` | 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. | `'"#,##0"$"';-#,##0"$";"-"'`: · 1200 --> `'1,200$'` · -1200 --> `'1,200$'` · 0 --> `'-'` |
797+| `(`, and `)` | Sometimes used for currency values to indicate negative numbers, instead of minus sign | `'#,##0"$";(#,##0)"$"'`: · -1200 --> `'(1200)$'` |
798+| `[red]` | The formatted string is displayed in the specified color. Instead of `[red]`, you can use accordingly `[black]`, `[white]`, `[green]`, `[blue]`, `[magenta]`, `[yellow]`, or `[cyan]`. Often used to highlight negative currency values. | `'"$" #,##0.00;[red]("$" #,##0.00)'`: · -1200 --> '`($ 1200.00)`' |
839799
840800##### A note on Excel dates
841801
842802There 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.
843803
844804#### Colors
845805
846806FPSpreadsheet supports colors for text, cell background, and cell borders. The basic EGA colors are declared in unit *fpstypes* as constants:
847807
848808![](/wiki-images/7/7b/DefaultPalette.png)
849809
850810``` pascal
851811type
852812 TsColor = DWORD;
853813
854814const
855815 scBlack = $00000000;
856816 scWhite = $00FFFFFF;
857817 scRed = $000000FF;
858818 scGreen = $0000FF00;
859819 scBlue = $00FF0000;
860820 scYellow = $0000FFFF;
861821 scMagenta = $00FF00FF;
862822 scCyan = $00FFFF00;
863823 scDarkRed = $00000080;
864824 scDarkGreen = $00008000;
865825 scDarkBlue = $00800000;
866826 scOlive = $00008080;
867827 scPurple = $00800080;
868828 scTeal = $00808000;
869829 scSilver = $00C0C0C0;
870830 scGray = $00808080;
871831 scGrey = scGray; // redefine to allow different spelling
872832
873833 // Identifier for undefined color
874834 scNotDefined = $40000000;
875835
876836 // Identifier for transparent color
877837 scTransparent = $20000000;
878838```
879839
880840The `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.)
881841
882842The high order byte is usually zero but is used internally to identify special color values, such as for undefined or transparent colors.
883843
884844> **Note:** In older versions of the library colors were defined as indexes into a color palette. **THIS IS NO LONGER WORKING.**
885845
886846Unit *fpsutils* contains some useful functions for **modification of colors**:
887847
888848- `function GetColorName(AColor: TsColor): String;`\
889849 returns the name of the colors defined above, or a string showing the rgb components for other colors.
890850- `function HighContrastColor(AColor: TsColor): TsColor;`\
891851 returns `scBlack` for a "bright", `scWhite` for a "dark" input color.
892852- `function TintedColor(AColor: TsColor; tint: Double): TsColor;`\
893853 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.
894854
895855#### Cell background
896856
897857The cell background can be filled by predefined patterns which are identified by the record `TsFillPattern`:
898858
899859``` pascal
900860type
901861 TsFillPattern = record
902862 Style: TsFillStyle; // fill style pattern as defined below
903863 FgColor: TsColor; // forground color of the fill pattern
904864 BgColor: TsColor; // background color of the fill pattern
905865 end;
906866
907867 TsFillStyle = (fsNoFill, fsSolidFill, fsGray75, fsGray50, fsGray25, fsGray12, fsGray6,
908868 fsStripeHor, fsStripeVert, fsStripeDiagUp, fsStripeDiagDown,
909869 fsThinStripeHor, fsThinStripeVert, fsThinStripeDiagUp, fsThinStripeDiagDown,
910870 fsHatchDiag, fsThinHatchDiag, fsThickHatchDiag, fsThinHatchHor);
911871```
912872
913873- 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.
914874- The fill pattern of a particular cell can be retrieved by calling the workbook method `ReadBackground`.
915875- The simplified method `WriteBackgroundColor` can be used to achieve a uniform background color.
916876- **Limitations:**
917877 - 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.
918878 - BIFF2 files support only a 12.5% black-and-white shaded pattern.
919879
920880``` pascal
921881type
922882 TsWorksheet = class
923883 public
924884 function WriteBackground(ARow, ACol: Cardinal; AStyle: TsFillStyle; APatternColor, ABackgroundColor: TsColor): PCell; overload;
925885 procedure WriteBackground(ACell: PCell; AStyle: TsFillStyle; APatternColor, ABackgroundColor: TsColor); overload;
926886
927887 function WriteBackgroundColor(ARow, ACol: Cardinal; AColor: TsColor): PCell; overload;
928888 procedure WriteBackgroundColor(ACell: PCell; AColor: TsColor); overload;
929889
930890 function ReadBackground(ACell: PCell): TsFillPattern;
931891 function ReadBackgroundColor(ACell: PCell): TsColor; overload;
932892 // ...
933893 end;
934894
935895var
936896 cell: PCell;
937897...
938898 // Example 1: Assign a pattern of thin, horizontal, yellow stripes on a blue background to empty cell A1 (row 0, column 0)
939899 MyWorksheet.WriteBackground(0, 0, fsThinStripeHor, scYellow, scBlue);
940900
941901 // Example 2: Uniform gray background color of cell B1 (row 0, column 1) containing the number 3.14
942902 cell := MyWorksheet.WriteNumber(0, 1, 3.14);
943903 MyWorksheet.WriteBackgroundColor(cell, clSilver);
944904```
945905
946906#### Cell borders
947907
948908Cells 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`:
949909
950910``` pascal
951911type
952912 TsCellBorder = (cbNorth, cbWest, cbEast, cbSouth, cbDiagUp, cbDiagDown);
953913 TsCellBorders = set of TsCellBorder;
954914```
955915
956916In 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:
957917
958918``` pascal
959919 MyWorksheet.WriteBorders(0, 0, [cbNorth, cbSouth]); // A1: row 0, column 0
960920 MyWorksheet.WriteBorders(0, 1, [cbNorth, cbSourth]); // B1: row 0, column 1
961921```
962922
963923Lines 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:
964924
965925``` pascal
966926type
967927 TsLineStyle = (lsThin, lsMedium, lsDashed, lsDotted, lsThick, lsDouble, lsHair,
968928 lsMediumDash, lsDashDot, lsMediumDashDot, lsDashDotDot, lsMediumDashDotDot, lsSlantDashDot);
969929
970930 TsCellBorderStyle = record
971931 LineStyle: TsLineStyle;
972932 Color: TsColor;
973933 end;
974934
975935 TsCellBorderStyles = array[TsCellBorder] of TsCellBorderStyle;
976936
977937 TsWorksheet = class
978938 public
979939 function WriteBorderStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; AStyle: TsCellBorderStyle): PCell; overload;
980940 procedure WriteBorderStyle(ACell: PCell; ABorder: TsCellBorder; AStyle: TsCellBorderStyle); overload;
981941
982942 function WriteBorderStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; ALineStyle: TsLineStyle; AColor: TsColor): PCell; overload;
983943 procedure WriteBorderStyle(ACell: PCell; ABorder: TsCellBorder; ALineStyle: TsLineStyle; AColor: TsColor); overload;
984944
985945 function WriteBorderColor(ARow, ACol: Cardinal; ABorder: TsCellBorder; AColor: TsColor): PCell; overload;
986946 procedure WriteBorderColor(ACell: PCell; ABorder: TsCellBorder; AColor: TsColor): PCell; overload;
987947
988948 function WriteBorderLineStyle(ARow, ACol: Cardinal; ABorder: TsCellBorder; ALineStyle: TsLineStyle): PCell; overload;
989949 procedure WriteBorderLineStyle(ACell: PCell; ABorder: TsCellBorder; ALineStyle: TsLineStyle): PCell; overload;
990950
991951 function WriteBorderStyles(ARow, ACol: Cardinal; const AStyles: TsCellBorderStyles): PCell; overload;
992952 procedure WriteBorderStyles(ACell: PCell; const AStyles: TsCellBorderStyles); overload;
993953
994954 function WriteBorders(ARow, ACol: Cardinal; ABorders: TsCellBorders): PCell; overload
995955 procedure WriteBorders(ACell: PCell; ABorders: TsCellBorders); overload
996956
997957 function ReadCellBorders(ACell: PCell): TsCellBorders;
998958 function ReadCellBorderStyle(ACell: PCell; ABorder: TsCellBorder): TsCellBorderStyle;
999959 function ReadCellBorderStyles(ACell: PCell): TsCellBorderStyles;
1000960 ...
1001961 end;
1002962```
1003963
1004964The style of a given cell border can be specified by the following methods provided by the worksheet:
1005965
1006966- **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.
1007967- **WriteBorderColor** changes the color of a given border without affecting the line style of this border.
1008968- **WriteBorderLineStyle** sets the line style of the border only, but leaves the color unchanged.
1009969- **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.
1010970
1011971This example adds a thin black border to the top, and a thick blue border to the bottom of cells A1 and B1:
1012972
1013973``` pascal
1014974var
1015975 cellA1, cellB1: PCell;
1016976...
1017977 cellA1 := MyWorksheet.WriteBorders(0, 0, [cbNorth, cbSouth]); // cell A1: row 0, column 0
1018978 MyWorksheet.WriteBorderStyle(cellA1, cbNorth, lsThin, scBlack);
1019979 MyWorksheet.WriteBorderStyle(cellA1, cbSouth, lsThick, scBlue);
1020980
1021981 cellB1 := MyWorksheet.WriteBorders(0, 1, [cbNorth, cbSouth]); // cell B1: row 0, column 1
1022982 MyWorksheet.WriteBorderStyles(cellB1, cellA1^.BorderStyles); // copy all border styles from cell A1 to B1
1023983```
1024984
1025985> **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.
1026986
1027987#### Fonts
1028988
1029989The cell text can displayed in various fonts. For this purpose, the workbook provides a list of `TsFont` items:
1030990
1031991``` pascal
1032992type
1033993 TsFont = class
1034994 FontName: String;
1035995 Size: Single;
1036996 Style: TsFontStyles;
1037997 Color: TsColor;
1038998 Position: TsFontPosition;
1039999 end;
10401000```
10411001
10421002- The **FontName** corresponds to the name of the font as used by the operational system. In Windows, an example would be "Times New Roman".
10431003- The **FontSize** is given in "points", i.e. units 1/72 inch which are commonly used in Office applications.
10441004- 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.
10451005- The **Color** determines the foreground color of the text characters given in rgb presentation as discussed above.
10461006- 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).
10471007
10481008Every cell is provided with an **index into the font list**.
10491009
10501010In order to assign a particular font to a cell, use one of the following methods of `TsSpreadsheet`:
10511011
10521012``` pascal
10531013type
10541014 TsSpreadsheet = class
10551015 public
10561016 function WriteFont(ARow, ACol: Cardinal; const AFontName: String;
10571017 AFontSize: Single; AFontStyle: TsFontStyles; AFontColor: TsColor): Integer; overload;
10581018 procedure WriteFont(ARow, ACol: Cardinal; AFontIndex: Integer); overload;
10591019 function WriteFontColor(ARow, ACol: Cardinal; AFontColor: TsColor): Integer;
10601020 function WriteFontSize(ARow, ACol: Cardinal; ASize: Integer): Integer;
10611021 function WriteFontStyle(ARow, ACol: Cardinal; AStyle: TsFontStyles): Integer;
10621022 // plus: overloaded versions accepting a pointer to a cell record instead of the row and column index as parameter
10631023 // ...
10641024 end;
10651025```
10661026
10671027- **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.
10681028- **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.
10691029- **WriteFontSize** replaces the size of the currently used font of the cell.
10701030- **WriteFontStyle** replaces the style (normal, bold, italic, etc.) of the currently used cell font.
10711031
10721032The 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.
10731033
10741034The 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`.
10751035
10761036Here is an **example** which decreases the size of all 10-point "Arial" fonts to 9-point:
10771037
10781038``` pascal
10791039var
10801040 i: Integer;
10811041 font: TsFont;
10821042begin
10831043 for i := 0 to MyWorkbook.GetFontCount-1 do
10841044 begin
10851045 font := MyWorkbook.GetFont(i);
10861046 if (font.FontName = 'Arial') and (font.Size = 10.0) then
10871047 font.Size := 9.0;
10881048 end;
10891049end;
10901050```
10911051
10921052#### Rich-text formatting
10931053
10941054In 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).
10951055
10961056For this purpose, unit *fpstypes* declares the type `TsRichTextParams` which is an array of `TsRichTextParam` records:
10971057
10981058``` pascal
10991059type
11001060 TsRichTextParam = record
11011061 FontIndex: Integer;
11021062 FirstIndex: Integer;
11031063 end;
11041064
11051065 TsRichTextParams = array of TsRichTextParam;
11061066```
11071067
11081068`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.
11091069
11101070There are two ways to add "rich-text" formatting to a cell text:
11111071
11121072- 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
11131073
11141074``` pascal
11151075 MyWorksheet.WriteTextAsHTML(0, 0, 'Area (m<sup>2</sup>');
11161076```
11171077
11181078- Alternatively, the standard text writing method, `WriteText` can be called with an additional parameter specifiying the rich-text formatting parameters to be used directly:
11191079
11201080``` pascal
11211081var
11221082 richTextParams: TsRichTextParams;
11231083 fnt: TsFont;
11241084 cell: PCell;
11251085begin
11261086 SetLength(rtp, 2);
11271087 cell := MyWorksheet.GetFont(0, 0);
11281088 fnt := MyWorksheet.ReadCellFont(cell);
11291089 richTextParams[0].FirstIndex := 8; // The superscript groups begins with "2" which is the (1-based) character #8 of the cell text.
11301090 richTextParams[0].FontIndex := MyWorkbook.AddFont(fnt.FontName, fnt.Size, fnt.Style, fnt.Color, fpSuperscript);
11311091 richTextParams[1].FirstIndex := 9; // Normal font again beginning with character #9.
11321092 richTextParams[1].FontIndex := MyWorksheet.ReadCellFontIndex(0, 0);
11331093 MyWorksheet.WriteUTF8Text(cell, 'Area (m2)', richTextParams);
11341094end;
11351095```
11361096
11371097Use the worksheet method `DeleteRichTextParams` to remove rich-text formatting from a previously formatted cell.
11381098
11391099> **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.
11401100
11411101#### Text rotation
11421102
11431103Usually 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.
11441104
11451105If you need this feature use the worksheet method `WriteTextRotation` and specify the text direction by an element of the enumeration type `TsTextRotation`:
11461106
11471107``` pascal
11481108type
11491109 TsTextRotation = (trHorizontal, rt90DegreeClockwiseRotation,
11501110 rt90DegreeCounterClockwiseRotation, rtStacked);
11511111
11521112 TsWorksheet = class
11531113 public
11541114 function WriteTextRotation(ARow, ACol: Cardinal; ARotation: TsTextRotation): PCell; overload;
11551115 procedure WriteTextRotation(ACell: PCell; ARotation: TsTextRotation); overload;
11561116
11571117 function ReadTextRotation(ACell: PCell): TsTextRotation;
11581118 // ...
11591119 end;
11601120
11611121 // example for counter-clockwise rotated text in cell A1:
11621122 WriteTextRotation(0, 0, rt90DegreeCounterClockwiseRotation);
11631123```
11641124
11651125> **Warning:** Finer degrees of rotation which may be supported by some spreadsheet file formats are ignored.
11661126
11671127#### Text alignment
11681128
11691129By 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`:
11701130
11711131``` pascal
11721132type
11731133 TsHorAlignment = (haDefault, haLeft, haCenter, haRight, haJustified, haDistributed, haFilled);
11741134 TsVertAlignment = (vaDefault, vaTop, vaCenter, vaBottom);
11751135
11761136 TsWorksheet = class
11771137 public
11781138 function WriteHorAlignment(ARow, ACol: Cardinal; AValue: TsHorAlignment): PCell; overload;
11791139 procedure WriteHorAlignment(ACell: PCell; AValue: TsHorAlignment); overload;
11801140 function ReadHorAlignment(ACell: PCell): TsHorAlignment;
11811141
11821142 function WriteVertAlignment(ARow, ACol: Cardinal; AValue: TsVertAlignment): PCell; overload;
11831143 procedure WriteVertAlignment(ACell: PCell; AValue: TsVertAlignment); overload;
11841144 function ReadVertAlignment(ACell: PCell): TsVertAlignment;
11851145 // ...
11861146 end;
11871147
11881148 // Example: Center the text in cell A1 both horizontally and vertically
11891149 MyWorksheet.WriteHorAlignment(0, 0, haCenter);
11901150 MyWorksheet.WriteVertAlignment(0, 0, vaCenter);
11911151```
11921152
11931153Explanation of special horizontal alignments:
11941154
11951155- `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.
11961156- `haJustified`: like `haDistributed`, expect for the last line which remains left-justified.
11971157- `haFilled`: the text is repeated to fill the entire cell.
11981158
11991159#### Word wrap
12001160
12011161Text which is longer than the width of a cell can wrap into several lines by calling the method `WriteWordwrap` of the spreadsheet:
12021162
12031163``` pascal
12041164type
12051165 TsWorksheet = class
12061166 public
12071167 function WriteWordwrap(ARow, ACol: Cardinal; AValue: Boolean): PCell; overload;
12081168 procedure WriteWordwrap(ACell: PCell; AValue: Boolean); overload;
12091169 function ReadWordwrap(ACell: PCell): Boolean;
12101170 //...
12111171 end;
12121172
12131173 // Example: activate wordwrap in cell A1
12141174 MyWorksheet.WriteWordwrap(0, 0, true);
12151175```
12161176
12171177#### Merged cells
12181178
12191179Like 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:
12201180
12211181``` pascal
12221182 MyWorksheet.MergeCells('A1:D5');
12231183 // or: MyWorksheet.MergeCells(0, 0, 4, 3); // first row, first column, last row, last column
12241184```
12251185
12261186The 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.
12271187
12281188In 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:
12291189
12301190``` pascal
12311191 MyWorksheet.UnmergeCells('B1');
12321192 // or: MyWorksheet.UnmergeCells(0, 1); // row, column of any cell within the range
12331193```
12341194
12351195Merged cells can be read from/written to all file formats except for `sfCSV`, `sfExcel2` and `sfExcel5` which do not support this feature natively.
12361196
12371197The 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:
12381198
12391199``` pascal
12401200var
12411201 cell, base: PCell;
12421202 r1,c1,r2,c2: Cardinal;
12431203...
12441204 cell := MyWorksheet.FindCell('B1');
12451205 if MyWorksheet.IsMerged(cell) then
12461206 begin
12471207 WriteLn('Cell B1 is merged.');
12481208
12491209 MyWorksheet.FindMergedRange(cell, r1, c1, r2, c2);
12501210 WriteLn('The merged range is ' + GetCellRangeString(r1, c1, r2, c2));
12511211
12521212 base := MyWorksheet.FindMergeBase(cell);
12531213 WriteLn('The merge base is cell ' + GetCellString(base^.Row, base^.Col));
12541214 end;
12551215```
12561216
12571217#### Cell protection
12581218
12591219This is described in a separate section below.
12601220
12611221#### Miscellaneous
12621222
12631223##### Disable printing of specific cells
12641224
12651225Specific cells can be disabled from printing:
12661226
12671227``` pascal
12681228type
12691229 TsWorksheet = class
12701230 public
12711231 function WriteDoNotPrintCell(ARow, ACol: Cardinal; AValue: boolean): PCell; overload;
12721232 procedure WriteDoNotPrintCell(ACell: PCell; AValue: Boolean); overload;
12731233 function ReadDoNotPrintCell(ACell: PCell): Boolean;
12741234```
12751235
12761236### Additional data
12771237
12781238#### Cell comments
12791239
12801240Comments can be attached to any cell by calling
12811241
12821242``` pascal
12831243 MyWorksheet.WriteComment(0, 0, 'This is a comment for cell A1');
12841244```
12851245
12861246They are stored in an internal list of the worksheet. Use the corresponding worksheet methods to access comments:
12871247
12881248- If you want to know whether a particular cell contains a comment call the worksheet method `HasComment(cell)`.
12891249- For retrieving a cell comment use the method `ReadComment(cell)`, or its overloaded companion `ReadComment(ARow, ACol)`.
12901250- The total number of comments can be retrieved from `worksheet.Comments.Count`.
12911251
12921252#### Hyperlinks
12931253
12941254Hyperlinks 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
12951255
12961256``` pascal
12971257 procedure TWorksheet.WriteHyperlink(ARow, ACol: Cardinal; ATarget: String; ATooltip: String = '');
12981258```
12991259
13001260- 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 `'!'`.
13011261- The optional `Tooltip` parameter is evaluated by Excel to display it in a hint window if the mouse if above the hyperlink.
13021262
13031263> **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.
13041264
13051265**Examples:**
13061266
13071267``` pascal
13081268 // Open the web site www.google.com
13091269 MyWorksheet.WriteText(0, 0, 'Open google');
13101270 MyWorksheet.WriteHyperlink(0, 0, 'http://www.google.com');
13111271
13121272 // Open the local file with the absolute path "C:\readme.txt" (assuming Windows)
13131273 MyWorksheet.WriteHyperlink(1, 0, 'file:///c:\readme.txt');
13141274
13151275 // Open the mail client to send a mail
13161276 MyWorksheet.WriteText('Send mail');
13171277 MyWorksheet.WriteHyperlink(3, 0, 'mailto:somebody@gmail.com?subject=Test');
13181278
13191279 // Jump to a particular cell
13201280 MyWorksheet.WriteText(5, 0, 'Jump to cell A10 on sheet2');
13211281 MyWorksheet.WriteHyperlink(5, 0, '#Sheet2!A10');
13221282
13231283 // Jump to cell A10 on the current sheet and display a popup hint
13241284 MyWorksheet.WriteHyperlink(5, 0, '#A10', 'Go to cell A10');
13251285```
13261286
13271287> **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.
13281288
13291289#### Images
13301290
13311291FPSpreadsheet supports embedding of images in worksheets. Use one of the worksheet methods `WriteImage()` to add an image to the worksheet:
13321292
13331293``` pascal
13341294 MyWorksheet.WriteImage(row, col, filename, offsetX, offsetY, scaleX, scaleY);
13351295 MyWorksheet.WriteImage(row, col, stream, offsetX, offsetY, scaleX, scaleY);
13361296 MyWorksheet.WriteImage(row, col, imageindex, offsetX, offsetY, scaleX, scaleY);
13371297```
13381298
13391299The 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.
13401300
13411301Note 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:
13421302
13431303``` pascal
13441304type
13451305 TsImageType = integer;
13461306 TGetImageSizeFunc = function (AStream: TStream; out AWidth, AHeight: DWord; out dpiX, dpiY: Double): Boolean;
13471307
13481308function RegisterImageType(AMimeType, AExtension: String; AGetImageSize: TGetImageSizeFunc): TsImageType;
13491309```
13501310
13511311Due 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:
13521312
13531313- Predefine the widths of all columns at least up to the one containing the right edge of the image.
13541314- Predefine the heights of all rows at least up to the one containing the lower edge of the image.
13551315- 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).
13561316- If the exact size of the image is important make sure that it fits into a single cell.
13571317
13581318### Sorting
13591319
13601320Cells 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'`):
13611321
13621322``` pascal
13631323type
13641324 TsWorksheet = class
13651325 // ...
13661326 procedure Sort(const ASortParams: TsSortParams;
13671327 ARowFrom, AColFrom, ARowTo, AColTo: Cardinal); overload;
13681328 procedure Sort(ASortParams: TsSortParams; ARange: String); overload;
13691329 // ...
13701330 end;
13711331```
13721332
13731333The sorting criteria are defined by a record of type `TsSortParams`:
13741334
13751335``` pascal
13761336type
13771337 TsSortParams = record
13781338 SortByCols: Boolean;
13791339 Priority: TsSortPriority; // spNumAlpha ("Numbers first"), or spAlphaNum ("Text first")
13801340 Keys: TsSortKeys;
13811341 end;
13821342
13831343 TsSortKey = record
13841344 ColRowIndex: Integer;
13851345 Options: TsSortOptions; // set of [spDescending, spCaseInsensitive]
13861346 end;
13871347```
13881348
13891349- 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).
13901350- `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`).
13911351- 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.
13921352
13931353`InitSortParams` is a handy utility to initialize the sorting parameters:
13941354
13951355``` pascal
13961356function InitSortParams(ASortByCols: Boolean = true; ANumSortKeys: Integer = 1;
13971357 ASortPriority: TsSortPriority = spNumAlpha): TsSortParams;
13981358```
13991359
14001360The next code fragment shows a typical sorting call:
14011361
14021362``` pascal
14031363var
14041364 sortParams: TsSortParams;
14051365begin
14061366 sortParams := InitSortParams(true, 2); // sorting along columns, 2 sorting keys
14071367
14081368 // primary sorting key: column 3, ascending, case-insensitive
14091369 sortParams.Keys[0].ColRowIndex := 3;
14101370 sortParams.Keys[0].Options := [ssoCaseInsensitive];
14111371
14121372 // secondary sorting key: colum 1, descending
14131373 sortParams.Keys[1].ColRowIndex := 1;
14141374 sortParams.Keys[1].Options := [ssoDescending];
14151375
14161376 // The sorted block extends between cells A1 (row=0, col=0) and F10 (row=9, col=5)
14171377 MyWorksheet.Sort(sortParams, 0, 0, 9, 5);
14181378 // or: MyWorksheet.Sort(sortParams, 'A1:F10');
14191379end;
14201380```
14211381
14221382### Searching and replacing
14231383
14241384Unit *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.
14251385
14261386**Example:**
14271387
14281388``` pascal
14291389uses
14301390 fpsTypes, fpSpreadsheet, fpsUtils, fpsSearch, fpsAllFormats;
14311391var
14321392 MyWorkbook: TsWorkbook;
14331393 foundWorksheet: TsWorksheet;
14341394 foundRow, foundCol: Cardinal;
14351395 MySearchParams: TsSearchParams;
14361396begin
14371397 MyWorkbook := TsWorkbook.Create;
14381398 try
14391399 MyWorkbook.ReadFromFile(AFileName);
14401400
14411401 // Specify search criteria
14421402 MySearchParams.SearchText := 'Hallo';
14431403 MySearchParams.Options := [soEntireDocument];
14441404 MySearchParams.Within := swWorkbook;
14451405
14461406 // or: MySearchParaams := InitSearchParams('Hallo', [soEntireDocument], swWorkbook);
14471407
14481408 // Create search engine and execute search
14491409 with TsSearchEngine.Create(MyWorkbook) do begin
14501410 if FindFirst(MySearchParams, foundWorksheet, foundRow, foundCol) then begin
14511411 WriteLn('First "', MySearchparams.SearchText, '" found in cell ', GetCellString(foundRow, foundCol), ' of worksheet ', foundWorksheet.Name);
14521412 while FindNext(MySeachParams, foundWorksheet, foundRow, foundCol) do
14531413 WriteLn('Next "', MySearchParams.SearchText, '" found in cell ', GetCellString(foundRow, foundCol), ' of worksheet ', foundWorksheet.Name);
14541414 end;
14551415 Free;
14561416 end;
14571417 finally
14581418 MyWorkbook.Free;
14591419 end;
14601420end;
14611421```
14621422
14631423The 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.
14641424
14651425The record `TsSearchParams` specifies the criteria used for searching:
14661426
14671427``` pascal
14681428type
14691429 TsSearchParams = record
14701430 SearchText: String;
14711431 Options: TsSearchOptions;
14721432 Within: TsSearchWithin;
14731433 end;
14741434```
14751435
14761436Besides the text to be searched (`SearchText`) it provides a set of options to narrow the search:
14771437
14781438- `soCompareEntireCell`: Compares the `SearchText` with the entire cell content. If not contained in the `Options` then the cell text is compared only partially.
14791439- `soMatchCase`: Perform a case-sensitive search
14801440- `soRegularExpr`: The `SearchText` is considered as a regular expression
14811441- `soAlongRows`: The search engine proceeds first along the rows. If not contained in the `Options` then the search proceeds along the columns.
14821442- `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.
14831443- `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).
14841444- `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`.
14851445
14861446The record field `Within` identifies the part of the spreadsheet to be searched:
14871447
14881448- `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.
14891449- `swWorksheet`: The search is limited to the currently active worksheet
14901450- `swColumn`: Search is restricted to the column of the active cell
14911451- `swRow`: Search is restricted to the row of the active cell.
14921452
14931453The 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.
14941454
14951455In 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:
14961456
14971457``` pascal
14981458type
14991459 TsReplaceParams = record
15001460 ReplaceText: String;
15011461 Options: TsReplaceOptions;
15021462 end;
15031463```
15041464
15051465The `ReplaceText` identifies the string which will replace the found text pattern. The `Options` define a set of criteria how the replacement is done:
15061466
15071467- `roReplaceEntirecell`: Replaces the entire cell text by the `ReplaceText`. If not contained in the `Options` then only the part matching the `SearchText` is replaced.
15081468- `roReplaceAll`: Performs the replacement in all found cells (i.e., simply call `ReplaceFirst` to replace all automatically).
15091469- `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.
15101470
15111471Use the function `InitReplaceParams` (in unit *fpsutils*) to initialize the replace parameters record with the provided (but optional) values.
15121472
15131473### Column and row operations
15141474
15151475The worksheet provides these methods for inserting, deleting, hiding or unhiding columns and rows:
15161476
15171477``` pascal
15181478type
15191479 TsWorksheet = class
15201480 ...
15211481 procedure DeleteCol(ACol: Cardinal);
15221482 procedure DeleteRow(ARow: Cardinal);
15231483
15241484 procedure InsertCol(ACol: Cardinal);
15251485 procedure InsertRow(ARow: Cardinal);
15261486
15271487 procedure RemoveCol(ACol: Cardinal);
15281488 procedure RemoveRow(ARow: Cardinal);
15291489
15301490 procedure RemoveAllCols;
15311491 procedure RemoveAllRows
15321492
15331493 procedure HideCol(ACol: Cardinal);
15341494 procedure HideRow(ARow: Cardinal);
15351495
15361496 procedure ShowCol(ACol: Cardinal);
15371497 procedure ShowRow(ARow: Cardinal);
15381498
15391499 function ColHidden(ACol: Cardinal): Boolean;
15401500 function RowHidden(ARow: Cardinal): Boolean;
15411501```
15421502
15431503- 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.
15441504
15451505- `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.
15461506
15471507- `RemoveAllCols` **removes all** column records, i.e. resets all column widths; `RemoveAllRows` does the same with the row records and row heights.
15481508
15491509- A column or row is **inserted** before the index specified as parameter of the `InsertXXX` method.
15501510
15511511### Page layout
15521512
15531513#### General
15541514
15551515So 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.
15561516
15571517``` pascal
15581518type
15591519 TsPageOrientation = (spoPortrait, spoLandscape);
15601520
15611521 TsPrintOption = (poPrintGridLines, poPrintHeaders, poPrintPagesByRows,
15621522 poMonochrome, poDraftQuality, poPrintCellComments, poDefaultOrientation,
15631523 poUseStartPageNumber, poCommentsAtEnd, poHorCentered, poVertCentered,
15641524 poDifferentOddEven, poDifferentFirst, poFitPages);
15651525
15661526 TsPrintOptions = set of TsPrintOption;
15671527
15681528 TsHeaderFooterSectionIndex = (hfsLeft, hfsCenter, hfsRight);
15691529
15701530 TsCellRange = record
15711531 Row1, Col1, Row2, Col2: Cardinal;
15721532 end;
15731533
15741534 TsPageLayout = class
15751535 ...
15761536 public
15771537 ...
15781538 { Methods }
15791539 // embedded header/footer images
15801540 procedure AddHeaderImage(AHeaderIndex: Integer;
15811541 ASection: TsHeaderFooterSectionIndex; const AFilename: String);
15821542 procedure AddFooterImage(AFooterIndex: Integer;
15831543 ASection: TsHeaderFooterSectionIndex; const AFilename: String);
15841544 procedure GetImageSections(out AHeaderTags, AFooterTags: String);
15851545 function HasHeaderFooterImages: Boolean;
15861546
15871547 // Repeated rows and columns
15881548 function HasRepeatedCols: Boolean;
15891549 function HasRepeatedRows: Boolean;
15901550 procedure SetRepeatedCols(AFirstCol, ALastCol: Cardinal);
15911551 procedure SetRepeatedRows(AFirstRow, ALastRow: Cardinal);
15921552
15931553 // print ranges
15941554 function AddPrintRange(ARow1, ACol1, ARow2, ACol2: Cardinal): Integer; overload;
15951555 function AddPrintRange(const ARange: TsCellRange): Integer; overload;
15961556 function GetPrintRange(AIndex: Integer): TsCellRange;
15971557 function NumPrintRanges: Integer;
15981558 procedure RemovePrintRange(AIndex: Integer);
15991559
16001560 { Properties }
16011561 property Orientation: TsPageOrientation read FOrientation write FOrientation;
16021562 property PageWidth: Double read FPageWidth write FPageWidth;
16031563 property PageHeight: Double read FPageHeight write FPageHeight;
16041564 property LeftMargin: Double read FLeftMargin write FLeftMargin;
16051565 property RightMargin: Double read FRightMargin write FRightMargin;
16061566 property TopMargin: Double read FTopMargin write FTopMargin;
16071567 property BottomMargin: Double read FBottomMargin write FBottomMargin;
16081568 property HeaderMargin: Double read FHeaderMargin write FHeaderMargin;
16091569 property FooterMargin: Double read FFooterMargin write FFooterMargin;
16101570 property StartPageNumber: Integer read FStartPageNumber write SetStartPageNumber;
16111571 property ScalingFactor: Integer read FScalingFactor write SetScalingFactor;
16121572 property FitHeightToPages: Integer read FFitHeightToPages write SetFitHeightToPages;
16131573 property FitWidthToPages: Integer read FFitWidthToPages write SetFitWidthToPages;
16141574 property Copies: Integer read FCopies write FCopies;
16151575 property Options: TsPrintOptions read FOptions write FOptions;
16161576 property Headers[AIndex: Integer]: String read GetHeaders write SetHeaders;
16171577 property Footers[AIndex: Integer]: String read GetFooters write SetFooters;
16181578 property RepeatedCols: TsRowColRange read FRepeatedCols;
16191579 property RepeatedRows: TsRowColRange read FRepeatedRows;
16201580 property PrintRange[AIndex: Integer]: TsCellRange read GetPrintRange;
16211581 property FooterImages[ASection: TsHeaderFooterSectionIndex]: TsHeaderFooterImage read GetFooterImages;
16221582 property HeaderImages[ASection: TsHeaderFooterSectionIndex]: TsHeaderFooterImage read GetHeaderImages;
16231583 end;
16241584
16251585 TsWorksheet = class
16261586 ...
16271587 public
16281588 property PageLayout: TsPageLayout;
16291589 ...
16301590 end;
16311591```
16321592
16331593> **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.
16341594
16351595- **Orientation** defines the orientation of the printed paper, either portrait or landscape.
16361596
16371597- **Page width** and **page height** refer to the standard orientation of the paper, usually portrait orientation.
16381598
16391599- **Left**, **top**, **right** and **bottom margins** are self-explanatory and are given in millimeters.
16401600
16411601- **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.
16421602
16431603- **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.
16441604
16451605- 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`.
16461606
16471607- 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:
16481608
16491609``` pascal
16501610 MyWorksheet.PageLayout.Options := MyWorksheet.PageLayout.Options + [poFitPages];
16511611 MyWorksheet.PageLayout.FitWidthToPages := 1; // all columns on one page width
16521612 MyWorksheet.PageLayout.FitHeightToPages := 0; // use as many pages as needed
16531613```
16541614
16551615- **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.
16561616
16571617- **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.
16581618
16591619- **Copies** specifies how often the worksheet will be printed.
16601620
16611621- 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.
16621622
16631623#### Headers and footers
16641624
16651625**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:
16661626
16671627- `&L`: begins the **left-aligned section** of a header or a footer text definition
16681628- `&C`: begins the **centered section** of a header or a footer text definition
16691629- `&R`: begins the **right-aligned section** of a header or a footer text definition
16701630- `&P`: **page number**
16711631- `&N`: **page count**
16721632- `&D`: current **date** of printing
16731633- `&T`: current **time** of printing
16741634- `&A`: **worksheet name**
16751635- `&F`: **file name** without path
16761636- `&Z`: **file path** without file name
16771637- `&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*.
16781638- `&B`: **bold** on/off
16791639- `&I`: **italic** on/off
16801640- `&U`: **underlining** on/off
16811641- `&E`: **double-underlining** on/off
16821642- `&S`: **strike-out** on/off
16831643- `&H`: **shadow** on/off
16841644- `&O`: **outline** on/off
16851645- `&X`: **superscript** on/off
16861646- `&Y`: **subscript** on/off
16871647- `&"font"`: begin using of the **font** with the specified name, e.g. `&"Arial"`
16881648- `&number`: begin using of the specified **font size** (in points), e.g. `&16`
16891649- `&Krrggbb`: switch to the **font color** specified to the binary value of the specified color, e.g. use `&KFF0000` for red.
16901650
16911651The arrays `Headers[]`/`Footers[]` provide space for usage of three different headers or footers:
16921652
16931653- `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.
16941654- `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`.
16951655- `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`.
16961656
16971657Leave 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:
16981658
16991659``` pascal
17001660 MyWorksheet.PageLayout.Headers[HEADER_FOOTER_INDEX_ALL] := '&C&D &T'; // centered "date time" on all pages as header
17011661 MyWorksheet.PageLayout.Footers[HEADER_FOOTER_INDEX_ODD] := '&RPage &P of &N'; // right-aligned "Page .. of ..." on odd pages as footer
17021662 MyWorksheet.PageLayout.Footers[HEADER_FOOTER_INDEX_EVEN] := '&LPage &P of &N'; // dto, but left-aligned on even pages
17031663```
17041664
17051665### Protection
17061666
17071667In 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.
17081668
17091669Protection is handled at three levels: workbook protection, worksheet protection and cell protection.
17101670
17111671#### Workbook protection
17121672
17131673`TsWorkbook` contains a set of workbook or document protection options:
17141674
17151675- `bpLockRevision`: specifies that the workbook is locked for revisions
17161676- `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.
17171677- `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.
17181678
17191679In relation to workbook protection is the worksheet option `soPanesProtection` which prevents the panes of a worksheet from being modified if the workbook is protected.
17201680
17211681Depending on the file format, only some of these options might be supported. In these cases, the non-supported options are commonly accepted default values.
17221682
17231683Office 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:
17241684
17251685``` pascal
17261686function TForm1.QueryPasswordHandler: String;
17271687begin
17281688 Result := InputBox('Password required', 'Password', '');
17291689end;
17301690
17311691procedure TForm1.LoadWorkbook(AFileName: String);
17321692var
17331693 workbook: TsWorkbook;
17341694begin
17351695 workbook := TsWorkbook.Create;
17361696 try
17371697 workbook.OnQueryPassword := @QueryPasswordHandler;
17381698 workbook.ReadFromFile(AFileName);
17391699 ...
17401700 finally
17411701 workbook.Free;
17421702 end;
17431703end;
17441704
17451705// or
17461706
17471707procedure TForm1.LoadWorkbookWithPassword(AFileName, APassword: STring);
17481708var
17491709 workbook: TsWorkbook;
17501710begin
17511711 workbook := TsWorkbook.Create;
17521712 try
17531713 workbook.ReadFromFile(AFileName, APassword);
17541714 ...
17551715```
17561716
17571717#### Worksheet protection
17581718
17591719`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:
17601720
17611721- `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.
17621722- `spDeleteColumns`: deleting of columns is not be allowed
17631723- `spDeleteRows`: it is not possible to delete rows
17641724- `spFormatCells`: formatting of cells is not allowed
17651725- `spFormatColumns`: columns cannot be formatted.
17661726- `spFormatRows`: rows cannot be formatted
17671727- `spInsertColumns`: it is not allowed to insert columns
17681728- `spInsertRows`: rows cannot be inserted
17691729- `spInsertHyperlinks`: it is not possible to insert new hyperlinks
17701730- `spSort`: the worksheet is not allowed to be sorted.
17711731- `spSelectLockedCells`: Cells which are locked cannot be selected any more.
17721732- `spSelectUnlockedCells`: Even cells which are unlocked cannot be selected. Together with `spSelectLockedCells` this means that the selection in the worksheet is frozen.
17731733
17741734These levels of protection become active if the option `soProtected` is added to the worksheet's `Options`, or by calling the worksheet method `Protect(true)`.
17751735
17761736#### Cell protection
17771737
17781738Cell 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:
17791739
17801740- `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.
17811741- `cpHideFormulas`: prevents formulas from being shown in the Office application.
17821742
17831743Cell protection can be changed by calling the worksheet method `WriteCellProtection`. Conversely, `ReadCellProtection` can be used to retrieve the protection state of a particular cell:
17841744
17851745``` pascal
17861746// query and modifiy the protection state of cell A1 (row=0, col=0)
17871747var
17881748 cell: PCell;
17891749 cellprot: TsCellProtections;
17901750...
17911751 // Find the cell
17921752 cell := worksheet.FindCell(0, 0);
17931753 // query cell protection
17941754 cellprot := worksheet.ReadCellProtection(cell);
17951755 // Unlock the cell for editing, don't change the visibility of formulas
17961756 worksheet.WriteCellProtection(cell, cellprot - [cpLockCell]);
17971757 // Hide formula of the cell and unlock the cell.
17981758 worksheet.WriteCellProtection(cell, [cpHideFormulas]);
17991759 // Activate protection
18001760 worksheet.Protect(true);
18011761```
18021762
18031763#### Passwords
18041764
18051765Workbook 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:
18061766
18071767``` pascal
18081768type
18091769 TsCryptoInfo = record
18101770 PasswordHash: String;
18111771 Algorithm: TsCryptoAlgorithm; // caExcel, caSHA1, caSHA256, etc.
18121772 SaltValue: String;
18131773 SpinCount: Integer;
18141774 end;
18151775```
18161776
18171777> **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.
18181778
18191779### Loading and saving
18201780
18211781#### Adding new file formats
18221782
18231783FPSpreadsheet 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.
18241784
18251785- 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.
18261786- Register the new reader/writer by calling the function `RegisterSpreadFileFormat` in the `initialization` section of this unit (implemented in unit *fpsRegFileFormats*):
18271787
18281788``` pascal
18291789function RegisterSpreadFormat(AFormat: TsSpreadsheetFormat; AReaderClass: TsSpreadReaderClass; AWriterClass: TsSpreadWriterClass;
18301790 AFormatName, ATechnicalName: String; const AFileExtensions: array of String): TsSpreadFormatID;
18311791```
18321792
18331793- `AFormat` must have the value `sfUser` to register an external file format.
18341794- `AReaderClass` is the class of the reader (or nil, if reading functionality is not implemented).
18351795- `AWriterClass` is the class of the writer (or nil, if writing functionality is not implemented).
18361796- `AFormatName` defines the name of the format as used for example in the filter list of file-open dialogs.
18371797- `ATechnicalName` defines a shorter format name.
18381798- `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`.
18391799- 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.
18401800- 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.
18411801
18421802#### Stream selection
18431803
18441804Workbooks are loaded and saved by means of the `ReadFromFile` and `WriteToFile` methods, respectively (or by their stream counterparts, `ReadFromStream` and `WriteToStream`).
18451805
18461806By 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.
18471807
18481808- 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.
18491809- 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.
18501810- If both options are set then `boBufStream` is ignored.
18511811- In practice, however, the effect of the selected streams is not very large if memory is to be saved.
18521812
18531813#### Virtual mode
18541814
18551815Beyond 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.
18561816
18571817These are the steps required to use this mode:
18581818
18591819- Activate virtual mode by adding the option `boVirtualMode` to the `Options` of the workbook.
18601820- Tell the spreadsheet writer how many rows and columns are to be written. The corresponding worksheet properties are `VirtualRowCount` and `VirtualColCount`.
18611821- 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.
18621822- Call the `WriteToFile` method of the workbook.
18631823
18641824Virtual mode also works for reading spreadsheet files.
18651825
18661826The 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.
18671827
18681828### Dataset export
18691829
18701830FPC 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).
18711831
18721832FPSpreadsheet 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.
18731833
18741834For 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.
18751835
18761836A simple example of how this works:
18771837
18781838``` pascal
18791839uses
18801840...
18811841fpsexport
18821842...
18831843var
18841844 Exp: TFPSExport;
18851845 ExpSettings: TFPSExportFormatSettings;
18861846 TheDate: TDateTime;
18871847begin
18881848 FDataset.First; //assume we have a dataset called FDataset
18891849 Exp := TFPSExport.Create(nil);
18901850 ExpSettings := TFPSExportFormatSettings.Create(true);
18911851 try
18921852 ExpSettings.ExportFormat := efXLS; // choose file format
18931853 ExpSettings.HeaderRow := true; // include header row with field names
18941854 Exp.FormatSettings := ExpSettings; // apply settings to export object
18951855 Exp.Dataset:=FDataset; // specify source
18961856 Exp.FileName := 'c:\temp\datadump.xls';
18971857 Exp.Execute; // run the export
18981858 finally
18991859 Exp.Free;
19001860 ExpSettings.Free;
19011861 end;
19021862```
19031863
19041864#### Export to DBF
19051865
19061866You 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)
19071867
19081868``` pascal
19091869procedure TForm1.ExportToDBF(AWorksheet: TsWorksheet; AFileName: String);
19101870var
19111871 i: Integer;
19121872 f: TField;
19131873 r, c: Cardinal;
19141874 cell: PCell;
19151875begin
19161876 DbfGlobals.DefaultCreateCodePage := 1251; //default encoding of the dbf
19171877 DbfGlobals.DefaultOpenCodePage := 1251; //default encoding of the dbf
19181878 if Dbf1.Active then Dbf1.Close;
19191879 if FileExists(AFileName) then DeleteFile(AFileName);
19201880
19211881 Dbf1.FilePathFull := ExtractFilePath(AFileName);
19221882 Dbf1.TableName := ExtractFileName(AFileName);
19231883 Dbf1.TableLevel := 25; // DBase IV: 4 - most widely used; or 25 = FoxPro supports nfCurrency
19241884 Dbf1.LanguageID := $C9; //russian language by default
19251885 Dbf1.FieldDefs.Clear;
19261886 //below are the fields in excel
19271887 Dbf1.FieldDefs.Add('fam', ftString);
19281888 //add other fields you want to save
19291889
19301890 Dbf1.CreateTable;
19311891 Dbf1.Open;
19321892
19331893 for f in Dbf1.Fields do
19341894 f.OnGetText := @DbfGetTextHandler;
19351895
19361896 // Skip row 0 which contains the headers
19371897 for r := 1 to AWorksheet.GetLastRowIndex do begin
19381898 Dbf1.Append;
19391899 for c := 0 to Dbf1.FieldDefs.Count-1 do begin
19401900 f := Dbf1.Fields[c];
19411901 cell := AWorksheet.FindCell(r, c);
19421902 if cell = nil then
19431903 f.Value := NULL
19441904 else
19451905 case cell^.ContentType of
19461906 cctUTF8String: f.AsString := UTF8ToCP1251(cell^.UTF8StringValue);
19471907 cctNumber: f.AsFloat := cell^.NumberValue;
19481908 cctDateTime: f.AsDateTime := cell^.DateTimeValue;
19491909 else f.AsString := UTF8ToCP1251(AWorksheet.ReadAsText(cell));
19501910 end;
19511911 end;
19521912 Dbf1.Post;
19531913 end;
19541914end;
19551915
19561916//This procedure is called so the text in the cells could be correctly dispayed on WorkSheetGrid on the form, otherwise '?' symbols showing
19571917procedure TForm1.DbfGetTextHandler(Sender: TField; var AText: string; DisplayText: Boolean);
19581918begin
19591919 if DisplayText then
19601920 AText := CP1251ToUTF8(Sender.AsString);
19611921end;
19621922```
19631923
19641924## Visual controls for FPSpreadsheet
19651925
19661926The package **laz_fpspreadsheet_visual** implements a series of controls which simiplify creation of visual GUI applications:
19671927
19681928- **TsWorkwookSource** links the controls to a workbook and notifies the controls of changes in the workbook.
19691929- **[[TsWorksheetGrid]]** implements a grid control with editing and formatting capabilities; it can be applied in a similar way to TStringGrid.
19701930- **TsWorkbookTabControl** provides a tab sheet for each worksheet of the workbook. It is the ideal container for a [[TsWorksheetGrid]].
19711931- **TsWorksheetIndicator**: a combobox which lists all worksheets of the workbook.
19721932- **TsCellEdit** corresponds to the editing line in Excel or Open/LibreOffice. Direct editing in the grid, however, is possible as well.
19731933- **TsCellIndicator** displays the name of the currently selected cell; it can be used for navigation purposes by entering a cell address string.
19741934- **TsCellCombobox** offers to pick cell properties for a selection of formatting attributes: font name, font size, font color, background color.
19751935- **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.
19761936- 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.
19771937- **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.
19781938
19791939See 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.
19801940
19811941## Examples
19821942
19831943Please see [[FPSpreadsheet: Examples]] for a variety of code examples.
19841944
19851945## Download
19861946
19871947### Subversion
19881948
19891949You can download FPSpreadsheet using the subversion software and the following command line:
19901950
19911951``` bash
19921952svn checkout https://svn.code.sf.net/p/lazarus-ccr/svn/components/fpspreadsheet fpspreadsheet
19931953```
19941954
19951955### Stable releases
19961956
19971957The 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".
19981958
19991959Older releases of FPSpreadsheet cann still be found on [sourceforge](https://sourceforge.net/projects/lazarus-ccr/files/FPSpreadsheet/).
20001960
20011961## Installation
20021962
20031963- 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.
20041964- 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.
20051965- 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.
20061966- FPSpreadsheet is developed with the latest stable fpc version (currently fpc 3.0.2). We only occasionally check older versions.
20071967- 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.
20081968
20091969### Conditional defines
20101970
20111971Here 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:
20121972
20131973- `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`.
20141974- `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.
20151975- `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.
20161976- `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`.
20171977- `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.
20181978- `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.
20191979- `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.
20201980- `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.
20211981- `FPS_NO_STRING_SPLIT`: Activate the following define if FPS does not have the string Split helper, e.g. before v3.0
20221982
20231983All these defines are collected in the include file *fps.inc*.
20241984
20251985In 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.
20261986
20271987## Support and Bug Reporting
20281988
20291989The recommended place to discuss FPSpreadsheet and obtain support is asking in the [Lazarus Forum](http://forum.lazarus.freepascal.org/index.php?board=49.0).
20301990
20311991Bug reports should be sent to the [Lazarus/Free Pascal Bug Tracker](http://bugs.freepascal.org/); please specify the "Lazarus-CCR" project.
20321992
20331993## Current Progress
20341994
20351995### Progress by supported cell content
20361996
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>
1997+| Format | Multiple · sheets | Unicode | Reader · support | Writer · support | Text | Number | String · Formula | RPN · Formula | 3D cell · references | Date/Time | Comments | Hyperlinks | Images +++ | Protection | Conditional · formats |
1998+|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1999+| CSV files | No | Yes + | Working ++ | Working ++ | Working ++ | Working ++ | N/A | N/A | N/A | Working ++ | N/A | N/A | N/A | N/A | N/A |
2000+| Excel 2.x | No | No * | Working ** | Working | Working | Working | Working | Working *** | N/A | Working | Working | N/A | N/A | Working | N/A |
2001+| Excel 5.0 (Excel 5.0 and 95) | Yes | No * | Working ** | Working | Working | Working | Working | Working *** | Working | Working | Working | N/A | N/A | Working | N/A |
2002+| Excel 8.0 (Excel 97- 2003) | Yes | Yes | Working ** | Working | Working | Working | Working | Working *** | Working | Working | Reading only | Working | Not working | Working | Not working |
2003+| Excel 2003/XML | Yes | Yes | Working ** | Working | Working | Working | Working *** | Working | Working | Working | Working | Working | N/A | Working | Working |
2004+| Excel OOXML | Yes | Yes | Working ** | Working | Working | Working | Working *** | Working | Working | Working | Working | Working | Working | Working | Working ++++ |
2005+| OpenDocument | Yes | Yes | Working ** | Working | Working | Working | Working *** | Working | Working | Working | Working | Working | Working | Working | Working |
2006+| HTML | No | Yes | Working ++ | Working ++ | Working ++ | Working ++ | N/A | N/A | N/A | Working ++ | N/A | Working | Not working | N/A | N/A |
2007+| Wikitable files (Mediawiki) | No | Yes | planned | Working ++ | Working ++ | Working ++ | N/A | N/A | N/A | Working ++ | N/A | N/A | Not working | N/A | N/A |
20572008
20582009(+) Depends on file.\
20592010(++) No "true" number format support because the file does not containg number formatting information. But the number format currently used in the spreadsheet understood.\
20602011(+++) Only very basic image support: no transformations, no cropping, no image manipulation.\
20612012(++++) Extended OOXML formatting options not supported.\
20622013(*) 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.\
20632014(**) Some cell could be returned blank due to missing or non ready implemented number and text formats.\
20642015(***) This is the format in which the formulas are written to file (determined by design of the file format).\
20652016(****) Writing of all formats is supported. Some rare custom formats, however, may not be recognized correctly. BIFF2 supports only built-in formats by design.
20662017
20672018### Progress of the formatting options
20682019
20692020The following formatting options are available:
20702021
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>
2022+| Format | Text · alignment | Text · rotation | Font | Rich · text | Border | Color · support | Back · ground | Word · wrap | Col&Row · size | Number · format | Merged · cells | Page · layout | Print · ranges | Header/footer · images | Column/row · format | Hide · cols/rows | Page · breaks |
2023+|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2024+| CSV files | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
2025+| Excel 2.x | Working * | N/A | Working | N/A | Working | Working | Working** | N/A | Working | Working | N/A | Working | N/A | N/A | Working | N/A | Working |
2026+| Excel 5.0 · (Excel 5.0 and 95) | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | N/A | Working | Working | N/A | Working | Working | Working |
2027+| Excel 8.0 · (Excel 97 - XP) | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Not working | Working | Working | Working |
2028+| Excel 2003/XML | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | N/A | Working | Wworking | Working |
2029+| Excel OOXML (xlsx) | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working | Working |
2030+| OpenDocument | Working | Working | Working | Working | Working | Working | Working*** | Working | Working | Working | Working | Working | Working | Working | Working | Working | |
2031+| HTML (+) | Working | bugs | Working | Working | bugs | Working | Working | Writing only | Writing only | N/A | Working | N/A | N/A | Not working | Writing only | to be done | N/A |
2032+| Wikitable (Mediawiki) | Writing only | N/A | Writing only | Not working | Writing only | Writing only | | Writing only | Writing only | N/A | Writing only | N/A | N/A | Not working | Writing only | to be done | N/A |
21112033
21122034(N/A) Feature is not available for this format intrinsically.\
21132035(*) BIFF2 supports only horizontal text alignment, vertical alignment is ignored.\
21142036(**) BIFF2 does not support a background color; a dotted black&white background is used instead.\
21152037(***) OpenDocument supports only uniform backgrounds; a fill color interpolated between foreground and background colors is written instead.\
21162038(****) Only uniform background color, no fill styles.\
21172039(+) HTML reader does not support styles. Since the writer does use styles these files are not read back correctly.
21182040
21192041### Progress of workbook/worksheet user-interface options
21202042
21212043Some additional options were added to interface the file contents with the `TsWorksheetGrid`:
21222044
21232045| Format | Hide grid lines | Hide headers | Frozen Panes | Active sheet/cell | Zooming | BiDi mode | Tab color |
21242046|----|----|----|----|----|----|----|----|
21252047| Excel 2.x | Working | Working | not working | N/A | N/A | N/A | N/A |
21262048| Excel 5.0 (Excel 5.0 and 95) | Working | Working | Working | Working | Working | N/A | N/A |
21272049| Excel 8.0 (Excel 97 - XP) | Working | Working | Working | Working | Working | Working | Working |
21282050| Excel2003/XML | Working | Working | Working | Working | Working \|\| class="working\|Working | N/A | |
21292051| Excel OOXML | Working | Working | Working | Working | Working | Working | Working |
21302052| OpenDocument | Working | Working | Working | Working | Working | Working | Working |
21312053| HTML | Writing only | Writing only | N/A | N/A | N/A | not working | N/A |
21322054
21332055### To do list
21342056
21352057Note: 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!
21362058
21372059- Find out why BIFF2 files are corrupt when saved with frozen rows/cols activated.
21382060- Add row and column formats
21392061- Add reading support for wikitable (Mediawiki) files
21402062- 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).
21412063- Improve color support: due to palette support colors may change from file to file currently.
21422064- Add embedded images.
21432065- Fix writing of cell comments to BIFF8 files.
21442066
21452067**Long-term:**
21462068
21472069- 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.
21482070- Store formatting in a format list of the workbook, not in the cell, to reduce memory usage.
21492071- Use BIFF8 file-wide string storage instead of storing strings in cells (should reduce memory usage in case of many duplicate strings)
21502072- Redo ooxml and ods readers based upon SAX/TXmlReader instead of DOM to reduce memory usage of large files.
21512073- 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).
21522074
21532075## Changelog
21542076
21552077### SVN
21562078
21572079**Changes with respect to current release**
21582080
21592081- (currently none)
21602082
21612083**Incompatible changes**
21622084
21632085- (currently none)
21642086
21652087### Version 1.16
21662088
21672089This is the latest stable release.
21682090
21692091**Changes with respect to current release**
21702092
21712093- XLSX reader can handle embedded as well as header/footer images now.
21722094- Less strict format check by Excel2 reader since there are BIFF2 files with BOF record of Excel8 which Excel can read.
21732095- Reading support for the Excel3 and Excel4 formats (unit *xlsbiff34*)
21742096- ODS reader supports the \<text:s\> node
21752097- ODS reader is able to open encrypted files.
21762098
21772099**Incompatible changes**
21782100
21792101- (none)
21802102
21812103### Version 1.14
21822104
21832105**Changes with respect to v1.12**
21842106
21852107- Implementation of **conditional formats** for ods, xlsx and Excel xml.
21862108- Implementation of **meta data** for ods, xlsx and Excel xml.
21872109- Add a worksheet-based dataset in separate package (**TsWorksheetDataset**).
21882110
21892111**Incompatible changes**
21902112
21912113- Removed the deprecated worksheet properties DefaultRowHeight and DefaultColWidth. Use the corresponding Read/Write routines instead (ReadDefaultColWidth(units), WriteDefaultColWidth(units)).
21922114
21932115### Version 1.12
21942116
21952117**Changes with respect to v1.10x**
21962118
21972119- **Hide** (and unhide) rows and columns.
21982120- Enforce **Page breaks** before rows and columns during printing by the Office applications.
21992121- Full support (reading and writing) of the **ExcelXML** xml format (Excel 2003 and XP).
22002122- 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.
22012123- Add TsWorksheetIndicator to visual controls.
22022124
22032125### Version 1.10.1
22042126
22052127**Changes with respect to v1.8x**
22062128
22072129- **Workbook, worksheet and cell protection** (read/write in BIFF2/BIFF5/BIFF8/OOXML/ODS, write in ExcelXML).
22082130- New package **laz_fpspreadsheet_crypto** to decipher the encryption for worksheet-protection in xls files. Requires DCPcrypt.
22092131- TsWorksheetGrid can **display embedded images**.
22102132- **Drag and drop** in TsWorksheetGrid
22112133- New, **highDPI-aware** component palette icons.
22122134- New workbook optiond **boAbortReadingOnFormulaError** and **boIgnoreFormulas**.
22132135- Formulas with **references to other sheets**, i.e. `'=Sheet1!A1+Sheet2!A2'`
22142136
22152137**Incompatible changes**
22162138
22172139- The field **FormulaValue** has been removed from the cell record. The cell formula now can be retrieved by calling `Worksheet.ReadFormula(cell)`.
22182140
22192141### Version 1.8
22202142
22212143**Changes with respect to v1.6x**
22222144
22232145- **"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`).
22242146- **Searching** for cells with specified content in worksheet or workbook.
22252147- Support for reading and writing of **HTML format**
22262148- Support for writing of the **ExcelXML format** (Excel XP and 2003)
22272149- Ability to use **user-provided file reader/writer classes** to extend FPSpreadsheet to new file formats.
22282150- Readers and writers now support all the **line styles** of Excel8 and OOXML.
22292151- xls, xlsx and ods readers/writers now support the **active worksheet** and **selected cell**.
22302152- Ability to write to/read from the system's **clipboard** for copy & paste using the visual controls.
22312153- Support for **print ranges** and **repeated header rows and columns** in the Office applications.
22322154- Support for **embedded images** (currently only writing to xlsx and ods, no reading).
22332155- Improved compatibility of **TsWorksheetGrid** with TStringGrid (`Cells[Col,Row]` property). Standalone application as an advanced StringGrid replacement.
22342156- 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.
22352157- Support of several **units** for specification of column widths and row heights.
22362158- The library now supports **localization** using po files. Translations are welcome.
22372159- **Zoom factor** read and written by the worksheet, and applied by the TsWorksheetGrid.
22382160- Support of **column and row formats**
22392161- Support of **hidden** worksheets
22402162
22412163**Incompatible changes**
22422164
22432165- 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.
22442166- 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.
22452167- The public properties of `TsWorksheetGrid` using a `TRect` as parameter were modified to use the Left, Top, Right, Bottom values separately.
22462168- 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.
22472169- Most of the predefined color constants were marked as deprecated; only the basic EGA colors will remain.
22482170- Unit fpsNumFormatParser is integrated in fpsNumFormat. Old code which "uses" fpsNumFormatParser must "use" fpsNumFormat now.
22492171- 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.
22502172
22512173### Version 1.6
22522174
22532175**Changes with respect to v1.4.x**
22542176
22552177- 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.
22562178- 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)
22572179- 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)
22582180- Comments in cells
22592181- Background fill patterns
22602182- Hyperlinks
22612183- Enumerators for worksheet's internal AVLTrees for faster iteration using a for-in loop.
22622184- Formatting of numbers as fractions.
22632185- Improved number format parser for better recognition of Excel-like number formats.
22642186- Page layout (page margins, headers, footer, used for only when printing in the Office applications - no direct print support in fpspreadsheet!)
22652187- Improved color management: no more palettes, but direct rgb colors. More pre-defined colors.
22662188- A snapshot of the wiki documentation is added to the library as chm help file.
22672189
22682190**Incompatible changes**
22692191
22702192- 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.
22712193- 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.
22722194- 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])`.
22732195- **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.
22742196- 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.
22752197- 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.
22762198
22772199### Version 1.4
22782200
22792201**Changes with respect to v1.2.x**
22802202
22812203- 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`).
22822204- **Shared formulas** (reading for sfExcel5, sfExcel8, sfOOXML; writing for sfExcel2, sfExcel5, sfExcel8).
22832205- Significant **speed-up** of writing of large spreadsheets for the xml-based formats (ods and xlsx), speed up for biff2; **speedtest demo** program
22842206- **VirtualMode** allowing to read and write very large spreadsheet files without loading entire document representation into memory. Formatting of cells in VirtualMode.
22852207- Demo program for database export using virtual mode and TFPSExport.
22862208- Added db export unit allowing programmatic exporting datasets using **TFPSExport**. Similar export units are e.g. [[fpdbfexport]], [[fpXMLXSDExport]].
22872209- Reader for **xlsx** files, now fully supporting the same features as the other readers.
22882210- Reader/writer for **CSV files** based on [[CsvDocument]].
22892211- **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
22902212- **Insertion and deletion of rows and columns** into a worksheet containing data.
22912213- Implementation of **sorting** of a worksheet.
22922214- Support of **diagonal "border" lines**
22932215- **Logging of non-fatal error messages** during reading/writing (TsWorksheet.ErrorMsg)
22942216- **Merged** cells
22952217- **Registration** of currency strings for automatic conversion of strings to **currency values**
22962218- 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]].
22972219- **Overflow cells** in TsWorksheetGrid: label cells with text longer than the cell width extend into the neighboring cell(s).
22982220
22992221**Incompatible changes**
23002222
23012223- 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).
23022224- 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.
23032225- With full support of string formulas some features related to RPN formulas were removed:
23042226 - The field `RPNFormulaResult` of TCell was dropped, as well as the element `cctRPNFormula` in the `TsContentType` set.
23052227 - Sheet function identifiers were removed from the `TsFormulaElement` set, which was truncated after `fekParen`.
23062228 - 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`.
23072229 - 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).
23082230 - Code related to RPN formulas was moved to a separate unit, `fpsRPN`. Add this unit to the uses clause if you need RPN features.
23092231
23102232## License
23112233
23122234LGPL with static linking exception. This is the same license as is used in the Lazarus Component Library.
23132235
23142236## References
23152237
23162238### Documentation
23172239
23182240FPSpreadsheet is documented in this wiki file.
23192241
23202242Every 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.
23212243
23222244This 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:
23232245
23242246- Version 1.16: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=157438](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=157438)
23252247- Version 1.14: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=149828](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=149828)
23262248- Version 1.12: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=136886](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118771)
23272249- 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)
23282250- Version 1.10: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118441](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=118441)
23292251- Version 1.8: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=107616](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=107616)
23302252- 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)
23312253- Version 1.6: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=91469](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=91469)
23322254- Version 1.4: [wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=85299](https://wiki.lazarus.freepascal.org/index.php?title=FPSpreadsheet&oldid=85299)
23332255- 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)
23342256
23352257### Wiki links
23362258
23372259- [[Office Automation]]
23382260- [[CsvDocument]]
23392261- [[FPSpreadsheet: Examples]]
23402262- [[RPN Formulas in FPSpreadsheet|RPN formulas in FPSpreadsheet]]
23412263- [[FPSpreadsheet: List of formulas]]
23422264- [[FPSpreadsheet tutorial: Writing a mini spreadsheet application]]
23432265
23442266### External Links
23452267
23462268- [Microsoft OLE Document Format](http://sc.openoffice.org/compdocfileformat.pdf)
23472269- [Excel file format description](http://sc.openoffice.org/excelfileformat.pdf)
23482270- 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.
23492271- Icons used in the demo programs:
23502272 - [silk icons](http://www.famfamfam.com/lab/icons/silk/)
23512273 - [fugue icons](http://p.yusukekamiyamane.com/)
23522274
23532275---
23542276*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).*
23552277Category: Components
23562278Category: Data import and export
23572279Category: FPSpreadsheet
23582280Category: Grids
23592281Category: Lazarus-CCR

Back to history