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

From Lazarus wiki
Jump to navigationJump to search
Line 250: Line 250:
 
Test the program by compiling. Type some text into cells. Select one of them and click the "Bold" toolbutton - voila, the cell is in bold font. Select another cell. Note that the toolbutton is automatically drawn in the down state if the cell has bold font. Repeat with the other buttons.
 
Test the program by compiling. Type some text into cells. Select one of them and click the "Bold" toolbutton - voila, the cell is in bold font. Select another cell. Note that the toolbutton is automatically drawn in the down state if the cell has bold font. Repeat with the other buttons.
  
=== Saving to file ===
+
=== Tiedoston tallentaminen ===
  
After having entered data into the grid you will certainly want to '''save the grid to a spreadsheet file'''. Lazarus provides all the necessary infrastructure for saving available in the standard action <code>TFileSaveAs</code>. This action automatically opens a '''FileDialog''' for entering the file name.  
+
Saatuasi valmiiksi taulukkolaskenta datan niin varmasti haluat tallentaa sen taulukkolaskentatiedostoon.  
 +
Lazarus tarjoaa kaikki tarvittavat toiminnot tallentaa vakiotoiminnalla <code>TFileSaveAs</code>.  
 +
Tämä toiminto avaa automaattisesti '''FileDialog''' tiedostonimen valitsemista varten.
  
Select the <code>TFileSaveAs</code> standard action from the list of standard action classes. Note that it cannot be found in the "FPSpreadsheet" category, but in the "File" group since it is a standard action of the LCL.
+
Valitse <code>TFileSaveAs</code> toiminta listasta vakiotoiminnan luokkista.  
 +
Huomaa, että se ei kuulu "FPSpreadsheet" kategoriaan, mutta kuuluu "File" ryhmään, koska se on LCL:n vakiotoimintaa.
  
 
[[file:sFileFormatsForSaving.png‎|right|400px]]
 
[[file:sFileFormatsForSaving.png‎|right|400px]]
  
At first, let us specify the properties of the FileDialog. Select the property <code>Dialog</code> of the <code>TFileSaveAs</code> action in the object inspector. It is convenient to be able to store the workbook in various file formats; this can be prepared by providing a file format list in the <code>Filter</code> property of the dialog. Paste the following text into this property:
+
Aluksi  määritetään FileDialog:n  ominaisuuksia. Valitse ominaisuus Dialog on TFileSaveAs toiminto oliomuokkaimessa. Se on kätevä tapa tallentamaan taulukkolaskenta eri tiedostomuodoissa;  
 +
anna tiedostomuodot dialogin <code>Filter</code> omaisuuteen.  
 +
Liittämällä seuraava teksti tähän ominaisuuteen:
 +
 
  
 
:<code>Excel XML spreadsheet (*.xlsx)|*.xlsx|Excel 97-2003 spreadsheets (*.xls)|*.xls|Excel 5 spreadsheet (*.xls)|*.xls|Excel 2.1 spreadsheets (*.xls)|*.xls|LibreOffice/OpenOffice spreadsheet (*.ods)|*.ods|Comma-delimited files (*.csv)|*.csv|WikiTable (WikiMedia-Format, *.wikitable_wikimedia)|*.wikitable_wikimedia</code>
 
:<code>Excel XML spreadsheet (*.xlsx)|*.xlsx|Excel 97-2003 spreadsheets (*.xls)|*.xls|Excel 5 spreadsheet (*.xls)|*.xls|Excel 2.1 spreadsheets (*.xls)|*.xls|LibreOffice/OpenOffice spreadsheet (*.ods)|*.ods|Comma-delimited files (*.csv)|*.csv|WikiTable (WikiMedia-Format, *.wikitable_wikimedia)|*.wikitable_wikimedia</code>
  
When you click on the ellipsis button next to <code>Filter</code> the file list appears in a more clearly arranged dialog shown at the right.
+
Kun klikkaat kolmea pistettä <code>Filter</code> ominaisuudessa niin tiedostojen luettelo näkyy selvemmin järjestettynä. Siitä on kuva oikealla.
  
Make one of these file extensions, e.g. xlsx, the default of the file dialog by assigning its list index to the <code>FilterIndex</code> property. The xlsx file is the first format in the filter list. <code>FilterIndex</code>, therefore, must be set to 1.  
+
Valitse näistä yksi tiedostopääte, esim xlsx, oletukseksi. Liittämällä se FilterIndex omaisuuteen.
 +
Xlsx tiedosto on ensimmäinen <code>FilterIndex</code> luettelossa. Siksi se asetetaan ykköseksi.  
  
{{Note|The indexes in the filter list are 1-based, in contrast to the convention of Lazarus and FPC using 0-based indexes.}}
+
{{Note|Indeksit alkaa ykkösestä FilterIndex:ssä, toisin kuin muissa joissa aika usein käytetään nollapohjaisia indeksejä.}}
  
Next, we define what happens after a file name has been selected in the file dialog. For this purpose, the <code>TFileSaveAs</code> action provides the event <code>OnAccept</code>. This is one of the few places where we have to write code in this project... But it is short: We check which file format has been selected in the format list and write the corresponding spreadsheet file by calling the method <code>SaveToSpreadsheetFile</code> of the TWorkbookSource:
+
Seuraavaksi määrittelemme mitä tapahtuu sen jälkeen kun tiedoston nimi on valittu tiedostontallennusikkunassa.  
 +
