Sign in Join
Wiki copytemporary

TsWorksheetGrid

English · Русский

Overview

TsWorksheetGrid is a specialized grid component which interfaces to a TsWorksheet from the FPSpreadsheet library and displays spreadsheet data files like in a conventional TStringGrid.

Programming interface

TsWorksheetGrid inherits from TCustomGrid and behaves much like a standard TStringGrid. The main difference is that the grid itself does not store data, but data are stored in a TWorksheet of FPSpreadsheet. The worksheet can be accessed by using the property Worksheet of the grid. Similarly, Workbook allows to access the entire workbook to which the worksheet belongs.

A variety of properties are available to access cells, their values and attributes, in a StringGrid-like way, such as writing a cell value by means of Grid.Cells[ACol, ARow] := 1.234. The cells are identified in these properties by means of the cell's column and row indexes. Please note that the indexes are passed in the order "column first / row last", and they include the indexes occupied by the fixed cells, i.e. the top/left data cell has the indexes col=1 and row=1. This is different from fpspreadsheat where the indexes always start at 0 and are passed to functions in the opposite order "row first / column last".

Access to cell values

The property Cells[ACol, ARow] provides access to the data in a cell given by its column and row indexes. This is similar to TStringGrid. Unlike TStringGrid which works with strings only, TsWorksheetGrid, however, accepts numbers, dates, booleans, and formulas as well. For this reason, the data type of Cells is a variant.

Writing of cell values

Use this code to write data to a cell in a TsWorksheetGrid named Grid for simplicity:

pascal
  // Write a string
  Grid.Cells[1, 1] := 'This is a string';  
  // Write a string with embedded HTML codes
  Grid.Cells[1, 2] := 'Chemical formula of <b>water</b>: H<sub>2</sub>O';
  // Write a number
  Grid.Cells[1, 3] := 1.2345;
  // Write a date
  Grid.Cells[1, 4] := EncodeDate(2016, 1, 18);
  // Write a formula
  Grid.Cells[1, 5] := '=A3+2';
  // etc.

Note: A text assigned to a cell can contain embedded simple HTML codes to change the font for particular words or characters.

Reading of cell values

In the same way, cell values can be read into variables of decidated types:

pascal
var
  str: String;
  x: Double;
begin
  str := Grid.Cells[1, 1];  // Variable "str" will contain the value "This is a string"
  x := Grid.Cells[1, 2];    // x will be 1.2345
  str := Grid.Cells[1, 2];  // Although the cell contains a number it is converted to the string "1.2345"
end;

Comparing cell values

Since the Cells property is a variant it is a bit more difficult to compare string values. Use the string-to-variant conversion function VarToStr() provided by unit variants.

pascal
  // This straightforward comparison will fail:
  // if Grid.Cells[1,1] = 'This is a string' then ...

  // Use this instead:
  if VarToStr(Grid.Cells[1,1]) = 'This is a string' then ...

Numerical values often can be compared without an explicit conversion:

pascal
  if Grid.Cells[1,2] = 1.2345 then ...

Formulas in cells

Since the TsWorksheetGreed works on top of a spreadsheet all formulas supported by FPSpreadsheet can be entered. See this document for a complete list of supported formulas.

The formula string must begin with the character "=". Cell references must follow Excel's "A1" notation, i.e. column index must be characters "A".."Z" , and row index is a 1-based integer. If there are more than 26 columns then two (or three) characters can be used.

In case of a cell range, the coordinates of the top-left and bottom-right corners of the cell rectangle must be separated by a colon, e.g. '=SUM(A1:C10)' calculates the sum of the values in the cell rectangle extending from A1 to C10.

Formulas referring to cells in other sheets can be used by following the Excel syntax: specify the sheet name followed by a "!" in front of the cell addresses, e.g. '=Sheet3!A1' or '=SUM(Sheet3:Sheet4!A1:C10)'.

Note that formulas are not automatically calculated by default. In order to activate automatic calculation of formulas set the grid property AutoCalc to true, or set the option boAutoCalc of the workbook used by the grid. "Automatic calculation" means that all formulas in the entire worksheet are recalculated whenever the content of any cell changes. Therefore, it is not required that the cells addressed by the formula already have values when the formula is entered.

pascal
// Enable automatic calculation of formulas
Grid.AutoCalc := true;        
// or: Grid.Workbook.Options := Grid.Workbook.Options + [boAutoCalc];

