Excel借助Python连接Workbench,实现Excel输入参数返回结果(转载)

来源: ANSYS与ABAQUS
作者: 八诫
现在可以使用非常流行的脚本语言python来实现,Workbench应用程序的项目页面、工程数据和参数管理器,这一点非常的方便;但同时由于python也适用于Microsoft Excel。因此,如果用python连接Excel和Workbench,凭借着excel几乎无学习成本的亲民性,将极大的简化和降低使用Workbench的门槛和学习成本。幸运的是,ANSYS帮助文档中提供了一个很好的例子。现将这个例子搬来,并补充上笔者认为重要,但例子给省略的步骤,分享给大家。
你可以打开ansys系统帮助文档,按上图,找到例子的具体页面。这是一个很简单的例子,一个悬臂梁,但它是一个很好的实现python和Workbench相连的基础例子。仔细完整的阅读帮助手册,并按例子亲自做一遍,其中帮助系统省略几个步骤,下面一一介绍。
1、怎么运行?打开新项目,按下图加仓ExcelScripting.wbjn文件。此时看到excel文件ParameterExample.xlsx自动启动。
2、怎么使用?ParameterExample.xlsx打开后,可以看到下图所示界面,只需在这个excel界面里修改悬臂梁的长度和载荷参数,然后点击页面右侧的UpdateWorkbench更新按钮。等ansys计算结束,结果自动更新在excel的结果栏内。
调试:由于电脑装过不同的Office版本,在链接过程中可能出错,解决方法是,在注册表中找到出错的键值,把旧版本的office注册信息删掉,然后在控制面板中找到office程序,进行修复,即可解决此类问题。
适用范围:在设计非标设备时,同一模型需要反复计算时,高级分析工程师,可以把计算模型调试好,参数列在excel表中,之后的反复计算工作完全可以交给初级设计人员。从而解放了人员,提高了工作效率。
附件:ExcelScripting.wbjn,其中要把第7行修改为文件所在目录的绝对地址
1# IronPython imports to enable Excel interop
2import clr
3import os
4clr.AddReference("Microsoft.Office.Interop.Excel")
5import Microsoft.Office.Interop.Excel as Excel
6# Define working directory AbsUserPathName(
7workingDir = AbsUserPathName("F:\\ScriptingGuideExamples\\Excel_Parameter_Scripting\\")
8def updateHandler():
9 # Update can take long, so disable the Excel warning -
10 # "Excel is waiting for another application to complete an OLE action"
11 ex.Application.DisplayAlerts = False
12 # Define key ranges in the Workbook
13 lengthCell = worksheet.Range["A3"]
14 loadCell = worksheet.Range["B3"]
15 defCell = worksheet.Range["C3"]
16 # Get the Workbench Parameters
17 lengthParam = Parameters.GetParameter(Name="P1")
18 loadParam = Parameters.GetParameter(Name="P2")
19 defParam = Parameters.GetParameter(Name="P3")
20 # Assign values to the input parameters
21 lengthParam.Expression = lengthCell.Value2.ToString()
22 loadParam.Expression = loadCell.Value2.ToString() + " [N]"
23 # Mark the deformation parameter as updating in the workbook
24 defCell.Value2="Updating..."
25 # Run the project update
26 Update()
27 # Update the workbook value from the WB parameter
28 defCell.Value2 = defParam.Value
29 # restore alert setting
30 ex.Application.DisplayAlerts = True
31# Open the Workbench Project
32Open(FilePath = os.path.join(workingDir, "ExcelParameterScripting.wbpj"))
33# Open Excel and the workbook
34ex = Excel.ApplicationClass()
35ex.Visible = True
36workbook = ex.Workbooks.Open(os.path.join(workingDir , "ParameterExample.xlsx"))
37worksheet=workbook.ActiveSheet
38#Apply the update handler to the workbook button
39OLEbutton = worksheet.OLEObjects("CommandButton1")
40commandButton = OLEbutton.Object
41commandButton.CLICK += updateHandler

工程师必备
- 项目客服
- 培训客服
- 平台客服
TOP
