Spreadsheet Workbench/ru: Difference between revisions

From FreeCAD Documentation
(Created page with "В следующей таблице показаны некоторые примеры, предполагающие, что модель имеет функцию с име...")
(Updating to match new version of source page)
Line 76: Line 76:
Если имя объекта в модели САПР изменяется, изменение автоматически распространяется на все ссылки в выражениях в электронной таблице, использующих изменённое имя.
Если имя объекта в модели САПР изменяется, изменение автоматически распространяется на все ссылки в выражениях в электронной таблице, использующих изменённое имя.


<div class="mw-translate-fuzzy">
В одном документе можно использовать более одной электронной таблицы; электронным таблицам можно давать присвоенное пользователем имя (переименовывать), как и любому другому объекту.
В одном документе можно использовать более одной электронной таблицы; электронным таблицам можно давать присвоенное пользователем имя (переименовывать), как и любому другому объекту.
</div>

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.)

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 проверяет на циклические зависимости. Смотрите в разделе [[#Текущие_ограничения|Текущие ограничения]].
FreeCAD проверяет на циклические зависимости. Смотрите в разделе [[#Текущие_ограничения|Текущие ограничения]].
Line 88: Line 94:
Как указано на вкладках, можно изменить следующие свойства:
Как указано на вкладках, можно изменить следующие свойства:


<div class="mw-translate-fuzzy">
* Цвет: цвет текста и цвет фона.
* Цвет: цвет текста и цвет фона.
* Выравнивание: выравнивание текста по горизонтали и вертикали
* Выравнивание: выравнивание текста по горизонтали и вертикали
Line 95: Line 102:
Хотя можно использовать номер строки и столбца в выражении для ссылки на ячейку, лучше всего дать ячейке псевдоним и использовать его.
Хотя можно использовать номер строки и столбца в выражении для ссылки на ячейку, лучше всего дать ячейке псевдоним и использовать его.
Например, если данные в ячейке B1 содержат параметр длины для объекта, псевдоним «MyObject_Length» позволяет называть значение «Spreadsheet.MyObject_Length» вместо «Spreadsheet.B1». {{Version|0.16}}
Например, если данные в ячейке B1 содержат параметр длины для объекта, псевдоним «MyObject_Length» позволяет называть значение «Spreadsheet.MyObject_Length» вместо «Spreadsheet.B1». {{Version|0.16}}
</div>


===Ссылки на данные САПР===
===Ссылки на данные САПР===
Line 140: Line 148:
===Данные таблицы в выражениях===
===Данные таблицы в выражениях===


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.
Использование данных электронных таблиц в других частях FreeCAD требует полностью определенного имени. Поскольку может быть более одной электронной таблицы в документе, необходимо имя электронной таблицы вместе с именем ячейки или псевдонимом. На следующих рисунках показано использование псевдонима «number» из электронной таблицы «MySheet» в выражении верстака PartDesign.

{|{{Prettytable}}
!
!Spreadsheet by Name
!Spreadsheet by Label
|-
!Cell by Position
|{{incode|<nowiki>=Spreadsheet042.B5</nowiki>}}
|{{incode|<nowiki>=<<MySpreadsheet>>.B5</nowiki>}}
|-
!Cell by Alias
|{{incode|<nowiki>=Spreadsheet042.MyAlias</nowiki>}}
|{{incode|<nowiki>=<<MySpreadsheet>>.MyAlias</nowiki>}}
|}

<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.
<div class="mw-collapsible-content">

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|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.

{{Version|0.16}}

</div>
</div>

<!--
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]]
[[File:Expression usage1.png]]


Typing an "M" shows a list of available names (above).
При вводе буквы «M» отображается список доступных имен (см. выше). Клавиши со стрелками позволяют перелистать к «MySheet» и выбрать его; {{KEY|Enter}} приведет к его завершению в выражении.
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]]
[[File:Expression usage2.png]]


Typing an "n" now shows the list of available alias names in MySheet starting with "n" (above).
При вводе «n» теперь отображается список всех начинающийся с «n» псевдонимов в MySheet (см. выше). Теперь можно выбрать «number», как описано выше.
"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).


[[File:Expression usage3.png]]
[[File:Expression usage3.png]]


