[英]How to access cell values in openpyxl
我使用openpyxl
尝试访问范围内的某些单元格值以更改其值。 具体来说,我想将其值更改为每个范围中第一个单元格的值。 例如,在下面的示例中,我们具有合并的单元格范围“ B3:B9”。 我想用第一个单元格(B3)的值填写此范围内的每个单元格。
def fill_in(rows,first_cell,last_cell):
#Take first cell's value
first_value = str(first_cell.value)
#Copy and fill/assign this value into each cell of the range
for cell in rows:
print(cell) ##E.g. (<Cell 'Sheet1'.B3>,)
print(cell.value) ##I get error here: AttributeError: 'tuple' object has no attribute 'value'
cell.value = first_value ##Same error here.
wb2 = load_workbook('Example.xlsx')
sheets = wb2.sheetnames #list of sheetnames
for i,sheet in enumerate(sheets): #for each sheet
ws = wb2[sheets[i]]
range_list = ws.merged_cell_ranges
for _range in range_list:
first_cell = ws[_range.split(':')[0]] #first cell of each range
last_cell = ws[_range.split(':')[1]]
rows = ws[_range] #big set of sets; each cell within each range
fill_in(list(rows),first_cell,last_cell)
供参考, rows
如下所示:
((<Cell 'Sheet1'.B3>,), (<Cell 'Sheet1'.B4>,), (<Cell 'Sheet1'.B5>,), (<Cell 'Sheet1'.B6>,), (<Cell 'Sheet1'.B7>,), (<Cell 'Sheet1'.B8>,), (<Cell 'Sheet1'.B9>,))
如何解决此错误? 在每个范围内,如何成功为每个单元格的值分配第一个单元格的值?
在打印输出中,您具有AttributeError: 'tuple' object ...
(<Cell 'Sheet1'.B3>,)
AttributeError: 'tuple' object ...
,并且单元格的打印方式类似于(<Cell 'Sheet1'.B3>,)
,因此您的实际变量包含一个元组,但是您将其(<Cell 'Sheet1'.B3>,)
细胞。 您需要打开元组的包装才能到达单元变量。
如果您这样做:
for cell, in rows:
...
这是一种拆箱方法,或者:
for tmp in rows:
cell = tmp[0]
是另一个。 顺便说一句,
sheets = wb2.sheetnames #list of sheetnames
for i,sheet in enumerate(sheets): #for each sheet
ws = wb2[sheets[i]]
该部分不是非常pythonic,下面应该做同样的事情...
for sheet in wb2.sheetnames:
ws = wb2[sheet]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.