Difference between revisions of "FPSpreadsheet tutorial: Writing a mini spreadsheet application/es"

From Free Pascal wiki
Jump to navigationJump to search
Line 12: Line 12:
 
== Controles Visuales FPSpreadSheet ==
 
== Controles Visuales FPSpreadSheet ==
  
FPSpreadsheet exposes non-visual classes, tales como TsWorkbook, TsWorksheet etc. Esto mantiene la librería suficientemente generalizada para todo tipo de programas Pascal. Por otro lado, para programamas con Interfaz Gráfica de Usuario (GUI, se necesita algo de infraestructura que relacione los SpreadSheets con los formularios, grids y otros controles.
+
FPSpreadsheet expone clases no visuales, tales como TsWorkbook, TsWorksheet etc. Esto mantiene la librería suficientemente generalizada para todo tipo de programas Pascal. Por otro lado, para programamas con Interfaz Gráfica de Usuario (GUI, se necesita algo de infraestructura que relacione los SpreadSheets con los formularios, grids y otros controles.
  
 
=== TsWorkbookSource ===
 
=== TsWorkbookSource ===
 +
 
[[file:TSWORKBOOKSOURCE.png]]  
 
[[file:TSWORKBOOKSOURCE.png]]  
The heart of the visual FPSpreadsheet controls is the '''TsWorkbookSource''' class. This provides a link between the non-visual spreadsheet data and the visual controls on the form. Its purpose is similar to that of a TDataSource component in database applications which links database tables or queries to dedicated "data-aware" controls.
 
  
All visual FPSpreadsheet controls have a property <code>WorkbookSource</code> which links them into the information chain provided by the TsWorkbookSource. The WorkbookSource keeps a list of all controls attached. Internally, these controls are called "listeners" because they listen to information distributed by the WorkbookSource.
+
El corazón de los controles visuales FPSpreadSheet es la clase '''TsWorkbookSource''' que aporta un enlace entre los datos no visuales spreadsheet y los controles visuales del formulario. Su propósito es similar al que tiene el componente TDataSource en aplicaciones de base de datos que enlazan las tablas de las bases de datos o consultas (queries) a controles orientados a datos (data-aware).
 +
 
 +
Todos los controles visuales FPSpreadSheet tienen una propiedad <code>WorkbookSource</code> que los enlaza con la cadena de información aportada por TsWorkbookSource. WorkbookSource mantiene un listado de todos los controles vinculados. Estos controles se llaman internamente "listeners" porque se encuentran en modo escucha de la informa distribuida por WorkbookSource.
 +
 
 +
El libro de trabajo (WorkBook) y las hojas de trabajo (WorkSheets) que contiene utilizan eventos para notificar a WorkBookSource todos los cambios relevantes:
 +
cambios en el contenido de las celdas o su formato, selección de otras celdas, añadir o borrar hojas de trabajo, etc. La información de estos cambios se pasa a través de los controles "listening"  y reaccionan a su propio modo especializado a dichos cambios. Si por ejemplo se añade una hoja de trabajo a un libro, entonces el control visual TsWorkbookTabControl crea una nueva solapa para la hoja de trabajo y el grid "TsWorksheetGrid" carga la nueva hoja de trabajo dentro de la grid.
  
The workbook and worksheets use events to notify the WorkbookSource of all relevant changes: changes in cell content or formatting, selecting other cells, adding or deleting worksheet etc. Information on these changes is passed on to the listening controls, and they react in their own specialized way on these changes. If, for example, a new worksheet is added to a workbook the visual TsWorkbookTabControl creates a new tab for the new worksheet, and the TsWorksheetGrid loads the new worksheet into the grid.
+
=== Control TsWorkbookTabControl ===
  
=== TsWorkbookTabControl ===
 
 
[[file:TSWORKBOOKTABCONTROL.png]]
 
[[file:TSWORKBOOKTABCONTROL.png]]
 +
 
This is a tabcontrol which provides a tab for each worksheet of the current workbook. The tab names are identical with the names of the worksheets. Selecting another tab is communicated to the other visual spreadsheet controls via the WorkbookSource.
 
This is a tabcontrol which provides a tab for each worksheet of the current workbook. The tab names are identical with the names of the worksheets. Selecting another tab is communicated to the other visual spreadsheet controls via the WorkbookSource.
  
 
=== TsWorksheetGrid ===
 
=== TsWorksheetGrid ===
 +
 
[[file:TSWORKSHEETGRID.png‎]]
 
[[file:TSWORKSHEETGRID.png‎]]
 +
 
This is a customized DrawGrid descendant of the LCL and displays cells of the currently selected worksheet. The texts are not stored in the grid (like a StringGrid would do), but are taken from the TsWorksheet data structure. Similarly, the worksheet provides the information of how each cell is formatted. Like any LCL grid it has a bunch of properties and can be tuned for many applications by adapting its <code>Options</code>. The most important one will be described below.  
 
This is a customized DrawGrid descendant of the LCL and displays cells of the currently selected worksheet. The texts are not stored in the grid (like a StringGrid would do), but are taken from the TsWorksheet data structure. Similarly, the worksheet provides the information of how each cell is formatted. Like any LCL grid it has a bunch of properties and can be tuned for many applications by adapting its <code>Options</code>. The most important one will be described below.  
 
{{Note|The TsWorksheetGrid can also be operated without a TsWorkbookSource. For this purpose it provides its own set of methods for reading and writing files.}}
 
{{Note|The TsWorksheetGrid can also be operated without a TsWorkbookSource. For this purpose it provides its own set of methods for reading and writing files.}}
  
 
=== TsCellEdit ===
 
=== TsCellEdit ===
 +
 
[[file:TSCELLEDIT.png]]
 
[[file:TSCELLEDIT.png]]
 +
 
The typical spreadsheet applications provide a line for editing formulas or cell content. This is the purpose of the '''TsCellEdit'''. It displays the content of the active cell of the worksheet which is the same as the active cell of the WorksheetGrid. If editing is finished (by pressing {{keypress|Enter}}, or by selecting another cell in the WorksheetGrid) the new cell value is transferred to the worksheet. Internally, the TsCellEdit is a memo control, i.e. it is able to process multi-line text correctly. Use {{keypress|Ctrl}}+{{keypress|Enter}} to insert a forced line-break.
 
The typical spreadsheet applications provide a line for editing formulas or cell content. This is the purpose of the '''TsCellEdit'''. It displays the content of the active cell of the worksheet which is the same as the active cell of the WorksheetGrid. If editing is finished (by pressing {{keypress|Enter}}, or by selecting another cell in the WorksheetGrid) the new cell value is transferred to the worksheet. Internally, the TsCellEdit is a memo control, i.e. it is able to process multi-line text correctly. Use {{keypress|Ctrl}}+{{keypress|Enter}} to insert a forced line-break.
  
 
=== TsCellIndicator ===
 
=== TsCellIndicator ===
 +
 
[[file:TSCELLINDICATOR.png]]
 
[[file:TSCELLINDICATOR.png]]
 +
 
This is a TEdit control which displays the address of the currently selected cell in Excel notation, e.g. 'A1' if the active cell is in the first row and first column (row = 0, column = 0). Conversely, if a valid cell address is entered into this control the corresponding cell becomes active.  
 
This is a TEdit control which displays the address of the currently selected cell in Excel notation, e.g. 'A1' if the active cell is in the first row and first column (row = 0, column = 0). Conversely, if a valid cell address is entered into this control the corresponding cell becomes active.  
  
 
=== TsCellCombobox ===
 
=== TsCellCombobox ===
 +
 
[[file:TSCELLCOMBOBOX.png]]This combobox can be used to modify various cell properties by selecting values from the dropdown list. The property affected is determined by the <code>CellFormatItem</code> of the combobox:
 
[[file:TSCELLCOMBOBOX.png]]This combobox can be used to modify various cell properties by selecting values from the dropdown list. The property affected is determined by the <code>CellFormatItem</code> of the combobox:
 
* <code>cfiFontName</code>: the list contains he names of all fonts available on the current system. If an item is selected the corresponding font is used to format the cell of the currently selected cells.
 
* <code>cfiFontName</code>: the list contains he names of all fonts available on the current system. If an item is selected the corresponding font is used to format the cell of the currently selected cells.
 
* <code>cfiFontSize</code>: the list contains the most typical font sizes used in spreadsheets. Selecting an item sets the font size of the currently selected cells accordingly.
 
* <code>cfiFontSize</code>: the list contains the most typical font sizes used in spreadsheets. Selecting an item sets the font size of the currently selected cells accordingly.
 
* <code>cfiFontColor</code>: the list contains all colors of the workbook's palette. The selected color is assigned to the font of the selected cells.
 
* <code>cfiFontColor</code>: the list contains all colors of the workbook's palette. The selected color is assigned to the font of the selected cells.
* <code>cfiBackgroundColor</code>: like <code>cfiFontColor</code> - the selected color is used as background fill color of the selected cells.
+
* <code>cfiBackgroundColor</code>: like <code>cfiFontColor</code> - se utiliza el color seleccionado como color de relleno de fondo de las celdas seleccionadas.
 
   
 
   
 
=== TsSpreadsheetInspector ===
 
=== TsSpreadsheetInspector ===
 +
 
[[file:TSSPREADSHEETINSPECTOR.png]]
 
[[file:TSSPREADSHEETINSPECTOR.png]]
Inherits from TValueListEditor and displays name-value pairs for properties of the workbook, the selected worksheet, and the content and formatting of the active cell. It's main purpose is to help with debugging.
+
Hereda de TValueListEditor y muestra pares nombre-valor (name-value) para propiedades del libro de trabajo, la hoja de trabajo y el contenido y formateado de la celda activa. Su propósito principal es ayudar con el depurado (debugging).

Revision as of 16:34, 14 January 2015

Introducción

FPSpreadsheet es un paquete potente para la lectura y escritura de ficheros spreadsheet (Hoja de cálculo). La intención principal es aportar una plataforma capaz de exportar e importar de forma nativa datos a/desde los más importantes formatos de fichero de hojas de cálculo sin tener que instalar aplicaciones adicionales.

Pronto, como siempre, surge el deseo de utilizar este paquete también para editar el contenido y formato. Para este propósito, la librería contiene un control grid (FPSpreadSheetGrid) dedicado, que nos recuerda las características de una hoja de trabajo (WorkSheet) de las aplicaciones de hojas de cálculo. Junto a un conjunto de opciones de formato, esta demo todavía viene a tener 1400 líneas de código en su unidad de formulario principal. Por lo tanto, se ha diseñado un conjunto de controles visuales que simplifican ampliamente la creación de aplicaciones de hoja de cálculo (SpreadSheets).

La intención de este tutorial es escribir un programa de hoja de cálculo simple en base a estos controles.

Aunque la mayor parte de la estructura interna de la librería FPSpreadsheet está cubierta mediante los controles visuales sigue siendo recomendable tener algún conocimiento de FPSpreadsheet. Por supuesto debería tenerse un conocimiento básico de Lazarus o FPC y sobre como trabajar con el inspector de objetos de Lazarus.

Controles Visuales FPSpreadSheet

FPSpreadsheet expone clases no visuales, tales como TsWorkbook, TsWorksheet etc. Esto mantiene la librería suficientemente generalizada para todo tipo de programas Pascal. Por otro lado, para programamas con Interfaz Gráfica de Usuario (GUI, se necesita algo de infraestructura que relacione los SpreadSheets con los formularios, grids y otros controles.

TsWorkbookSource

TSWORKBOOKSOURCE.png

El corazón de los controles visuales FPSpreadSheet es la clase TsWorkbookSource que aporta un enlace entre los datos no visuales spreadsheet y los controles visuales del formulario. Su propósito es similar al que tiene el componente TDataSource en aplicaciones de base de datos que enlazan las tablas de las bases de datos o consultas (queries) a controles orientados a datos (data-aware).

Todos los controles visuales FPSpreadSheet tienen una propiedad WorkbookSource que los enlaza con la cadena de información aportada por TsWorkbookSource. WorkbookSource mantiene un listado de todos los controles vinculados. Estos controles se llaman internamente "listeners" porque se encuentran en modo escucha de la informa distribuida por WorkbookSource.

El libro de trabajo (WorkBook) y las hojas de trabajo (WorkSheets) que contiene utilizan eventos para notificar a WorkBookSource todos los cambios relevantes: cambios en el contenido de las celdas o su formato, selección de otras celdas, añadir o borrar hojas de trabajo, etc. La información de estos cambios se pasa a través de los controles "listening" y reaccionan a su propio modo especializado a dichos cambios. Si por ejemplo se añade una hoja de trabajo a un libro, entonces el control visual TsWorkbookTabControl crea una nueva solapa para la hoja de trabajo y el grid "TsWorksheetGrid" carga la nueva hoja de trabajo dentro de la grid.

Control TsWorkbookTabControl

TSWORKBOOKTABCONTROL.png

This is a tabcontrol which provides a tab for each worksheet of the current workbook. The tab names are identical with the names of the worksheets. Selecting another tab is communicated to the other visual spreadsheet controls via the WorkbookSource.

TsWorksheetGrid

TSWORKSHEETGRID.png

This is a customized DrawGrid descendant of the LCL and displays cells of the currently selected worksheet. The texts are not stored in the grid (like a StringGrid would do), but are taken from the TsWorksheet data structure. Similarly, the worksheet provides the information of how each cell is formatted. Like any LCL grid it has a bunch of properties and can be tuned for many applications by adapting its Options. The most important one will be described below.

Light bulb  Nota: The TsWorksheetGrid can also be operated without a TsWorkbookSource. For this purpose it provides its own set of methods for reading and writing files.

TsCellEdit

TSCELLEDIT.png

The typical spreadsheet applications provide a line for editing formulas or cell content. This is the purpose of the TsCellEdit. It displays the content of the active cell of the worksheet which is the same as the active cell of the WorksheetGrid. If editing is finished (by pressing Enter, or by selecting another cell in the WorksheetGrid) the new cell value is transferred to the worksheet. Internally, the TsCellEdit is a memo control, i.e. it is able to process multi-line text correctly. Use Ctrl+ Enter to insert a forced line-break.

TsCellIndicator

TSCELLINDICATOR.png

This is a TEdit control which displays the address of the currently selected cell in Excel notation, e.g. 'A1' if the active cell is in the first row and first column (row = 0, column = 0). Conversely, if a valid cell address is entered into this control the corresponding cell becomes active.

TsCellCombobox

TSCELLCOMBOBOX.pngThis combobox can be used to modify various cell properties by selecting values from the dropdown list. The property affected is determined by the CellFormatItem of the combobox:

  • cfiFontName: the list contains he names of all fonts available on the current system. If an item is selected the corresponding font is used to format the cell of the currently selected cells.
  • cfiFontSize: the list contains the most typical font sizes used in spreadsheets. Selecting an item sets the font size of the currently selected cells accordingly.
  • cfiFontColor: the list contains all colors of the workbook's palette. The selected color is assigned to the font of the selected cells.
  • cfiBackgroundColor: like cfiFontColor - se utiliza el color seleccionado como color de relleno de fondo de las celdas seleccionadas.

TsSpreadsheetInspector

TSSPREADSHEETINSPECTOR.png Hereda de TValueListEditor y muestra pares nombre-valor (name-value) para propiedades del libro de trabajo, la hoja de trabajo y el contenido y formateado de la celda activa. Su propósito principal es ayudar con el depurado (debugging).