Tätä tarkoitusta varten, <code>TFileSaveAs</code> toiminta tarjoaa tapahtuman <code>OnAccept</code>. Tämä on yksi niistä harvoista paikoista, joissa täytyy kirjoittaa koodia tässä sovelluksessa ... Mutta koodi on lyhyt:  
 +
Se tarkistaa mikä tiedostomuoto on valittu formaattiluettelosta ja tallentaa vastaavan tiedostomuotoon
 +
kutsumalla menetelmää SaveToSpreadsheetFile :
  
 
<syntaxhighlight>
 
<syntaxhighlight>
Line 296: Line 306:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
We will make the FileSaveAs action available in the toolbar and in the menu:
+
Teemme FileSaveAs toiminnon saatavilla työkalupalkkiin ja valikkoon:
* '''Toolbar''': Add a TToolButton to the first toolbar and drag it to its left edge. Assign the FileSaveAs action to its <code>Action</code> property.
+
* '''Työkalurivi''':Lisää TToolButton ensimmäiseksi työkaluriviin ja vedä se vasempaan reunaan. Määritä FileSaveAs toiminto sen  <code>Action</code> omaisuuteen..
* '''Menu''': The "Save" command is usually in a submenu called "File". Therefore, double click on the TMainMenu, right-click on the "Format" item and insert a new item "before" the current one. Name it "File". Add a submenu to it. Click at the default menu item and assign the FileSaveAs action to its <code>Action</code> property.
+
* '''Valikko''': "Save" komento on yleensä alivalikkossa nimeltä "File". Siksi kaksoisnapsauta TMainMenu, klikkaa hiiren oikealla "Format" kohta ja lisätään uusi kohta "ennen" tämänhetkistä.  
 +
Nimeä se "File". Lisää se alavalikkoon. Klikkaa oletus valikkokohta ja anna FileSaveAs toiminto sen  <code>Action</code> omaisuuteen.
  
 
=== Tiedoston lukeminen ===
 
=== Tiedoston lukeminen ===

Revision as of 21:40, 8 March 2015

Template:MenuTranslate

FPSpreadsheet harjoitus: Tee oma pieni taulukkolaskentasovellus

Johdanto

FPSpreadsheet on tehokas paketti eri taulukkolaskentatiedostojen lukemista ja kirjoittamista varten. Päätarkoitus on tarjota rajapinta, joka pystyy natiiviisti tuomaan ja viemään tärkeimpiä taulukkolaskentaohjelmien tiedostomuotoja ilman että näitä taulukkolaskentasovelluksia on asennettu.

Pian kuitenkin heräsi toive käyttää tätä pakettia myös tiedostojen sisällön muokkaamiseen ja muotoiluun. Tätä varten kirjasto sisältää erityisen taulukon ohjauksen, FPSpreadsheetGrid, joka muistuttaa läheisesti taulukkolaskentaohjelman taulukkoa. FPSpreadsheet:n mukana tuleva esimerkkiohjelma "Spready" näyttää mitä piirteitä on tarjolla. Tosin siinä joukko muotoiluasetuksia,joten tässä demossa on edelleen jopa yli 1400 riviä koodia pääkäännösyksikössä. Tarjolla on joukko visuaalisia komponentteja jotka yksinkertaistavat taulukkolaskentasovelluksen tekemisen.

Tämän ohjeen tarkoituksena olla oppaana miten tehdä yksinkertaisesti taulukkolaskentaohjelma käyttäen näitä komponentteja.

Vaikka suurin osa FPSpreadsheet kirjaston sisäisestä rakenteesta kuuluu visuaalisiin komponentteihin niin on suositeltavaa, että sinulla on jonkin verran tietoa myös koko FPSpreadsheet kirjastosta. Tietenkin pitäisi olla perustiedot Lazaruksesta ja Free Pascal:sta sekä taidot miten työskennellä Lazaruksen komponenttimuokkaimen parissa.

Visuaaliset FPSpreadsheet komponentit

FPSpreadsheet sisältää paljon ei-visuaalisia luokkia, kuten TsWorkbook, TsWorksheet jne. Nämä pitää kirjaston yleiskäyttöisenä kaikenlaisia ​​Pascal ohjelmia varten.


TsWorkbookSource

TSWORKBOOKSOURCE.png Visuaalisten FPSpreadsheet-komponenttien sydän on TsWorkbookSource-komponentti. Tämä tarjoaa yhteyden ei-visuaalisten laskentataulukkotietojen ja lomakkeella olevien visuaalisten komponenttien kanssa. Sen tarkoituksena on olla samanlainen kuin TDataSource komponentti tietokantasovelluksissa joka yhdistää tietokannan taulukoita tai kyselyitä.

Kaikilla visuaalisilla FPSpreadsheet komponenteilla on ominaisuus WorkbookSource joka yhdistää ne tietoketjuun TsWorkbookSource kautta. WorkbookSource ylläpitää luetteloa kaikista siihen liitetyistä komponenteista. Sisäisesti näitä kontrolleja nimitetään "kuuntelijoiksi", koska he kuuntelevat WorkbookSource:n jakaman tiedon.


Workbook ja worksheets käyttävät tapahtumia (events) ilmoittamaan WorkbookSource:lle kaikista merkittävistä muutoksista: muutokset solujen sisällöstä tai muotoilusta, muitten solujen valitseminen, laskentataulukon lisääminen tai poistaminen jne. Tieto näistä muutoksista on vyörytetty "kuuntelu" komponenteille, ja ne reagoivat omalla erikoistuneella tavalla näihin muutoksiin. Jos esimerkiksi uusi taulukko lisätään taulukkolaskentaan niin visuaalinen TsWorkbookTabControl luo uuteen välilehteen uuden laskentataulukon, ja TsWorksheetGrid lataa uuden taulukon.