Further typing, such as adding a "+" sign, will result in an expression which is no longer valid
Дальнейший ввод, например добавление знака «+», приведёт к выражению, которое больше не действительно, что будет указано.
which will be indicated.
Продолжение для завершения выражения может снова привести к правильному выражению.
Continuing to complete the expression can again result in a valid expression.
-->


==Единицы измерения==
==Единицы измерения==

Revision as of 22:19, 9 November 2020

Spreadsheet workbench icon

Введение

Верстак электронных таблиц позволяет создать и редактировать электронные таблицы, использовать данные из электронной таблицы как параметр в модели, заполнять таблицу данными из модели, выполнять вычисления, и экспортировать данные в другие приложения текстовых таблиц, такие как LibreOffice или Microsoft Excel.

Таблица с определенными ячейками, заполненными текстом и значениями.

Инструменты

  • Create sheet: создать новую электронную таблицу.
  • Импорт: импортировать файл со значениями, разделёнными запятыми (CSV), в электронную таблицу.
  • Экспорт: экспорт файла со значениями, разделёнными запятыми (CSV), из электронной таблицы.
  • Align left: выровнять содержимое выбранных ячеек по левому краю.
  • Align center: выровнять содержимое выбранных ячеек горизонтально по центру.
  • Align right: выровнять содержимое выбранных ячеек по правому краю.
  • Align top: выровнять содержимое выбранных ячеек по верху.
  • Align vertical center: выровнять содержимое выбранных ячеек вертикально по центру.
  • Align bottom: выровнять содержимое выбранных ячеек по низу.
  • Style bold: установить для выбранных ячеек жирный шрифт.
  • Style italic: установить для выбранных ячеек наклонный шрифт.
  • Style underline: установить для выбранных ячеек подчёркнутый шрифт.
  • Set alias: установить псевдоним для выбранных ячеек.
  • Black и White устанавливают цвета переднего и заднего плана выбранных ячеек.

Выражения в ячейках

Ячейка таблицы может содержать любой текст или выражение. Технически, выражение должно начинаться со знака равенства '='. Однако, таблица пытается быть умной, и если Вы введёте нечто, похожее на выражение, но без начального знака '=', он будет добавлен автоматически.

Выражения ячеек могут содержать числа, функции, ссылки на другие ячейки и ссылки на свойства модели. (Но смотрите текущие ограничения ниже). Ссылки на ячейки по их столбцам (ЗАГЛАВНЫЕ буквы) и строкам (числа). На ячейки можно так же ссылаться по их псевдонимам (см. ниже). Пример: B4 + A6

Примечание: Выражения в ячейках обрабатываются FreeCAD как программный код. Поэтому при редактировании ячеек видимое содержимое не следует настройкам дисплея:

  • десятичный разделитель всегда точка
  • число показываемых десятичных чисел может отличаться от настроек

Ссылки на объекты в модели описаны в разделе Ссылки на данные САПР. Использование значений ячеек для определения параметров моделей описано в разделе Данные таблицы в выражениях. Относительно специфики формирования выражений, смотрите Выражения.

Поддерживаемые функции

Поддерживаются стандартные тригонометрические и прочие общие математические функции, плюс функции статистического агрегирования (см. Выражения).

Взаимодействие между электронными таблицами и моделью САПР

Данные в ячейках электронной таблицы могут использоваться в выражениях параметров модели САПР. Таким образом, электронная таблица может использоваться как источник значений параметров, используемых во всей модели, эффективно собирая значения в одном месте. Когда значения изменяются в электронной таблице, они распространяются по всей модели.

Точно так же свойства из объектов модели САПР могут использоваться в выражениях в ячейках электронной таблицы. Это позволяет использовать такие свойства объекта, как объем или площадь в электронной таблице. Если имя объекта в модели САПР изменяется, изменение автоматически распространяется на все ссылки в выражениях в электронной таблице, использующих изменённое имя.

В одном документе можно использовать более одной электронной таблицы; электронным таблицам можно давать присвоенное пользователем имя (переименовывать), как и любому другому объекту.

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 проверяет на циклические зависимости. Смотрите в разделе Текущие ограничения.

Свойства ячейки

Свойства ячейки электронной таблицы можно редактировать, щелкнув ячейку правой кнопкой мыши. Появится следующий диалог:

