preface
I use the openpyxl library. When I want to read out a value and put it into a variable, there is an error like the title.
Wrong line
I wanted to read the contents of cell A1 into the value variable, but there was an error in the execution of the code.
value = sheet.cell(1, 1).value
How to Solve:
After Reading some articles, it is found that the parameter dislocation problem is caused by the openpyxl version. The first and second parameters of this version are not row and column. Reading this, I believe there must be a smart little partner who came up with a solution. This paper lists two solutions.
Solution 1:
Set the first parameter to null
value = sheet.cell(None, 1, 1).value
Solution 2:
It’s okay if you don’t want to write None. Just write the assignment to the specified parameter directly in parentheses.
value = sheet.cell(row=1, column=1).value
Summary
The execution effect of these two methods is the same. The first method is to copy an unnecessary variable as empty. The second method is to copy the specified variable without caring about other variables.
Both methods have the same goal, but I prefer the second method, so that we can no longer worry about dislocation and write the position freely, while the first method locks the position of parameter input.
Examples
When using the first method
1. The first line of code below will read the values of the cells in the first line and the second column
2. The second line of code below will read the value of the cell in the first column of the second line
value = sheet.cell(None, 1, 2).value
value = sheet.cell(None, 2, 1).value
When using the second method
1. The execution effect of the following two lines of code is the same. They both get values from the cells in the first row and the second column
value = sheet.cell(column=2, row=1).value
value = sheet.cell(row=1, column=2).value