TsWorkbookTabControl

TSWORKBOOKTABCONTROL.png Tämä on välilehtikomponentti joka tarjoaa välilehden jokaiselle laskentataulukolle taulukkolaskennassa. Välilehtien nimet ovat samat kuin laskentataulukoissa. Valitsemalla toisen välilehden se viestitetään muille visuaalisille taulukkolaskentakomponenteille WorkbookSource-komponentin kautta.


TsWorksheetGrid

TSWORKSHEETGRID.png TsWorksheetGrid on periytetty LCL:n DrawGrid-komponentista ja se näyttää valitut solut laskentataulukossa. Tekstit eivät tallennu kuten StringGrid tekee, mutta ne otetaan TsWorksheet tietorakenteeseen. Samoin worksheet tarjoaa tiedon siitä, miten kukin solu on muotoiltu. Kuten kaikki LCL grid:t se on joukko ominaisuuksia ja voidaan soveltaa moniin sovelluksiin muuttamalla Options kohtaa. Tärkeimmät niistä kerrotaan jäljempänä.

Light bulb  Huomaa: TsWorksheetGrid voidaan käyttää myös ilman TsWorkbookSource-komponenttia. Tätä varten se tarjoaa omat menetelmät tiedoston lukemiseen ja kirjoittamiseen.

TsCellEdit

TSCELLEDIT.png On tyypillistä että taulukkolaskentaohjelmat on varustettu tekstikentällä jossa voi muokata laskukaavaa ja solun sisältöä. Tähän tarkoitukseen on TsCellEdit. Se näyttää laskentataulukon aktiivisen solun sisällön , joka on sama kuin WorksheetGrid:n aktiivinen solu. Kun muokkaus on valmis (painamalla Enter,tai valitsemalla toinen solu WorksheetGrid:ssa) uuden solun arvo siirretään taulukkoon. Sisäisesti TsCellEdit on Memo-tyylinen , eli se pystyy käsittelemään monirivistä tekstiä oikein. Paina näppäimistöltä Ctrl+ Enter jos haluat lisätä pakollisen rivinsiirron.

TsCellIndicator

TSCELLINDICATOR.png Tämä on TEdit tyylinen komponentti, joka näyttää valitun solun osoitteen Excel notaatiolla, esimerkiksi "A1", jos aktiivinen solu on ensimmäisessä rivissä ja ensimmäisessä sarakkeessa (rivi = 0, sarake = 0). Toisaalta, jos tähän annetaan voimassa oleva solun osoite niin vastaava solu aktivoituu.


TsCellCombobox

TSCELLCOMBOBOX.pngTällä ComboBox-tyylisellä komponentilla muokataan solujen ominaisuuksia valitsemalla arvot pudotusvalikosta. Se millaisia piirteitä valitaan määräytyy CellFormatItem ominaisuuden mukaan:

  • cfiFontName: luettelo sisältää nykyiseen järjestelmään saatavilla olevien kirjaisimien (fonttien) nimet. Jos fontti valitaan niin vastaava fonttia käytetään valituissa soluissa.
  • cfiFontSize: luettelo sisältää tyypillisimmät kirjasinkoot joita käytetään taulukkolaskentaohjelmassa. Kohteen valitseminen muuttaa fontin koon valituissa soluissa vastaamaan fontin kokoa.
  • cfiFontColor: luettelo sisältää workbook:n paletin kaikki värit.

Valittu väri on tulee käyttöön kaikissa valituissa soluissa.

  • cfiBackgroundColor: kuten cfiFontColor - valittua väriä käytetään taustavärinä valituissa soluissa.

TsSpreadsheetInspector

TSSPREADSHEETINSPECTOR.png Periytetty TValueListEditor ja näyttää ominaisuuksien nimi-arvo-pareja workbook:ssa , valitun taulukon, ja sisältöä sekä aktiivisen solun muotoilua . Sen päätarkoitus on auttaa virheenkorjauksessa.

Tee taulukkolaskentaohjelma

Siinä oli tarpeeksi teoriaa joten voimme aloittaa. Tehdään pieni taulukkolaskentaohjelma. Ei se ole niin täydellinen taulukkolaskentaohjelma mitä toimisto-ohjelmissa kuten Excel tai Open/LibreOffice on, mutta siinä on tärkeimmät ominaisuudet mitä FPSpreadsheet-kirjastossa on. Ja se käyttää FPSpreadsheet komponentteja jolla saavutetaan vähäinen kirjoitettavan koodin määrä.

Esivalmistelut

fpspreadsheetcontrols preparations.png

Luo uusi projekti ja tallenna se mieleiseen kansioon.


Koska Office-sovellukset on valikko ja työkalurivi, lisää TMainMenu ja TToolbar komponentti lomakkeelle (form). (Voit jopa tehdä samantapaisen ribbon käyttöliittymän uusien Microsoft-sovellusten tapaan lisäämällä TSpkToolbar lomakkeelle, joka löytyy Lazarus Code and Components Repository, mutta ole tietoinen siitä, että tämä ei vielä tarjoa kaikkia vakiotyökalurivin ominaisuuksia).

In fact, we will be needing another toolbar for the formula edit line. As you will see later, it will be resizable; as size control add a TSplitter to the form and top-align it such that it is positioned underneath the two toolbars. In order to keep a minimum size of the toolbar you should establish constraints: Look at the current height of the toolbar and enter this number into the MinHeight field of the Constraints property of the toolbar. To separate the formula toolbar from the rest of the main form, activate the option ebBottom of the EdgeBorders property of the second toolbar.