Как указано на вкладках, можно изменить следующие свойства:

  • Цвет: цвет текста и цвет фона.
  • Выравнивание: выравнивание текста по горизонтали и вертикали
  • Стиль: стиль текста: полужирный, курсив, подчеркивание.
  • Единицы: Отображение единиц измерения для этой ячейки. Прочтите раздел Единицы измерения ниже.
  • Псевдоним: Определение псевдонима для этой ячейки. Этот псевдоним можно использовать в формулах ячеек, а также в общих выражениях FreeCAD.

Хотя можно использовать номер строки и столбца в выражении для ссылки на ячейку, лучше всего дать ячейке псевдоним и использовать его. Например, если данные в ячейке B1 содержат параметр длины для объекта, псевдоним «MyObject_Length» позволяет называть значение «Spreadsheet.MyObject_Length» вместо «Spreadsheet.B1». introduced in version 0.16

Ссылки на данные САПР

Как указано выше, можно ссылаться на данные из модели САПР в выражениях электронной таблицы.

Вычисляемые выражения в ячейках электронной таблицы начинаются со знака равенства ('='). Однако механизм ввода в электронную таблицу пытается быть умным. Выражение можно вводить без символа '=' в начале; если введённая строка является допустимым выражением, при вводе последнего Enter автоматически добавляется '='. Если введённая строка не является допустимым выражением (часто это результат ввода чего-то в неправильном регистре, например, «MyCube.length» вместо «MyCube.Length»), начальный знак «=» не добавляется и рассматривается как просто текстовая строка.

Примечание: Такое поведение (автоматическая вставка '=') имеет некоторые неприятные последствия:

  • Если вы хотите сохранить столбец имен, соответствующий псевдонимам в соседнем столбце значений, вы должны ввести имя в столбце метки перед тем как дать ячейке в колонке значений его псевдоним. В противном случае, при вводе псевдонима в столбце метки, электронная таблица предположит, что это выражение, и изменит его на «= <имя-псевдонима>»; а отображаемый текст станет значением из ячейки <alias-name>.
  • Если вы допустили ошибку при вводе имени в столбце метки и хотите исправить ее, вы не сможете просто изменить ее на псевдоним. Вместо этого вам придётся сначала изменить псевдоним на другой, затем исправить текстовое имя в столбце метки, и лишь потом вернуть псевдоним в столбце значений в исходный вид.

Один из способов обойти эти проблемы - поставить перед текстовыми метками, соответствующими псевдонимам, фиксированную строку, тем самым делая их разными. Обратите внимание, что «_» не будет работать, так как он преобразуется в «=». Однако пробел, хотя и невидим, работать будет.

В следующей таблице показаны некоторые примеры, предполагающие, что модель имеет функцию с именем «MyCube»:

Данные САПР Ячейка в таблице Результат
Параметрическая длинна Куба верстака Part =MyCube.Length Длинна в единицах mm
Объём Cube =MyCube.Shape.Volume Объём в mm³ без указания единиц
Тип формы Cube =MyCube.Shape.ShapeType String: Solid
Метка Cube =MyCube.Label String: MyCube
Координата X центра масс Cube =MyCube.Shape.CenterOfMass.x Координата X в mm без указания единиц

Данные таблицы в выражениях

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.

introduced in version 0.16


Единицы измерения

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.

Импорт и экспорт

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.

Текущие ограничения

FreeCAD проверяет циклические зависимости. По задумке эта проверка останавливается на уровне объекта электронной таблицы. Как следствие, у вас не должно быть электронной таблицы, содержащей как ячейки, значения которых используются для определения параметров модели, так и ячейки, значения которых используют выходные данные модели. Например, у вас не может быть ячеек, определяющих длину, ширину и высоту объекта, и другой ячейки, которая ссылается на общий объем полученной формы. Это ограничение можно преодолеть с помощью двух электронных таблиц: одна используется в качестве источника данных для входных параметров модели, а другая используется для расчётов на основе результирующих геометрических данных.

При копировании ячеек копируется только содержание (выражение/значение). Описанные выше свойства ячейки не копируются.

Насчёт ранних версий смотрите Spreadsheet legacy.

Scripting Basics

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