// Enter cells
Grid.Cells[1,1] := 1;         // this is cell A1
Grid.Cells[1,2] := 2;         // this is cell A2

// Enter formula
Grid.Cells[1,3] := '=A1+A2';  // Calculates the sum of the values in A1 and A2 

// Another formula in Cell B3
Grid.Cells[2,3] := '=B1*B2';  // It does not matter that the cells B1 and B2 do not exist, yet.

// Enter cells needed by the formula
Grid.Cells[2,1] := '=A3';     // Use the result of the previous formula
Grid.Cells[2,2] := 10;

Cell formatting

Cell attributes can be attached to each cell in a similar way as the cell values. There is a set of grid properties representing each attribute:

These properties can also be accessed for a range of cells specified by the indexes of the left column, top row, right column and bottom row of the cell block. Since these properties are related to several cells they are spelled in plural form (with appended "s"):

If properties to be read do not have identical values within the cell block then a neutral or default value is returned.

Example

This example adds a formula for today's date to cell A1, formats the cells to display the number as a date and selects a white, italic font on lightgray background. A red dotted border is drawn around the cell.

pascal
const
  RED_DOTTED_BORDER: TsBorderStyle = (LineStyle: lsDotted; Color: scRed);

// Set cell content
Grid.Cells[1,1] := '=TODAY()';

// Format as date
Grid.Numberformat[1,1] := 'yyyy/mm/dd';

// Select background color
Grid.BackgroundColor[1,1] := scSilver;

// Select format 
Grid.FontColor[1,1] := scWhite;
Grid.FontStyle[1,1] := [fssItalic];

// Activate cell borders 
Grid.Border[1,1] := [cbEast, cbWest, cbNorth, cbSouth];

// Determine how cell borders will be drawn
Grid.BorderStyle[1,1, cbEast] := RED_DOTTED_BORDER;
Grid.BorderStyle[1,1, cbWest] := RED_DOTTED_BORDER;
Grid.BorderStyle[1,1, cbNorth] := RED_DOTTED_BORDER;
Grid.BorderStyle[1,1, cbSouth] := RED_DOTTED_BORDER;

Defining cell borders for a larger cell block by using these properties is a bit cumbersome because different styles may have to be used for the corder, border and inner cells. To simplyfy this task, the grid provides a method ShowCellBorders which gets the coordinates of the cell block and the styles of the left, top, right, bottom outer, and horizontal and vertical inner border lines. Use the constant NO_CELL_BORDER of no border line should be drawn at the specific location:

pascal
const
  THICK_CELL_BORDER: TsCellBorderStyle = (LineStyle: lsThick; Color: clBlack);
  DOTTED_CELL_BORDER: TsCellBorderStyle = (LineStyle: lsDotted; Color: clSilver);

// Draw a thick border around the block A1:C3, no inner border
Grid.ShowCellBorders(1,1, 3,3,      // left, top, right, bottom coordinates of cell block
  THICK_CELL_BORDER, THICK_CELL_BORDER, THICK_CELL_BORDER, THICK_CELL_BORDER,   // outer border styles
  NO_CELL_BORDER, NO_CELL_BORDER                                                // inner border styles
);

// Draw a thick border around the block A1:C3, dotted gray horizontal inner lines
Grid.SetCellBorders(1,1, 3,3, 
  THICK_CELL_BORDER, THICK_CELL_BORDER, THICK_CELL_BORDER, THICK_CELL_BORDER, 
  DOTTED_CELL_BORDER, NO_CELL_BORDER
);

Cell comments

Comments can be added to each cell by using the grid's property CellComment[ACol, ARow: Integer]: String. Cells containing a comment are marked with a red triangle in the upper right corner of a cell. If the mouse is moved into a cell with a comment a popup window appears to display the comment.

Note: For the popup window to show up it is required to add the flag goCellHints to the grid's Options, and the standard grid property ShowHint must be true. Otherwise the popup windows will not appear.

Example:

pascal
Grid.Cells[1,1] := '=pi()';
Grid.CellComment[1,1] := 'The number pi is needed to calculate the area and circumference of a circle.';

Hyperlinks in cells

