Spreadsheet Workbench: Difference between revisions

From FreeCAD Documentation
(re-wrote paragraph about spreadsheet usage, omitting misleading screenshots and adding cross-references to other articles)
(Marked this version for translation)
(22 intermediate revisions by 9 users not shown)
Line 3: Line 3:
<!--T:76-->
<!--T:76-->
{{Docnav
{{Docnav
|[[Sketcher Workbench|Sketcher Workbench]]
|[[Sketcher_Workbench|Sketcher Workbench]]
|[[Start Workbench|Start Workbench]]
|[[Start_Workbench|Start Workbench]]
|IconL=Workbench_Sketcher.svg
|IconL=Workbench_Sketcher.svg
|IconR=Workbench_Start.svg
|IconR=Workbench_Start.svg
Line 15: Line 15:


<!--T:6-->
<!--T:6-->
The [[Image:Workbench_Spreadsheet.svg|24px]] [[Spreadsheet Workbench|Spreadsheet Workbench]] allows you to create and edit spreadsheets, use data from the spreadsheet as parameters in a model, fill the spreadsheet with data retrieved from a model, perform calculations, and export the data to other spreadsheet applications such as LibreOffice or Microsoft Excel.
The [[Image:Workbench_Spreadsheet.svg|24px]] [[Spreadsheet_Workbench|Spreadsheet Workbench]] allows you to create and edit spreadsheets, use data from the spreadsheet as parameters in a model, fill the spreadsheet with data retrieved from a model, perform calculations, and export the data to other spreadsheet applications such as LibreOffice or Microsoft Excel.


<!--T:16-->
<!--T:16-->
Line 30: Line 30:


<!--T:85-->
<!--T:85-->
* [[File:Spreadsheet_Import.svg|24px]] [[Spreadsheet_Import|Import]]: import a comma-separated values (CSV) file into a spreadsheet.
* [[File:Spreadsheet_Import.svg|24px]] [[Spreadsheet_Import|Import]]: import a tab-separated values file into a spreadsheet.
* [[File:Spreadsheet_Export.svg|24px]] [[Spreadsheet_Export|Export]]: export a comma-separated values (CSV) file from a spreadsheet.
* [[File:Spreadsheet_Export.svg|24px]] [[Spreadsheet_Export|Export]]: export a tab-separated values file from a spreadsheet.


<!--T:86-->
<!--T:86-->
Line 56: Line 56:
* {{Button|Black}} and {{Button|White}} set the foreground and the background colors of the selected cells.
* {{Button|Black}} and {{Button|White}} set the foreground and the background colors of the selected cells.


== Cell Expressions == <!--T:53-->
<!--T:115-->
* Context-menu of the spreadsheet rows and columns: right-click onto the header of a row or column to insert a new row above or a new column at the left, or to delete the current row/column. You can also select several rows or columns to delete them.</br>{{Version|0.20}} You can also select where the the new rows/columns will be inserted. Furthermore, to insert for example 3 new columns at once, select 3 columns and use the context-menu that will now offer to insert 3 columns.

== Cell properties == <!--T:21-->

<!--T:22-->
The properties of a spreadsheet cell can be edited with a right-click on a cell. The following
dialog pops up:

<!--T:23-->
[[File:SpreadsheetCellPropDialog.png]]

<!--T:24-->
As indicated by the tabs, the following properties can be changed:

<!--T:25-->
* Color: Text color and background color
* Alignment: Text horizontal and vertical alignment
* Style: Text style: bold, italic, underline
* Units: <span id="units_tab"></span>Display units for this cell. Please read the [[#Units|Units]] section below.
* Alias: <span id="alias_name"></span>Define an [[Spreadsheet_SetAlias|alias]] for this cell. This alias can be used in cell formulas and also in general [[Expressions|expressions]]; see section [[#Spreadsheet_data_in_expressions|Spreadsheet data in expressions]] for more information.

== Cell expressions == <!--T:53-->


<!--T:54-->
<!--T:54-->
A spreadsheet cell may contain arbitrary text or an expression.
A spreadsheet cell may contain arbitrary text or an expression. Technically, expressions must start with an equals '=' sign. However, the spreadsheet attempts to be intelligent; if you enter what looks like an expression without the leading '=', one will be added automatically.
Technically, expressions must start with an equals '=' sign.
However, the spreadsheet attempts to be intelligent;
if you enter what looks like an expression without the leading '=',
one will be added automatically.


<!--T:55-->
<!--T:55-->
Cell expressions may contain numbers, functions, references to other cells, and references to properties of the model
Cell expressions may contain numbers, functions, references to other cells, and references to properties of the model (But see [[#Current_limitations|Current limitations]] below). Cells are referenced by their column (CAPITAL letter) and row (number). A cell may also be referenced by its [[#alias_name|alias-name]] (below).
(But see [[#Current_Limitations|Current Limitations]] below).
Cells are referenced by their column (CAPITAL letter) and row (number).
A cell may also be referenced by its [[#alias_name|alias-name]] (below).
Example: B4 + A6
Example: B4 + A6


Line 78: Line 93:


<!--T:63-->
<!--T:63-->
References to objects in the model are explained under [[#References_to_CAD-Data|References to CAD-Data]] below.
References to objects in the model are explained under [[#References_to_CAD-data|References to CAD-data]] below. Using spreadsheet cell values to define model properties are explained under [[#Spreadsheet_data_in_expressions|Spreadsheet data in expressions]] below. For more information on expressions and the available functions, see [[Expressions|Expressions]].
Using spreadsheet cell values to define model properties are explained under [[#Spreadsheet_Data_in_Expressions|Spreadsheet Data in Expressions]] below.
For more specifics on how expressions are formed, see [[Expressions|Expressions]].


== Supported Functions == <!--T:17-->
== Interaction between spreadsheets and the CAD model == <!--T:65-->

<!--T:64-->
Standard trigonometric and other common mathematical functions as well as statistical aggregation functions are supported (see [[Expressions|Expressions]]).

== Interaction between Spreadsheets and the CAD Model == <!--T:65-->


<!--T:66-->
<!--T:66-->
Data in the cells of a spreadsheet may be used in CAD model parameter expressions.
Data in the cells of a spreadsheet may be used in CAD model parameter expressions. Thus, a spreadsheet may be used as the source for parameter values used throughout a model, effectively gathering the values in one place. When values are changed in the spreadsheet, they are propagated throughout the model.
Thus, a spreadsheet may be used as the source for parameter values used throughout a model,
effectively gathering the values in one place.
When values are changed in the spreadsheet, they are propagated throughout the model.


<!--T:67-->
<!--T:67-->
Similarly, properties from CAD model objects may be used in expressions in spreadsheet cells.
Similarly, properties from CAD model objects may be used in expressions in spreadsheet cells. This allows use of object properties like volume or area in the spreadsheet. If the name of an object in the CAD model is changed, the change will automatically be propagated to any references in spreadsheet expressions using the name which was changed.
This allows use of object properties like volume or area in the spreadsheet.
If the name of an object in the CAD model is changed,
the change will automatically be propagated to any references in spreadsheet expressions using the name which was changed.


<!--T:68-->
<!--T:68-->
More than one spreadsheet may be used in a document. A spreadsheet can be identified using either its name or its label.
More than one spreadsheet may be used in a document. A spreadsheet can be identified using either its name or its label.


<!--T:92-->
FreeCAD will automatically assign a unique name to a spreadsheet when it is created. These names follow the pattern {{incode|Spreadsheet}}, {{incode|Spreadsheet001}}, {{incode|Spreadsheet002}} and so on. The name can not be changed manually, and it is not visible in the properties of the spreadsheet. It can be used to refer to the spreadsheet in an [[Expressions|Expression]] (see [[#Spreadsheet Data in Expressions|Spreadsheet Data in Expressions]] below.)
FreeCAD will automatically assign a unique name to a spreadsheet when it is created. These names follow the pattern {{incode|Spreadsheet}}, {{incode|Spreadsheet001}}, {{incode|Spreadsheet002}} and so on. The name can not be changed manually, and it is not visible in the properties of the spreadsheet. It can be used to refer to the spreadsheet in an [[Expressions|Expression]] (see [[#Spreadsheet_data_in_expressions|Spreadsheet data in expressions]] below.)


<!--T:93-->
The label of a spreadsheet is automatically set to the name of the spreadsheet upon creation. Unlike the name, the label can be changed, for example in the properties panel or using the context menu action Rename. Note that the label of a spreadsheet within a document has to be unique; if you try to change the label to a label already used by another spreadsheet, FreeCAD will not accept the new label.
The label of a spreadsheet is automatically set to the name of the spreadsheet upon creation. Unlike the name, the label can be changed, for example in the properties panel or using the context menu action Rename. Note that the label of a spreadsheet within a document has to be unique; if you try to change the label to a label already used by another spreadsheet, FreeCAD will not accept the new label.


<!--T:69-->
<!--T:69-->
FreeCAD checks for cyclic dependencies. See [[Spreadsheet_Workbench#Current_Limitations|Current Limitations]].
FreeCAD checks for cyclic dependencies. See [[Spreadsheet_Workbench#Current_limitations|Current limitations]].


=== Cell Properties === <!--T:21-->
=== References to CAD-data === <!--T:19-->

<!--T:22-->
The properties of a spreadsheet cell can be edited with a right-click on a cell. The following
dialog pops up:

<!--T:23-->
[[File:SpreadsheetCellPropDialog.png]]

<!--T:24-->
As indicated by the tabs, the following properties can be changed:

<!--T:25-->
* Color: Text color and background color
* Alignment: Text horizontal and vertical alignment
* Style: Text style: bold, italic, underline
* Units: <span id="units_tab"></span>Display units for this cell. Please read the [[Spreadsheet_Workbench#Units|Units]] section below.
* Alias: <span id="alias_name"></span>Define an alias-name for this cell. This alias-name can be used in cell formulas and also in general FreeCAD Expressions.
While one may use the row and column number in an expression to reference a cell,
best practice is to give the cell an alias-name and use that.
For example, if the data in cell B1 contained the length parameter for an object,
an alias name of "MyObject_Length" would allow the value to be referred to as "Spreadsheet.MyObject_Length"
instead of "Spreadsheet.B1". {{Version|0.16}}

=== References to CAD-Data === <!--T:19-->


<!--T:20-->
<!--T:20-->
Line 141: Line 121:


<!--T:70-->
<!--T:70-->
Computed expressions in spreadsheet cells start with an equals ('=') sign. However, the spreadsheet entry mechanism attempts to be smart. An expression may be entered without the leading '='; if the string entered is a valid expression, an '=' is automatically added when the final {{KEY|Enter}} is typed. If the string entered is not a valid expression (often the result of entering something with the wrong case, e.g. "MyCube.length" instead of "MyCube.Length"), no leading '=' is added and it is treated as simply a text string.
Computed expressions in spreadsheet cells start with an equals ('=') sign.
However, the spreadsheet entry mechanism attempts to be smart.
An expression may be entered without the leading '=';
if the string entered is a valid expression,
an '=' is automatically added when the final {{KEY|Enter}} is typed.
If the string entered is not a valid expression
(often the result of entering something with the wrong case, e.g. "MyCube.length" instead of "MyCube.Length"),
no leading '=' is added and it is treated as simply a text string.


<!--T:71-->
<!--T:71-->
Line 156: Line 129:


<!--T:72-->
<!--T:72-->
One way to side-step these issues is to prefix text labels corresponding to alias-names with a fixed string,
One way to side-step these issues is to prefix text labels corresponding to alias-names with a fixed string, thereby making them different. Note that "_" will not work, as it is converted to "=". However, a blank, while invisible, will work.
thereby making them different. Note that "_" will not work, as it is converted to "=". However, a blank, while invisible, will work.


<!--T:73-->
<!--T:73-->
Line 187: Line 159:
|}
|}


=== Spreadsheet Data in Expressions === <!--T:37-->
=== Spreadsheet data in expressions === <!--T:37-->


<!--T:94-->
In order to use spreadsheet data in other parts of FreeCAD, you will usually create an [[Expressions|Expression]] that refers to the spreadsheet and the cell that contains the data you want to use. You can identify spreadsheets by name or by label, and you can identify the cells by position or by alias. Autocompletion is available for all forms of referencing.
In order to use spreadsheet data in other parts of FreeCAD, you will usually create an [[Expressions|Expression]] that refers to the spreadsheet and the cell that contains the data you want to use. You can identify spreadsheets by name or by label, and you can identify the cells by position or by alias. Autocompletion is available for all forms of referencing.


<!--T:95-->
{|{{Prettytable}}
{|{{Prettytable}}
!
!
Line 205: Line 179:
|}
|}


<!--T:96-->
<div class="mw-collapsible mw-collapsed">
<div class="mw-collapsible mw-collapsed">
The recommended way to refer to spreadsheet data is to use the spreadsheet label and cell alias name. For a more in-depth explanation of the pros and cons of the addressing modes, see the expanded section below.
The recommended way to refer to spreadsheet data is to use the spreadsheet label and cell alias name. For a more in-depth explanation of the pros and cons of the addressing modes, see the expanded section below.
<div class="mw-collapsible-content">
<div class="mw-collapsible-content">


<!--T:97-->
Using the spreadsheet label has the advantage that it can be freely changed to describe the contents of the spreadsheet. It is also easier to identify the spreadsheet that is being used since the text in the expression matches the label shown in the model and property views. If you decide to change the label of a spreadsheet, existing references to the contents of the spreadsheet will be updated, so you won't break your expressions by renaming the spreadsheet. The internal name of the spreadsheet is not readily available anywhere except within the expression editor, so if you use the internal name and later decide to rename the spreadsheets, you might have a hard time tracing your expression data back to its source.
Using the spreadsheet label has the advantage that it can be freely changed to describe the contents of the spreadsheet. It is also easier to identify the spreadsheet that is being used since the text in the expression matches the label shown in the model and property views. If you decide to change the label of a spreadsheet, existing references to the contents of the spreadsheet will be updated, so you won't break your expressions by renaming the spreadsheet. The internal name of the spreadsheet is not readily available anywhere except within the expression editor, so if you use the internal name and later decide to rename the spreadsheets, you might have a hard time tracing your expression data back to its source.


<!--T:98-->
Be aware that when you create a new spreadsheet, the name and the label are the same, so it is easy to accidentally use the spreadsheet name instead of the label. A simple way to avoid this is to give the spreadsheet a meaningful name before starting to use it in expressions.
Be aware that when you create a new spreadsheet, the name and the label are the same, so it is easy to accidentally use the spreadsheet name instead of the label. A simple way to avoid this is to give the spreadsheet a meaningful name before starting to use it in expressions.


<!--T:99-->
While you may use the row and column number in an expression to reference a cell, best practice is to give the cell an alias name and use that. See [[#Cell Properties|Cell Properties]] above on how to set the alias. For example, if the data in cell B1 contained the length parameter for an object, an alias name of {{incode|MyObject_Length}} would allow the value to be referred to as {{incode|<<MyParams>>.MyObject_Length}} instead of {{incode|Spreadsheet.B1}}. Besides being much easier to read and understand, alias names are also much easier to change if you decide to adjust the structure of your spreadsheet. Using an alias also has the advantage that it is reasier to see which cells are used to control other parts of the document. Note that FreeCAD will automatically adjust the positional references in expressions if you insert or remove rows and columns in the spreadsheet, so even if you use row and column numbers in an expression, you can insert rows and columns without breaking the references to the surrounding cells.
While you may use the row and column number in an expression to reference a cell, best practice is to give the cell an alias name and use that. See [[#Cell Properties|Cell Properties]] above on how to set the alias. For example, if the data in cell B1 contained the length parameter for an object, an alias name of {{incode|MyObject_Length}} would allow the value to be referred to as {{incode|<<MyParams>>.MyObject_Length}} instead of {{incode|Spreadsheet.B1}}. Besides being much easier to read and understand, alias names are also much easier to change if you decide to adjust the structure of your spreadsheet. Using an alias also has the advantage that it is reasier to see which cells are used to control other parts of the document. Note that FreeCAD will automatically adjust the positional references in expressions if you insert or remove rows and columns in the spreadsheet, so even if you use row and column numbers in an expression, you can insert rows and columns without breaking the references to the surrounding cells.


<!--T:101-->
{{Version|0.16}}

</div>
</div>
</div>
</div>


=== Complex models and recomputes === <!--T:110-->
<!--
NOTE: The screenshots in the following text are misleading since they suggest an editable spreadsheet name. Since they are not really specific to editing spreadsheets but rather explain how to use the autocompletion facility, I have omitted them from the re-written paragraph.

The usage of spreadsheet data in other parts of FreeCAD requires a fully defined name. Because it is possible to have
more than one spreadsheet in a document, the spreadsheet name together with the cell name or alias is required.
The following pictures show the usage of an alias "number" from a spreadsheet "MySheet" in an expression
in the PartDesign Workbench.

[[File:Expression usage1.png]]

Typing an "M" shows a list of available names (above).
The arrow-keys allow one to move down to "MySheet" and select it;
{{KEY|Enter}} will cause it to be completed in the expression.
You can also continue typing or click the entry with the mouse.

[[File:Expression usage2.png]]

Typing an "n" now shows the list of available alias names in MySheet starting with "n" (above).
"number" can now be selected as described above.
Once a valid name with usable content is entered,
the result field will show the calculated value; in this case, the length (below).


<!--T:111-->
[[File:Expression usage3.png]]
Editing a spreadsheet will trigger a recompute of the 3D model, even if the changes do not affect the model. For a complex model a recompute can take a long time, and having to wait after every single edit is of course quite annoying.


<!--T:112-->
Further typing, such as adding a "+" sign, will result in an expression which is no longer valid
There are three solutions to deal with this:
which will be indicated.
# Temporarily skip recomputes:
Continuing to complete the expression can again result in a valid expression.
#* In the [[Tree_view|Tree view]] right-click the [[Image:Document.svg|24px]] document that contains the spreadsheet.
-->
#* Select the {{MenuCommand|Skip recomputes}} option from the context menu.
#* There is a big disadvantage to this solution. New values entered in the spreadsheet will not be displayed until the document is recomputed. Instead {{incode|#PENDING}} is shown.
#* You can either recompute manually, using the [[Std_Refresh|Std Refresh]] command, or disable {{MenuCommand|Skip recomputes}} when you are done editing.
# Use a macro to automatically skip recomputes while editing a spreadsheet:
#* Download and run [https://forum.freecadweb.org/viewtopic.php?f=8&t=48600#p419301 skipSheet.FCMacro].
#* This solution saves a few steps compared to the first solution, but also has the mentioned disadvantage.
# Put the spreadsheet in a separate file:
#* You can reference spreadsheet data from an external file with this syntax: {{incode|<nowiki>=NameOfFile#<<MySpreadsheet>>.MyAlias</nowiki>}}.
#* The advantage of having the spreadsheet in another file over switching off recomputes is that the spreadsheet itself does get recomputed.
#* The disadvantage is that the model won't automatically recompute after changes to the spreadsheet.
#* In the scenario where you first open the 'spreadsheet' file, change one or more values and then open the 'model' file, there won't be any indication that the model needs to be recomputed. But if both files are open the [[Std_Refresh|Std Refresh]] icon will update correctly for the 'model' file after changes to the 'spreadsheet' file.


== Units == <!--T:26-->
== Units == <!--T:26-->


<!--T:27-->
<!--T:27-->
The Spreadsheet has a notion of dimension (units) associated with cell values. A number entered without an associated unit has no dimension. The unit should be entered immediately following the number value, with no intervening space. If a number has an associated unit, that unit will be used in all calculations. For example, the multiplication of two lengths with the unit mm gives an area with the unit mm&sup2;.
The Spreadsheet has a notion of dimension (units) associated with cell values.
A number entered without an associated unit has no dimension.
The unit should be entered immediately following the number value, with no intervening space.
If a number has an associated unit, that unit will be used in all calculations.
For example, the multiplication of two lengths with the unit mm gives an area with the unit mm&sup2;.


<!--T:75-->
<!--T:75-->
If a cell contains a value which represents a dimension, it should be entered with its associated unit. While in many simple cases one can get by with a dimensionless value, it is unwise to not enter the unit. If a value representing a dimension is entered without its associated unit, there are some sequences of operations which cause FreeCAD to complain of incompatible units in an expression when it appears the expression should be valid. (This may be better understood by viewing [https://forum.freecadweb.org/viewtopic.php?f=3&t=34713&p=292455#p292438 this thread] in the FreeCAD forums.)
If a cell contains a value which represents a dimension, it should be entered with its associated unit.
While in many simple cases one can get by with a dimensionless value,
it is unwise to not enter the unit.
If a value representing a dimension is entered without its associated unit, there are some sequences of operations which cause FreeCAD to complain of incompatible units in an expression when it appears the expression should be valid.
(This may be better understood by viewing [https://forum.freecadweb.org/viewtopic.php?f=3&t=34713&p=292455#p292438 this thread] in the FreeCAD forums.)


<!--T:28-->
<!--T:28-->
You can change the units displayed for a cell value using the properties dialog [[#units_tab|units tab]] (above).
You can change the units displayed for a cell value using the properties dialog [[#units_tab|units tab]] (above). This does not change the value contained in the cell; it only converts the existing value for display. The value used for calculations does not change, and the results of formulas using the value do not change. For example, a cell containing the value "5.08cm" can be displayed as "2in" by changing the units tab value to "in".
This does not change the value contained in the cell; it only converts the existing value for display.
The value used for calculations does not change,
and the results of formulas using the value do not change.
For example, a cell containing the value "5.08cm" can be displayed as "2in" by changing the units tab value to "in".


<!--T:29-->
<!--T:29-->
A dimensionless number cannot be changed to a number with a unit by the cell properties dialog.
A dimensionless number cannot be changed to a number with a unit by the cell properties dialog. One can put in a unit string, and that string will be displayed; but the cell still contains a dimensionless number. In order to change a dimensionless value to a value with a dimension, the value itself must be re-entered with its associated unit.
One can put in a unit string, and that string will be displayed; but the cell still contains a dimensionless number. In order to change a dimensionless value to a value with a dimension, the value itself must be re-entered with its associated unit.


<!--T:30-->
<!--T:30-->
Line 285: Line 241:


<!--T:46-->
<!--T:46-->
Spreadsheets in Excel-format "xlsx" can be imported via the menu {{MenuCommand|File → Import...}}. Excel-spreadsheets can also be opened by clicking in the menu {{MenuCommand|File → Open...}} or by clicking on the icon [[Image:Document-open.svg|24px]]. In these cases
Spreadsheets in Excel-format "xlsx" can be imported via the menu {{MenuCommand|File → Import...}}. Excel-spreadsheets can also be opened by clicking in the menu {{MenuCommand|File → Open...}} or by clicking on the icon [[Image:Document-open.svg|24px]]. In these cases a new document with a spreadsheet inside is created. The following features are supported:
a new document with a spreadsheet inside is created. The following features are supported:


<!--T:47-->
<!--T:47-->
Line 296: Line 251:
Other functionality is not imported into the FreeCAD spreadsheet. The Excel-import is {{Version|0.17}} of FreeCAD.
Other functionality is not imported into the FreeCAD spreadsheet. The Excel-import is {{Version|0.17}} of FreeCAD.


== Current Limitations == <!--T:31-->
== Printing == <!--T:113-->

<!--T:114-->
To handle the page setup necessary for printing, FreeCAD spreadsheets are printed by inserting them into a [[TechDraw_SpreadsheetView|TechDraw Spreadsheet View]].

== Current limitations == <!--T:31-->


<!--T:43-->
<!--T:43-->
FreeCAD checks for cyclic dependencies. By design, that check stops at the level of the spreadsheet object. As a consequence, you should not have a spreadsheet which contains both cells whose values are used to specify parameters to the model, and cells whose values use output from the model. For example, you cannot have cells specifying the length, width, and height of an object,
FreeCAD checks for cyclic dependencies.
and another cell which references the total volume of the resulting shape. This restriction can be surmounted by having two spreadsheets: one used as a data-source for input parameters to the model and the other used for calculations based on resultant geometry-data.
By design, that check stops at the level of the spreadsheet object.
As a consequence, you should not have a spreadsheet which contains both
cells whose values are used to specify parameters to the model,
and cells whose values use output from the model.
For example, you cannot have cells specifying the length, width, and height of an object,
and another cell which references the total volume of the resulting shape.
This restriction can be surmounted by having two spreadsheets:
one used as a data-source for input parameters to the model
and the other used for calculations based on resultant geometry-data.


<!--T:32-->
<!--T:32-->
When cells are copied, only the content (expression/value) is copied.
When cells are copied, only the content (expression/value) is copied. The [[Spreadsheet_Workbench#Cell_Properties|Cell Properties]] described above are not copied.
The [[Spreadsheet_Workbench#Cell_Properties|Cell Properties]] described above are not copied.


<!--T:13-->
<!--T:13-->
For earlier versions see [[Spreadsheet_legacy|Spreadsheet legacy]].
For earlier versions see [[Spreadsheet_legacy|Spreadsheet legacy]].


== Scripting Basics== <!--T:50-->
== Scripting basics== <!--T:50-->


</translate>
</translate>
{{Code|code=
{{Code|code=
import Spreadsheet
import Spreadsheet
sheet = App.ActiveDocument.addObject("Spreadsheet::Sheet")
sheet = App.ActiveDocument.addObject("Spreadsheet::Sheet","MySpreadsheet")
sheet.Label = "Dimensions"
sheet.Label = "Dimensions"

sheet.set('A1','10mm')
sheet.recompute()
sheet.get('A1')

sheet.setAlias('B1','Diameter')
sheet.set('Diameter','20mm')
sheet.recompute()
sheet.get('Diameter')
}}
}}
<translate>
<translate>



<!--T:14-->
<!--T:14-->
{{Docnav
{{Docnav
|[[Sketcher Workbench|Sketcher Workbench]]
|[[Sketcher_Workbench|Sketcher Workbench]]
|[[Start Workbench|Start Workbench]]
|[[Start_Workbench|Start Workbench]]
|IconL=Workbench_Sketcher.svg
|IconL=Workbench_Sketcher.svg
|IconR=Workbench_Start.svg
|IconR=Workbench_Start.svg

Revision as of 17:13, 6 May 2021

Spreadsheet workbench icon

Introduction

The Spreadsheet Workbench allows you to create and edit spreadsheets, use data from the spreadsheet as parameters in a model, fill the spreadsheet with data retrieved from a model, perform calculations, and export the data to other spreadsheet applications such as LibreOffice or Microsoft Excel.

A spreadsheet with certain cells filled with text and quantities

Tools

  • Import: import a tab-separated values file into a spreadsheet.
  • Export: export a tab-separated values file from a spreadsheet.
  • Align left: align the contents of selected cells to the left.
  • Align center: align the contents of selected cells to the center horizontally.
  • Align right: align the contents of selected cells to the right.
  • Align top: align the contents of selected cells to the top.
  • Align vertical center: align the contents of selected cells to the center vertically.
  • Align bottom: top align the contents of selected cells to the bottom.
  • Black and White set the foreground and the background colors of the selected cells.
  • Context-menu of the spreadsheet rows and columns: right-click onto the header of a row or column to insert a new row above or a new column at the left, or to delete the current row/column. You can also select several rows or columns to delete them.
    introduced in version 0.20 You can also select where the the new rows/columns will be inserted. Furthermore, to insert for example 3 new columns at once, select 3 columns and use the context-menu that will now offer to insert 3 columns.

Cell properties

The properties of a spreadsheet cell can be edited with a right-click on a cell. The following dialog pops up:

As indicated by the tabs, the following properties can be changed:

  • Color: Text color and background color
  • Alignment: Text horizontal and vertical alignment
  • Style: Text style: bold, italic, underline
  • Units: Display units for this cell. Please read the Units section below.
  • Alias: Define an alias for this cell. This alias can be used in cell formulas and also in general expressions; see section Spreadsheet data in expressions for more information.

Cell expressions

A spreadsheet cell may contain arbitrary text or an expression. Technically, expressions must start with an equals '=' sign. However, the spreadsheet attempts to be intelligent; if you enter what looks like an expression without the leading '=', one will be added automatically.

Cell expressions may contain numbers, functions, references to other cells, and references to properties of the model (But see Current limitations below). Cells are referenced by their column (CAPITAL letter) and row (number). A cell may also be referenced by its alias-name (below). Example: B4 + A6

Note: Cell expressions are treated by FreeCAD as programming code. Therefore, when you edit a cell the content you see that it is not following your display settings:

  • the decimal separator is always a dot
  • the number of displayed decimals can differ from your preferences settings

References to objects in the model are explained under References to CAD-data below. Using spreadsheet cell values to define model properties are explained under Spreadsheet data in expressions below. For more information on expressions and the available functions, see Expressions.

Interaction between spreadsheets and the CAD model

Data in the cells of a spreadsheet may be used in CAD model parameter expressions. Thus, a spreadsheet may be used as the source for parameter values used throughout a model, effectively gathering the values in one place. When values are changed in the spreadsheet, they are propagated throughout the model.

Similarly, properties from CAD model objects may be used in expressions in spreadsheet cells. This allows use of object properties like volume or area in the spreadsheet. If the name of an object in the CAD model is changed, the change will automatically be propagated to any references in spreadsheet expressions using the name which was changed.

More than one spreadsheet may be used in a document. A spreadsheet can be identified using either its name or its label.

FreeCAD will automatically assign a unique name to a spreadsheet when it is created. These names follow the pattern Spreadsheet, Spreadsheet001, Spreadsheet002 and so on. The name can not be changed manually, and it is not visible in the properties of the spreadsheet. It can be used to refer to the spreadsheet in an Expression (see Spreadsheet data in expressions below.)

The label of a spreadsheet is automatically set to the name of the spreadsheet upon creation. Unlike the name, the label can be changed, for example in the properties panel or using the context menu action Rename. Note that the label of a spreadsheet within a document has to be unique; if you try to change the label to a label already used by another spreadsheet, FreeCAD will not accept the new label.

FreeCAD checks for cyclic dependencies. See Current limitations.

References to CAD-data

As indicated above, one can reference data from the CAD model in spreadsheet expressions.

Computed expressions in spreadsheet cells start with an equals ('=') sign. However, the spreadsheet entry mechanism attempts to be smart. An expression may be entered without the leading '='; if the string entered is a valid expression, an '=' is automatically added when the final Enter is typed. If the string entered is not a valid expression (often the result of entering something with the wrong case, e.g. "MyCube.length" instead of "MyCube.Length"), no leading '=' is added and it is treated as simply a text string.

Note: The above behavior (auto insert of '=') has some unpleasant ramifications:

  • If you want to keep a column of names corresponding to the alias-names in an adjacent column of values, you must enter the name in the label column before giving the cell in the value column its alias-name. Otherwise, when you enter the alias-name in the label column the spreadsheet will assume it is an expression and change it to "=<alias-name>"; and the displayed text will be the value from the <alias-name> cell.
  • If you make an error when entering the name in the label column and wish to correct it, you cannot simply change it to the alias-name. Instead, you must first change the alias-name to something else, then fix the text name in the label column, then change the alias-name in the value column back to its original.

One way to side-step these issues is to prefix text labels corresponding to alias-names with a fixed string, thereby making them different. Note that "_" will not work, as it is converted to "=". However, a blank, while invisible, will work.

The following table shows some examples assuming the model has a feature named "MyCube":

CAD-Data Cell in Spreadsheet Result
Parametric Length of a Part-Workbench Cube =MyCube.Length Length with units mm
Volume of the Cube =MyCube.Shape.Volume Volume in mm³ without units
Type of the Cube-shape =MyCube.Shape.ShapeType String: Solid
Label of the Cube =MyCube.Label String: MyCube
x-coordinate of center of mass of the Cube =MyCube.Shape.CenterOfMass.x x-coordinate in mm without units

Spreadsheet data in expressions

In order to use spreadsheet data in other parts of FreeCAD, you will usually create an Expression that refers to the spreadsheet and the cell that contains the data you want to use. You can identify spreadsheets by name or by label, and you can identify the cells by position or by alias. Autocompletion is available for all forms of referencing.

Spreadsheet by Name Spreadsheet by Label
Cell by Position =Spreadsheet042.B5 =<<MySpreadsheet>>.B5
Cell by Alias =Spreadsheet042.MyAlias =<<MySpreadsheet>>.MyAlias

The recommended way to refer to spreadsheet data is to use the spreadsheet label and cell alias name. For a more in-depth explanation of the pros and cons of the addressing modes, see the expanded section below.

Using the spreadsheet label has the advantage that it can be freely changed to describe the contents of the spreadsheet. It is also easier to identify the spreadsheet that is being used since the text in the expression matches the label shown in the model and property views. If you decide to change the label of a spreadsheet, existing references to the contents of the spreadsheet will be updated, so you won't break your expressions by renaming the spreadsheet. The internal name of the spreadsheet is not readily available anywhere except within the expression editor, so if you use the internal name and later decide to rename the spreadsheets, you might have a hard time tracing your expression data back to its source.

Be aware that when you create a new spreadsheet, the name and the label are the same, so it is easy to accidentally use the spreadsheet name instead of the label. A simple way to avoid this is to give the spreadsheet a meaningful name before starting to use it in expressions.

While you may use the row and column number in an expression to reference a cell, best practice is to give the cell an alias name and use that. See Cell Properties above on how to set the alias. For example, if the data in cell B1 contained the length parameter for an object, an alias name of MyObject_Length would allow the value to be referred to as <<MyParams>>.MyObject_Length instead of Spreadsheet.B1. Besides being much easier to read and understand, alias names are also much easier to change if you decide to adjust the structure of your spreadsheet. Using an alias also has the advantage that it is reasier to see which cells are used to control other parts of the document. Note that FreeCAD will automatically adjust the positional references in expressions if you insert or remove rows and columns in the spreadsheet, so even if you use row and column numbers in an expression, you can insert rows and columns without breaking the references to the surrounding cells.

Complex models and recomputes

Editing a spreadsheet will trigger a recompute of the 3D model, even if the changes do not affect the model. For a complex model a recompute can take a long time, and having to wait after every single edit is of course quite annoying.

There are three solutions to deal with this:

  1. Temporarily skip recomputes:
    • In the Tree view right-click the document that contains the spreadsheet.
    • Select the Skip recomputes option from the context menu.
    • There is a big disadvantage to this solution. New values entered in the spreadsheet will not be displayed until the document is recomputed. Instead #PENDING is shown.
    • You can either recompute manually, using the Std Refresh command, or disable Skip recomputes when you are done editing.
  2. Use a macro to automatically skip recomputes while editing a spreadsheet:
    • Download and run skipSheet.FCMacro.
    • This solution saves a few steps compared to the first solution, but also has the mentioned disadvantage.
  3. Put the spreadsheet in a separate file:
    • You can reference spreadsheet data from an external file with this syntax: =NameOfFile#<<MySpreadsheet>>.MyAlias.
    • The advantage of having the spreadsheet in another file over switching off recomputes is that the spreadsheet itself does get recomputed.
    • The disadvantage is that the model won't automatically recompute after changes to the spreadsheet.
    • In the scenario where you first open the 'spreadsheet' file, change one or more values and then open the 'model' file, there won't be any indication that the model needs to be recomputed. But if both files are open the Std Refresh icon will update correctly for the 'model' file after changes to the 'spreadsheet' file.

Units

The Spreadsheet has a notion of dimension (units) associated with cell values. A number entered without an associated unit has no dimension. The unit should be entered immediately following the number value, with no intervening space. If a number has an associated unit, that unit will be used in all calculations. For example, the multiplication of two lengths with the unit mm gives an area with the unit mm².

If a cell contains a value which represents a dimension, it should be entered with its associated unit. While in many simple cases one can get by with a dimensionless value, it is unwise to not enter the unit. If a value representing a dimension is entered without its associated unit, there are some sequences of operations which cause FreeCAD to complain of incompatible units in an expression when it appears the expression should be valid. (This may be better understood by viewing this thread in the FreeCAD forums.)

You can change the units displayed for a cell value using the properties dialog units tab (above). This does not change the value contained in the cell; it only converts the existing value for display. The value used for calculations does not change, and the results of formulas using the value do not change. For example, a cell containing the value "5.08cm" can be displayed as "2in" by changing the units tab value to "in".

A dimensionless number cannot be changed to a number with a unit by the cell properties dialog. One can put in a unit string, and that string will be displayed; but the cell still contains a dimensionless number. In order to change a dimensionless value to a value with a dimension, the value itself must be re-entered with its associated unit.

Occasionally it may be desirable to get rid of a dimension in an expression. This can be done by multiplying by 1 with a reciprocal unit.

Importing and exporting

Sheets can be imported and exported to the csv format which can also be read and written by most other spreadsheet applications such as Microsoft Excel or LibreOffice Calc. When importing files into FreeCAD, the delimiter (the character that is used to separate columns) must be the TAB character (this can be set when exporting from other applications). The import of a CSV-file is available from the menu Spreadsheet → Import Spreadsheet or by clicking on the icon . This import function does not open Excel files or any other spreadsheet format.

Spreadsheets in Excel-format "xlsx" can be imported via the menu File → Import.... Excel-spreadsheets can also be opened by clicking in the menu File → Open... or by clicking on the icon . In these cases a new document with a spreadsheet inside is created. The following features are supported:

  • all functions that are also available in the FreeCAD spreadsheet. Other functions give an error in the corresponding cell after the import.
  • Alias names for cells
  • More than one "Sheet" in the Excel-spreadsheet. In this case one FreeCAD spreadsheet is created for each Excel sheet.

Other functionality is not imported into the FreeCAD spreadsheet. The Excel-import is introduced in version 0.17 of FreeCAD.

Printing

To handle the page setup necessary for printing, FreeCAD spreadsheets are printed by inserting them into a TechDraw Spreadsheet View.

Current limitations

FreeCAD checks for cyclic dependencies. By design, that check stops at the level of the spreadsheet object. As a consequence, you should not have a spreadsheet which contains both cells whose values are used to specify parameters to the model, and cells whose values use output from the model. For example, you cannot have cells specifying the length, width, and height of an object, and another cell which references the total volume of the resulting shape. This restriction can be surmounted by having two spreadsheets: one used as a data-source for input parameters to the model and the other used for calculations based on resultant geometry-data.

When cells are copied, only the content (expression/value) is copied. The Cell Properties described above are not copied.

For earlier versions see Spreadsheet legacy.

Scripting basics

import Spreadsheet
sheet = App.ActiveDocument.addObject("Spreadsheet::Sheet","MySpreadsheet")
sheet.Label = "Dimensions"

sheet.set('A1','10mm')
sheet.recompute()
sheet.get('A1')

sheet.setAlias('B1','Diameter')
sheet.set('Diameter','20mm')
sheet.recompute()
sheet.get('Diameter')