Koska valikko ja työkalurivit on käsittelevät samoja käyttäjän toimintoja on hyödyllistä lisätä TActionList komponentti yhdistämään kaikki toiminnot. Liittämällä siihen valikon kohteet ja toolbuttons niin molemmat reagoivat käyttäjän vuorovaikutusta samalla tavalla ilman ylimääräisiä koodausta. Lisäksi: FPSpreadsheet:n visuaalinen komponenttipaketti sisältää koko joukon taulukkolaskennan vakiotoimintoja valmiina käytettäväksi.

Täydellinen sovellus sisältää paljon kuvakkeita Työkalurivillä. Siksi käytämme TImageList komponenttia, johon on linkitetty Images ominaisuus TMainMenu, TToolbars ja TActionList komponenteissa. Mistä kuvakkeet? Voit katsoa Lazaruksen asennuksen images kansiota josta löytyy standardit kuvakkeet lataamiseen ja tallentamiseen jne. Nämä ovat osajoukko famfamfam SILK kuvakekirjastosta. Toinen laaja kuvakekirjasto on Fugue kuvakekokoelma. Molemmat kokoelmat ovat lisensoidaan "Creative commons" lisenssillä ja ovat vapaasti jopa kaupalliseen käyttöön, edellyttäen että asianmukaiset viitteet laitetaan luotuun ohjelmaan. Kun valitset kuvakkeita ota mieluummin png kuvana, ja varmista, että käytät aina samankokoisia kuvakkeita, yleensä 16x16 pikseliä on sopiva koko.

Setting up the visual workbook

TsWorkbookSource

Kuten edellä mainittiin niin johdanto-osan TsWorkbookSource komponentti on rajapinta työkirjan ja valvonnan käyttöliittymä. Tämä komponentti lisätään lomakkeelle ja sille annetaan kunnon nimi (Tällä kertaa pidämme kuitenkin oletusnimen sWorkbookSource1).Kuten pian huomaataan, tätä komponenttia osoitetaan kaikkien FPSpreadsheet_visual paketin komponenttien omaisuudessa WorkbookSource.


WorkbookSource vastaa tietojen lataamisesta ja kirjoittamisesta tiedostoon sekä työkirjan kommunikaatiosta. Siksi sillä on joukko vaihtoehtoja, jotka välitetään työkirjaan ja ohjaa näitä prosesseja:


type
  TsWorkbookOption = (boVirtualMode, boBufStream, boAutoCalc, boCalcBeforeSaving, boReadFormulas);
  TsWorkbookOptions = set of TsWorkbookOption;
sTabControl.png

Tärkeimmät ovat:

  • boAutoCalc: aktivoi automaattisen laskennan kaavoissa aina kun solun sisältö muuttuu.
  • boCalcBeforeSaving: laskee kaavat ennen kuin työkirja tallennetaan tiedostoon
  • boReadFormulas: jos on asetettu niin kaavat luetaan tiedoston, muuten vain kaavojen tulokset.
  • boBufStream ja boVirtualMode: Muissa kuin visuaalisissa ohjelmissa, nämä vaihtoehdot voivat auttaa, jos muisti on loppumassa kun kyseessä on todella suuria työkirjoja. boVirtualMode, ei ole käyttökelpoinen visuaalisissa sovelluksissa, koska vältytään pitämään tietoja laskentataulukon soluissa. Katso myös FPSpreadsheet#Virtual_mode.

Tässä opetusohjelmassa, oletetaan, että vaihtoehtot boAutoCalc ja boReadFormulas valitaan.

TsWorkbookTabControl

The first visual control used in the form is a TsWorkbookTabControl - click it onto the form (into the space not occupied by the toolbar). Client-align it within the form, this shows the TabControl as a bright rectangle only. Now link its WorkbookSource property to the TsWorkbookSource component that we have added just before. Now the TabControl shows a tab labelled "Sheet1". This is because the TsWorkbookSource has created a dummy workkbook containing a single worksheet "Sheet1". The WorkbookSource synchronizes this internal workbook with the TabControl (and the other visual controls to come) such that it displays this worksheet as a tab.

In Excel the worksheet tabs are at the bottom of the form - to achieve this effect you can set the property TabPosition of the TabControl to tpBottom; there are some painting issues of the LCL with this TabPosition, though, therefore, I prefer the default setting, tpTop.

The screenshot shows how far we've got.

TsWorksheetGrid

sWorksheetGrid.png

Now we add a TsWorksheetGrid control. Click it somewhere into the space occupied by the TabControl such that it becomes a child a of the TabControl. You see a standard stringgrid-like component. Link its WorkbookSource property to the source added at the beginning, and the grid looks more like a spreadsheet: there are the column headers labelled by letters "A", "B", etc, and the row headers labelled by numbers "1", "2", etc; the active cell, A1, is marked by a thick border.

