简体   繁体   中英

Printing value of a cell in openpyxl

I was writing a simple python program using openpyxl and I'm just a beginner trying to learn more about python and it's modules as it's confusing.

I wanted to print the value of a cell and I eventually landed at the doc page

https://openpyxl.readthedocs.io/en/stable/api/openpyxl.cell.cell.html?highlight=value#openpyxl.cell.cell.Cell.value

I would simply like to know what

class openpyxl.cell.cell.Cell(worksheet, row=None, column=None, value=None, style_array=None) 

actually means over here. I know it says openpyxl.cell.cell module at the top but really I find it confusing, does this mean that this is a class in a module in a module or have I got it entirely wrong?

Right now I'm using code like:

import openpyxl as xl
from openpyxl import Workbook
wb = xl.load_workbook('xyz.xlsx')
ws = wb['Sheet1']
print(ws.cell(row=1,column=1).value})

My question is how does the last line even work? Shouldn't I use xl.cell.cell.value instead of ws.cell(row=1,column=1).value ? I'm sorry but I don't understand. Any help would be much appreciated.

Use

import openpyxl 
print( openpyxl.__file__ ) 

to find path to source code (skip __init__.py )

On Linux I have /usr/local/lib/python3.7/dist-packages/openpyxl/ and there is folder cell with file cell.py which has class Cell - and this is your class openpyxl.cell.cell.Cell


There is no

xl.cell.cell.value

but

xl.cell.cell.Cell(...).value

or

mycell = xl.cell.cell.Cell(...) 
mycell.value 

but this creates standalone cell which is not part of workspace so it is useless for you.

When you read file then it creates many Cell() and keep all of them in other class Workspace (maybe as list/dict of cells or array of cells) and Workspace has method cell(row,column) (it is not class Cell , nor module cell ) to give you access to one of Cell() .

So use

ws.cell(row=1,column=1).value

because it gives you access to cells readed from file.

Doc can be useful to see what other functions you can use with ws.cell(row=1,column=1) - ie

mycell = ws.cell(row=1,column=1)

print( mycell.value )
print( mycell.column_letter )
print( mycell.column )
print( mycell.row )
print( mycell.offset(row=1,column=1) )

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