Excel借助Python連接Workbench,實現Excel輸入參數返回結果(轉載)

來源: ANSYS與ABAQUS

作者: 八誡

現在可以使用非常流行的腳本語言python來實現,Workbench應用程序的項目頁面、工程數據和參數管理器,這一點非常的方便;但同時由于python也適用于Microsoft Excel。因此,如果用python連接Excel和Workbench,憑借著excel幾乎無學習成本的親民性,將極大的簡化和降低使用Workbench的門檻和學習成本。幸運的是,ANSYS幫助文檔中提供了一個很好的例子。現將這個例子搬來,并補充上筆者認為重要,但例子給省略的步驟,分享給大家。

Excel借助Python連接Workbench,實現Excel輸入參數返回結果(轉載)的圖1

你可以打開ansys系統(tǒng)幫助文檔,按上圖,找到例子的具體頁面。這是一個很簡單的例子,一個懸臂梁,但它是一個很好的實現python和Workbench相連的基礎例子。仔細完整的閱讀幫助手冊,并按例子親自做一遍,其中幫助系統(tǒng)省略幾個步驟,下面一一介紹。

1、怎么運行?打開新項目,按下圖加倉ExcelScripting.wbjn文件。此時看到excel文件ParameterExample.xlsx自動啟動。

Excel借助Python連接Workbench,實現Excel輸入參數返回結果(轉載)的圖2

2、怎么使用?ParameterExample.xlsx打開后,可以看到下圖所示界面,只需在這個excel界面里修改懸臂梁的長度和載荷參數,然后點擊頁面右側的UpdateWorkbench更新按鈕。等ansys計算結束,結果自動更新在excel的結果欄內。

Excel借助Python連接Workbench,實現Excel輸入參數返回結果(轉載)的圖3

調試:由于電腦裝過不同的Office版本,在鏈接過程中可能出錯,解決方法是,在注冊表中找到出錯的鍵值,把舊版本的office注冊信息刪掉,然后在控制面板中找到office程序,進行修復,即可解決此類問題。

Excel借助Python連接Workbench,實現Excel輸入參數返回結果(轉載)的圖4

適用范圍:在設計非標設備時,同一模型需要反復計算時,高級分析工程師,可以把計算模型調試好,參數列在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
登錄后免費查看全文
立即登錄
App下載
技術鄰APP
工程師必備
  • 項目客服
  • 培訓客服
  • 平臺客服

TOP

16
2
4