You may want to switch the grid's TitleStyle to tsNative in order to achieve themed painting of the row and column headers. And here is a good place to adapt the grid's Options in order to activate many features well-known to spreadsheets:

  • goEditing must be active, otherwise the grid contents cannot be modified.
  • goAlwaysShowEditor should be off because it interferes with the editing convention of spreadsheet applications.
  • goColSizing enables changing of the column width by dragging the dividing line between adjacent column headers. Dragging occurs with the left mouse button pressed.
  • goRowSizing does the same with the row heights.
  • goDblAutoResize activates the feature that optimum column width can be set by double-clicking in the header on its dividing line to the next column. The "optimum" column width is such that no cell content is truncated and no extra space is shown in the column.
  • goHeaderHotTack gives visual feedback if the mouse is above a header cell.
  • goRangeSelect (which is on by default) enables selection of a rectangular range of cells by dragging the mouse between cells at opposite corners of the rectangle. If you have Lazarus trunk you can even select multiple rectangles by holding the CTRL key down before the next rectangle is dragged - in the release version of Lazarus (1.2.6 at the time of this writing) only a single range can be selected.
  • goThumbTracking activates immediate scrolling of the worksheet if one of the scrollbars is dragged with the mouse. The Office applications usually scroll by lines; you can achieve this by turning off goSmoothScroll.

In addition to these Options inherited from TCustomGrid there are some more properties specialized for spreadsheet operation:

  • ShowGridLines, if false, hides the row and column grid lines.
  • ShowHeaders can be set to false if the the column and row headers are to be hidden. (The same can be achieved also by the deprecated property DisplayFixedColRow).
  • The LCL grids normally truncate text at the cell border if it is longer than the cell width. If TextOverflow is set to true then text can overflow into adjacent empty cells.

The properties AutoCalc and ReadFormulas are meant for stand-alone usage of the WorksheetGrid (i.e. without a TsWorkbookSource). Please use the corresponding options of the WorkbookSource instead. (AutoCalc enables automatic calculation of formulas whenever cell content changes. ReadFormulas activates reading of formulas from files, otherwise the grid would display only the formula results).

Editing of values and formulas, Navigating

When you compile and run the program you'll already be able to enter data into the grid. Just select the cell that you want to edit by clicking or using the arrow keys - the active cell is highlighted by a thick border. Then begin typing. When finished select another cell or press the Enter key. Using Enter automatically selects the next cell in the grid. The grid's property AutoAdvance defines what is understood as being the "next cell": by default, Enter moves the active cell down (aaDown), but you can also move it to the right (aaRight), or turn this feature off (aaNone) - see the type TAutoAdvance defined in the unit grids.pas for even more options.

If - as assumed above - the WorkbookSource option boAutoCalc is enabled the worksheet automatically supports calculation of formulas. As an example, go to cell A1, and enter the number 10. Then, go to cell A2 and enter the formula =A1+10. The formula is automatically evaluated, and its result, 20, is displayed in cell A2.

When you navigate in the grid you may notice that cell A2 only displays the formula result, it seems that there is no way to modify the formula once it has been entered. No need to worry - press the key F2 or click into the cell a second time to enter enhanced edit mode in which formulas are visible in the cell.

sCellIndicator sCellEdit.png

In order to edit formulas the Office applications offer a dedicated formula editor bar. Of course, fpspreadsheet has this feature, too. It is built into the TsCellEdit component which is set up such as to always show the full content of a cell. You remember the second toolbar from the "Preparations" section? This will house the TsCellEdit. But wait a minute - there's more to consider: Since formulas occasionally may get rather long the control should be capable of managing serval lines. The same with multi-lined text. TsCellEdit can do this since it is inherited from TCustomMemo which is a multi-line control. You also remember that we added a splitter to the form of the second toolbar? This is for height adjustment for the case that we want to use the multi-line feature of the TsCellEdit: just drag the splitter down to show more lines, or drag it upwards to stop at the height of a single line due to the MinHeight constraints that we had assigned to the toolbar.

The TsCellEdit will cover all available space in the second toolbar. Before we add the TsCellEdit we can make life easier if we think about what else will be in the second toolbar. In Excel, there is an indicator which displays the address of the currently active cell. This is the purpose of the TsCellIndicator. Since its height should not change when the toolbar is dragged down we first add a TPanel to the second toolbar; reduce its Width to about 100 pixels, remove its Caption and set its BevelOuter to bvNone.

Add the TsCellIndicator to this panel and align it to the top of the panel. Connect its WorkbookSource to the TsWorkbookSource control on the form, and immediately you'll see the text "A1", the address of the currenly selected cell.

Sometimes it is desirable to change the width of this box at runtime. So, why not add a splitter to the second toolbar? Set its Align property to alLeft. The result is a bit strange: the splitter is at the very left edge of the toolbar, but you'd expect to see it at the right of the panel. This is because the panel is not aligned by default. Set the Align property of the panel to alLeft as well, and drag the splitter to the right of the panel. Now the splitter is at the correct position.

Almost done now... We finally add a TsCellEdit component to the empty space of the toolbar. Client-align it so that it fills the entire rest of the toolbar. As usual, set its WorkbookSource property to the instance of the TsWorkbookSource on the the form.

Compile and run. Play with the program:

  • Enter some dummy data. Navigate in the worksheet. You'll see that the CellIndicator always shows the address of the active cell. The contents of the active cell is displayed in the CellEdit box. The CellIndicator is not just a passive display of the current cell, it can also be edited. Type in the address of a cell which you want to become active, press Enter, and see what happens...
  • Enter a formula. Navigate back into the formula cell - the formula is displayed in the CellEdit and can be changed there readily.
  • Enter multi-lined text - you can enforce a lineending in the CellEdit by holding the Ctrl key down when you press Enter. The cell displays only one line of the text. Drag the horizontal splitter underneath the second toolbar down - the CellEdit shows all lines. Another way to see all lines of the text, is to adjust the cell height. You must have activated the grid Option goRowSizing. Then you can drag the lower dividing line of the row with the multi-line cell down to increase the row height - the missing lines now appear in the cell!

