问题
I have referred to the following links but still cannot get my code to work
Python openpyxl data_only=True returning None
Refresh Excel External Data with Python
Using Python's Openpyxl for an index match
I am tackling my project in small pieces as I am new to python and coding. Ultimately I hope to populate a cell with a random number then use an index match to evaluate a list of text and numbers to identify the text string which corresponds to the random number. So if Item 4 in the spreadsheet was "Hello World!" if the random number was 4 then the program would return "Hello World!"
Conceptually I think I can use the Data_only=True but the problem is the formula is never being evaluated since all the calcs are done in Python and not excel. So it keeps returning the formula and not the value.
I have tried rearranging the below code block. When it works the file simply prints "=index(B4:B72,match(B1,A4:A72,0))" I started trying to use the win32com library to open and close the file but it has not worked so far. But I also receive many errors when I try and manipulate the code to get the intended result. Sometimes if I immediately rerun the code I get an error saying permission is denied to file or that it is read only. I also notice in task manager a ton of Excel processes are launching even though no files actually open.
I was able to get decently far with Openpyxl docs but I find the xlwings docs really hard to grasp so I wanted to post looking for help.
path= "C:\\Users\\Me\\Documents\\Python\\File.xlsx"
xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.workbooks.open(path)
wb.RefreshAll()
wb.save(path)
xlapp.Quit()
myworkbook=load_workbook(path , data_only=True)
worksheet=myworkbook['Sheet1']
#print(myworkbook.sheetnames)
mycell=worksheet['B2']
mycell.value="=index(B4:B72,match(B1,A4:A72,0))"
myworkbook.save(path)
print(mycell.value)
This gives the error pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "We can't save 'File.xlsx' because the file is read-only.\n\nTo keep your changes, you'll need to save the workbook with a new name or in a different location.", 'xlmain11.chm', 0, -2146827284), None)
来源:https://stackoverflow.com/questions/58359177/evaluating-an-index-match-with-openpyxl-and-xlwings-formula-returns-not-value