Cells with attached hyperlinks allow the user to navigate to other cells or other documents by clicking on the cell. Hyperlinks can be accessed by using the property Hyperlink[ACol, ARow: Integer: String. The hyperlink string contains the hyperlink target and an optional tooltip text which is separated by means of a bar character ("|"). Internal targets are already handled by the grid, but for navitation to the hyperlink an event handler for OnClickHyperlink must be provided. To distinguish normal cell clicks from hyperlink clicks the mouse must be held down for fractions of a second before the hyperlink is executed.

Example:

pascal
// Example for adding an external hyperlink
Grid.Cells[1,1] := 'Lazarus';
Grid.Hyperlink[1,1] := 'www.lazarus-ide.org|Open Lazarus web site';

// Example for adding an internal hyperlink
Grid.Cells[2,2] := 'Summary';
Grid.Hyperlink[2,2] := '#Sheet2!B10|Go to the summary starting at cell B10 of sheet2';

// Example for an OnClickHyperlink event handler needed for external hyperlinks
uses
  ..., uriparser;

procedure TForm1.GridOnClickHyperlink(Sender: TObject; const AHyperlink: TsHyperlink);
begin
var
  uri: TUri;
begin
  uri := ParseURI(AHyperlink.Target);
  case Lowercase(uri.Protocol) of
    'http', 'https', 'ftp', 'mailto', 'file':
      OpenUrl(AHyperlink.Target);
    else
      ShowMessage('Hyperlink ' + AHyperlink.Target + ' clicked');
  end;
end;

Note: Follow the instructions above to show the tooltip text as a popup window.

Merged cells

A rectangular group of cells can be merged to a single block. The content of the top/left cell of this block is displayed across all the combined cells, the content of the other cells is ignored.

Use the method MergeCells to perform this operation. As parameters, it requires the left, top, right and bottom coordinates of the cell range to be merged. They also can be combined into a a TRect record. The method Unmerge splits a previously merged block again in the individual cells, here the coordinates of a single cell from the merged range is sufficient.

pascal
  // Example for merging
  Grid.MergeCells(1,1, 3,1);          // Combine the first 3 cells of the first row
  Grid.Cells[1,1] := 'Summary';       // Write the text "Summary" across the 3 cells
  Grid.HorAlignment[1,1] := haCenter; // and center it.

  // Example for unmerging
  Grid.UnmergeCells(1,1);             // Splits the merged block (1,1..3,1)

Column widths and row heights

Column widths and row heights can be changed for all cells by setting the DefaultColWidth and DefaultRowHeight. This works also in design mode. In addition, the widths and heights of particular columns and rows can be modified by the properties ColWidths[ACol] and RowHeights[ARow]. These values must be given in pixels.

pascal
  Grid.DefaultColWidth := 80;  // This is the width of all columns 
  Grid.ColWidths[10] := 10;    // except for column #10 which is only 10 pixels wide.

  Grid.DefaultRowHeight := 20; // All rows are 20 pixels high
  Grid.RowHeights[2] := 4;     // Row #2 serves as a spacer and is only 4 pixels high.

Worksheet and cell protection

The worksheet grid supports protection at the worksheet and cell level. This way, for example, an entire worksheet can be protected from changes by the user except for some specific cells. For this purpose you must follow the same inverted logic used also by Excel and LibreOffice Calc: Protect the entire worksheet, and then remove the protection from the writeable cells. In the following code snipped editing is allowed only in cells A1 and C2:C5:

pascal
  // Protect the worksheet
  Grid.Worksheet.Protection := DEFAULT_SHEET_PROTECTION;
  Grid.Worksheet.Protect(Checkbox1.Checked);

  // Unprotect the writeable cells A1 and C2:C5
  Grid.CellProtection[1, 1] := []; 
  Grid.CellProtections[3, 2, 3, 5] := [];

For further details on all protection options see the main FPSpreadsheet documentation.

New grid properties

In addition to the properties inherited from its ancestors TCustomDrawGrid and TCustomGrid, the TsWorksheetGrid introduces the following new published properties:

Events

Recommended property values

In order to set up the grid to behave similar to the well-known Office applications we recommend the following grid property settings. It should be emphasized, though, that differences in usage do exist and cannot be removed without a major re-write of the inherited grid infrastructure:

See also


From the Free Pascal wiki, page "TsWorksheetGrid", as it stood on 2023-12-19 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.

Revision 1, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.