Formatting of cells

In addition to entering data the user usually wants to apply some formatting to the cells in order to enhance or group them. The worksheet grid is set up in such a way that its cells display the formats taken from the workbook. In addition, the visual FPSpreadsheet controls are able to store formatting attributes into the cell. Because of the notification mechanism via the WorkbookSource these formats are returned to the WorksheetGrid for display.

Adding comboboxes for font name, font size, and font color

sCellFontCombobox.png

In this section, we want to provide the possibility to modify the font of the cell texts by selecting its name, size and/or color. The visual FPSpreadsheet provide the flexible TsCellCombobox for this purpose. It has the property CellFormatItem which defines which attribute it controls:

  • cfiFontName: This option populates the combobox with all fonts found in the current system. The selected item is used for the type face in the selected cells.
  • cfiFontSize fills the combobox with the mostly used font sizes (in points). Again, the selected item defines the font size of the selected cells.
  • cfiFontColor adds all pre-defined colors ("palette") of the workbook to the combobox to set the text color of the selected cells. The combobox items consist of a little color box along with the color name. If the ColorRectWidth is set to -1 the color name is dropped.
  • cfiBackgroundColor, the same with the background color of the selected cells.
  • cfiCellBorderColor, the same with the border color of the selected cells - this feature is currently not yet supported.

Add three TsCellComboboxes to the first toolbar and set their CellFormatItem to cfiFontname, cfiFontSize, and cfiFontColor, respectively. Link their WorkbookSource property to the TsWorkbookSource on the form. You may want to increase the width of the font name combobox such that the longest font names are not cut off; the other comboboxes may become narrower. You may also want to turn off the color names of the third combobox by setting its ColorRechtWidth to -1.

That's all to modify fonts. Compile and run. Enter some text and play with these new features of the program.

Using standard actions

sFontStyleAction selected.png

FPSpreadsheet supports a lot of formats that can be applied to cells, such as text alignment, text rotation, text font, or cell borders or background colors. Typical gui applications contain menu commands and/or toolbar buttons which are assigned to each of these properties and allow to set them by a simple mouse click. In addition, the state of these controls often reflects the properties of the active cell. For example, if there is a button for using a bold type-face this button should be drawn as being pressed if the active cell is bold, but as released if it is not. To simplify the coding of these tasks a large number of standard actions has been added to the library.

  • TsWorksheetAddAction: adds an empty worksheet to the workbook. Specify its name in the NameMask property. The NameMask must contain the format specifier %d which is replaced at runtime by a number such that the worksheet name is unique.
  • TsWorksheetDeleteAction: deletes the active worksheet from the workbook after a confirmation dialog. The last worksheet cannot be deleted.
  • TsWorksheetRenameAction: renames the active worksheet.
  • TsCopyAction: Copies the currently selected cells to an internal list ("CellClipboard") from where they can be pasted back into the spreadsheet to another location. The process can occur in a clipboard-manner ("copy"/"cut", then "paste") or in the way of the "copy brush" of the Office applications. The property CopyItem determines whether the entire cell, or only cell values, cell formulas, or cell formats are transferred.
  • TsFontStyleAction: Modifies the font style of the selected cells. The property FontStyle defines whether the action makes the font bold, italic, underlined or striked-out. Normally each font style is handles by its own action. See the example below.
  • TsHorAlignmentAction: Can be used to modify the horizontal alignment of text in the selected cells. Select HorAlignment to define which kind of alignment (left, center, right) is covered by the action. Like with the TsFontStyleAction, several actions should be provided to offer all available alignments. They are grouped in a mutually exclusive way like radiobuttons.
  • TsVertAlignmentAction: Changes the vertical alignment of text in the selected cells: the kind of alignment is defined by the VertAlignment property. Again, these actions work like radiobuttons.
  • TsTextRotationAction: Allows to specify the text orientation in the selected cells as defined by the property TextRotation in a mutially exclusive way.
  • TsWordWrapAction: Activates the word-wrapping feature for the selected cells: if text is longer than the width of the cell (or height, if the text is rotated) then it is wrapped into multiple lines.
  • TsNumberFormatAction: Defines the number format to be used for the selected cells. The format to be used is defined by the properties NumberFormat (such as nfFixed) for built-in formats, and NumberFormatStr for specialized formatting.
  • TsDecimalsAction: Allows to increase or decrease the number of decimal places shown in the selected cells. The property Delta controls whether an increase (+1) or decrease (-1) is wanted.
  • TsCellBorderAction: Allows to specify if a border will be drawn around the selected cells. The subproperties East, West, North, South, InnerHor, InnerVert of Borders define what the border will look like at each side of the cell range. Note that each rectangular range of cells is considere as a single block; the properties East, West, North and South are responsible for the outer borders of the entire block, inner borders are defined by InnerHor and InnerVert. Using these properties, borders can be switched on and off (Visible), and in addition, the line style and line color can be changed.
  • TsMergeAction: If checked, the cells of each selected rectangular range are merge to a single block. Unchecking the action separates the block to individual cells. Note that the block's content and formatting is defined by the top-left cell of each block; content and formats of other cells will be lost.

Adding buttons for "Bold", "Italic", and "Underline"

sFontStyleAction in ActionListEditor.png

