简体   繁体   中英

How to write a python function in an excel cell

Thank you so much for your help. For a testing project, I would like to write python functions in Excel spreadsheet directly for easy reference purpose.

This is how I envision the excel structure: the first column to document the function name so that I can use the name in column A to call the function in column B. However, after loading the spreadsheet in python using openpyxl, the function name and code are all strings.

I wonder: (1) is there a way to call the function in a string format or (2) how should I write the function in Excel so that it is easily callable after loading into python.

I also attach the code I am using to eval the statement, but I am getting the following error.

workbook = load_workbook(filename = path)
sheet = workbook.active

dict = {}
for row in sheet.iter_rows(min_row = 2, max_row = 4, min_col = 1, max_col = 2, values_only=True):
    dict[row[0]] = row[1]
    eval(row[0] + "()", dict)
Traceback (most recent call last):

  File "C:..\Test Code.py", line 20, in <module>
    eval(row[0] + "()", dict)

  File "<string>", line 1, in <module>

TypeError: 'str' object is not callable

Thank you so much once again!

Excel 格式

Is there a way to call the function in a string format?

Yes, you can use python's eval function to convert string into code. Converting strings into code is generally a significant security risk, so it should be done with caution.

How should I write the function so that it is easily callable after loading into python?

I don't know specifics but you'll want to make sure the functions are encoded in plain text, so saving your excel as a csv is probably the best way to go. You'll also want to only use spaces or only use tabs for your indents otherwise python will complain.

My Two Cents

I would not recommend this method of writing test code. By writing in Excel you lose all the hints and error catching of an Integrated Development Environment (IDE). You'll also expose your project to a security risk and potential unexpected behavior by converting string to code.

I would suggest you write your test code in python files in a separate directory in your project. Most IDEs ( such as pycharm ) will be handle separate test directories without issues. By writing in python files you'll be able to use a IDE and you'll remove what could be a significant security threat. Also, there are many more resources for writing tests in python rather than excel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM