Import displacement over time from Excel through Mechanical scripting

Martin Husek
Martin Husek Member, Employee Posts: 3
First Comment First Anniversary Ansys Employee Photogenic
✭✭✭

Using ACT, how can I import displacement values over time from an Excel spreadsheet to tabular data?

Comments

  • Martin Husek
    Martin Husek Member, Employee Posts: 3
    First Comment First Anniversary Ansys Employee Photogenic
    ✭✭✭
    edited August 2024

    You can use the following code:

    1. import clr
    2. clr.AddReferenceByName('Microsoft.Office.Interop.Excel')
    3. from Microsoft.Office.Interop import Excel
    4. 
    5. # Files
    6. filePath = r'D:\Data.xlsx'
    7. 
    8. # Data in Excel
    9. worksheetName = 'Data'
    10. rows = [2, 52] # without header
    11. columns = ['A','B'] # e.g. time vs displacement
    12. 
    13. # Import displacement over time from the Excel spreadsheet
    14. excel = Excel.ApplicationClass()
    15. excel.Visible = False
    16. excel.ScreenUpdating = False
    17. excel.DisplayAlerts = False
    18. excel.AskToUpdateLinks = False
    19. 
    20. workbook = excel.Workbooks.Open(filePath)
    21. worksheet = workbook.worksheets(worksheetName)
    22. 
    23. values = []
    24. ranges = [c + str(rows[0]) + ':' + c + str(rows[-1]) for c in columns]
    25. for range in ranges:
    26.     temp = []
    27.     column = worksheet.Range[range]
    28.     for cell, row in zip(column, column.Rows):
    29.         temp.append(cell.Value2)
    30.     values.append(temp)
    31. 
    32. excel.Application.Quit()
    33. excel.Quit()
    34. 
    35. # Create a displacement boundary condition
    36. Analysis = ExtAPI.DataModel.Project.Model.Analyses[0]
    37. Displacement = Analysis.AddDisplacement()
    38. Displacement.DefineBy = LoadDefineBy.NormalToOrTangential
    39. 
    40. # Push data from the Excel spreadsheet to tabular data
    41. Displacement.Distance.Inputs[0].DiscreteValues = [Quantity('{}[s]'.format(t)) for t in values[0]]
    42. Displacement.Distance.Output.DiscreteValues = [Quantity('{}[mm]'.format(d)) for d in values[1]]