If you have never worked with standard actions before here are some detailed step-by-step instructions. Let us stick to above example and provide the possibility to switch the font style of the selected cells to bold. The standard action which is responsible for this feature is the TsFontStyleAction.

  • At first, we add this action to the form: Double-click on the TActionList to open the "ActionList Editor".
  • Click on the down-arrow next to the "+" button, and select the item "New standard action" from the drop-down menu.
  • This opens a dialog with the list of registered "Standard Action Classes".
  • Scroll down until you find a group named "FPSpreadsheet".
  • In this group, select the item "TsFontStyleAction" by double-clicking.
  • Now an item sFontStyleAction1 appears in the ActionList Editor.
  • It should already be selected like in the screenshot at the right. If not, select sFontStyleAction1 in the ActionList Editor to bring it up in the Object Inspector and to set up its properties:
    • Use the text "Bold" for the Caption - this is the text that will be assigned to the corresponding menu item.
    • Similarly, assign "Bold font" to the Hint property.
    • Set the ImageIndex to the index of the icon in the form's ImageList that you want to see in the toolbar.
    • Make sure that the item fssBold is highlighted in the dropdown list of the property FontStyle. If not, select it. Since TsFontStyleAction can handle several font styles (bold, italic, underline, strikeout) we have to tell the action which font style it should be responsible of.
    • Like with the visual controls, don't forget to assign the TsWorkbookSource to the corresponding property WorkbookSource of the action. This activates the communication between the worksheet/workbook on the one hand, and the action and the related controls on the other hand.

Having set up the standard action we add a menu item to the form's MainMenu. Double-click on the TMainMenu of the form to bring up the "Menu Editor". Since the menu is empty so far there is only a dummy item, "New item1". This will become our "Format" menu. Select the item, and type "Format" into the Caption property field. Now the dummy item is re-labelled as "Format". Right-click on this "Format" item, and select "Create submenu" from the popup menu which brings up another new menu item, "New item2". Select it. In the dropdown list of the property Action of the object inspector, pick the sFontStyle1 action - this is the action that we have just set up - and the menu item automatically shows the caption provided by the action component, "Bold".

Finally we add a toolbar button for the "bold" action. Right-click onto the TToolbar, and add a new toolbutton by selecting item "New button" from the popup menu. Go to the property Action in the object inspector again, pick the sFontStyle1 item, and this is enough to give the tool button the ability to set a cell font to bold!

Repeat this procedure with two other buttons. Design them to set the font style to italic and underlined.

Test the program by compiling. Type some text into cells. Select one of them and click the "Bold" toolbutton - voila, the cell is in bold font. Select another cell. Note that the toolbutton is automatically drawn in the down state if the cell has bold font. Repeat with the other buttons.

Tiedoston tallentaminen

Saatuasi valmiiksi taulukkolaskenta datan niin varmasti haluat tallentaa sen taulukkolaskentatiedostoon. Lazarus tarjoaa kaikki tarvittavat toiminnot tallentaa vakiotoiminnalla TFileSaveAs. Tämä toiminto avaa automaattisesti FileDialog tiedostonimen valitsemista varten.

Valitse TFileSaveAs toiminta listasta vakiotoiminnan luokkista. Huomaa, että se ei kuulu "FPSpreadsheet" kategoriaan, mutta kuuluu "File" ryhmään, koska se on LCL:n vakiotoimintaa.

sFileFormatsForSaving.png

Aluksi määritetään FileDialog:n ominaisuuksia. Valitse ominaisuus Dialog on TFileSaveAs toiminto oliomuokkaimessa. Se on kätevä tapa tallentamaan taulukkolaskenta eri tiedostomuodoissa; anna tiedostomuodot dialogin Filter omaisuuteen. Liittämällä seuraava teksti tähän ominaisuuteen:


Excel XML spreadsheet (*.xlsx)|*.xlsx|Excel 97-2003 spreadsheets (*.xls)|*.xls|Excel 5 spreadsheet (*.xls)|*.xls|Excel 2.1 spreadsheets (*.xls)|*.xls|LibreOffice/OpenOffice spreadsheet (*.ods)|*.ods|Comma-delimited files (*.csv)|*.csv|WikiTable (WikiMedia-Format, *.wikitable_wikimedia)|*.wikitable_wikimedia

Kun klikkaat kolmea pistettä Filter ominaisuudessa niin tiedostojen luettelo näkyy selvemmin järjestettynä. Siitä on kuva oikealla.

Valitse näistä yksi tiedostopääte, esim xlsx, oletukseksi. Liittämällä se FilterIndex omaisuuteen. Xlsx tiedosto on ensimmäinen FilterIndex luettelossa. Siksi se asetetaan ykköseksi.

Light bulb  Huomaa: Indeksit alkaa ykkösestä FilterIndex:ssä, toisin kuin muissa joissa aika usein käytetään nollapohjaisia indeksejä.

Seuraavaksi määrittelemme mitä tapahtuu sen jälkeen kun tiedoston nimi on valittu tiedostontallennusikkunassa. Tätä tarkoitusta varten, TFileSaveAs toiminta tarjoaa tapahtuman OnAccept. Tämä on yksi niistä harvoista paikoista, joissa täytyy kirjoittaa koodia tässä sovelluksessa ... Mutta koodi on lyhyt: Se tarkistaa mikä tiedostomuoto on valittu formaattiluettelosta ja tallentaa vastaavan tiedostomuotoon kutsumalla menetelmää SaveToSpreadsheetFile :

uses
  ..., fpspreadsheet, ...;   // for TsSpreadsheetFormat

procedure TForm1.FileSaveAs1Accept(Sender: TObject);
var
  fmt: TsSpreadsheetFormat;
begin
  Screen.Cursor := crHourglass;
  try
    case FileSaveAs1.Dialog.FilterIndex of
      1: fmt := sfOOXML;                // Note: Indexes are 1-based here!
      2: fmt := sfExcel8;
      3: fmt := sfExcel5;
      4: fmt := sfExcel2;
      5: fmt := sfOpenDocument;
      6: fmt := sfCSV;
      7: fmt := sfWikiTable_WikiMedia;
    end;
    sWorkbookSource1.SaveToSpreadsheetFile(FileSaveAs1.Dialog.FileName, fmt);
  finally
    Screen.Cursor := crDefault;
  end;
end;

Teemme FileSaveAs toiminnon saatavilla työkalupalkkiin ja valikkoon:

  • Työkalurivi:Lisää TToolButton ensimmäiseksi työkaluriviin ja vedä se vasempaan reunaan. Määritä FileSaveAs toiminto sen Action omaisuuteen..
  • Valikko: "Save" komento on yleensä alivalikkossa nimeltä "File". Siksi kaksoisnapsauta TMainMenu, klikkaa hiiren oikealla "Format" kohta ja lisätään uusi kohta "ennen" tämänhetkistä.

Nimeä se "File". Lisää se alavalikkoon. Klikkaa oletus valikkokohta ja anna FileSaveAs toiminto sen Action omaisuuteen.

Tiedoston lukeminen

Se mitä on jäljellä on taulukkolaskentatiedoston lukeminen sovellukseen. Tietenkin FPSpreadsheet-kirjasto on hyvin varustautunut tähän toimintoon. Toiminnot ovat hyvin samanlaisia kuin tallentamisessa. Ei käytetä TFileSaveAs vakiotoimintoa, vaan sen sijaan käytetään TFileOpen vakiotoimintoa. Tähänkin vakiotoimintaan on sisäänrakennettu tiedostojen valintaikkuna, jossa asetetaan DefaultExtension (Todennäköisesti valitset ".xls" tai "Xlsx") ja tiedostosuodattimeksi


All spreadsheet files|*.xls;*.xlsx;*.ods;*.csv|All Excel files (*.xls, *.xlsx)|*.xls;*.xlsx|Excel XML spreadsheet (*.xlsx)|*.xlsx|Excel 97-2003 spreadsheets (*.xls)|*.xls|Excel 5 spreadsheet (*.xls)|*.xls|Excel 2.1 spreadsheets (*.xls)|*.xls|LibreOffice/OpenOffice spreadsheet (*.ods)|*.ods|Comma-delimited files (*.csv)|*.csv


(Kopioi tämä merkkijono Dialogin Filter kenttään). Kuten huomataan niin Filter sisältää valintoja, jotka kattavat eri tiedostomuotoja, kuten "Kaikki taulukkolaskenta tiedostot" tai "Kaikki Excel-tiedostot". Tämä on mahdollista, koska TsWorkbookSource komponentissa on ominaisuus AutoDetectFormat joka automaattisesti havaitsee taulukkolaskenta tiedostomuodot. Muissa tapauksissa, kuten "Libre / OpenOffice", voimme määrittää muodon, sfOpenDocument nimenmukaisesti. Oikean tiedostomuodon valinta ja lukeminen tehdään OnAccept tapahtumakäsittelijän toiminnoissa:


{ Loads the spreadsheet file selected by the FileOpen standard action }
procedure TForm1.FileOpen1Accept(Sender: TObject);
begin
  sWorkbookSource1.AutodetectFormat := false;
  case FileOpen1.Dialog.FilterIndex of
    1: sWorkbookSource1.AutoDetectFormat := true;         // All spreadsheet files
    2: sWorkbookSource1.AutoDetectFormat := true;         // All Excel files
    3: sWorkbookSource1.FileFormat := sfOOXML;            // Excel 2007+
    4: sWorkbookSource1.FileFormat := sfExcel8;           // Excel 97-2003
    5: sWorkbookSource1.FileFormat := sfExcel5;           // Excel 5.0
    6: sWorkbookSource1.FileFormat := sfExcel2;           // Excel 2.1
    7: sWorkbookSource1.FileFormat := sfOpenDocument;     // Open/LibreOffice
    8: sWorkbookSource1.FileFormat := sfCSV;              // Text files
  end;
  sWorkbookSource1.FileName :=FileOpen1.Dialog.FileName;  // This loads the file
end;

Jotta nähdään tämä toiminto työkalupalkissa ja valikossa, lisää TToolButton työkaluriviin ja liitä TFileOpenAction sen Action omaisuuteen. Valikossa, lisää uuden kohdan ennen "Tallenna" kohtaa, ja liitä sen Action sen mukaisesti.


Light bulb  Huomaa: Näet taulukkolaskentatiedoston jopa suunnitteluaikana jos annat tiedostonimen TsWorkbookSource Filenames omaisuuteen. Mutta muista, että tiedosto todennäköisesti ei löydy suoritusaikana, jos se on määritetty suhteellisen polun avulla ja jos sovellus ajetaan toisessa tietokoneessa, jossa on eri kansiorakenne!

Yhteenveto

Jos seurasit tätä ohjetta vaihe vaiheelta niin olet ohjelmoinut monimutkaisen graafisen taulukkolaskentaohjelma sovelluksen lähes kirjoittamatta koodirivejä (lukuun ottamatta lataus ja tallennusrutiinit). Jos et, vilkaise examples kansion demoa "fps_ctrls" FPSpreadsheet asennus; siinä tuloksena samanlainen opetusohjelma kuin tämäkin lisättynä joitakin lisäosia.