您的位置: 网站首页> openpyxl教程> 当前文章

openpyxl获取和设置单个单元格的数据

老董2020-04-23198围观,148赞

  openpyxl获取和设置单个单元格的数据,本节课介绍官方文档的2种方法。

  第1种:

  Now we know how to get a worksheet, we can start modifying cells content. Cells can be accessed directly as keys of the worksheet:

	  c = ws['A4']

  This will return the cell at A4, or create one if it does not exist yet. Values can be directly assigned:

	  ws['A4'] = 4

  实际上就是直接用excel单元格的行列来标识单元格即可。我们创建一个excel然后赋值。

# -*- coding: utf-8 -*-

from openpyxl import Workbook


wb = Workbook()
ws = wb.active

ws['A4'] = 4
ws['B1'] = 5

cell = ws['A4']
print(cell.value)

cell = ws['B1']
print(cell.value)

wb.save('test.xlsx')
4
5

  第2种:

  here is also the Worksheet.cell() method.

  This provides access to cells using row and column notation:

	  d = ws.cell(row=4, column=2, value=10)

  也就是sheet对象有一个cell方法,通过传参来指定单元格设置值或获取值。

# -*- coding: utf-8 -*-

from openpyxl import Workbook


wb = Workbook()
ws = wb.active

ws.cell(row=5, column=1, value=6)
ws.cell(row=4, column=2, value=9)

cell = ws['A5']
print(cell.value)

cell = ws.cell(row=4, column=2)
print(cell.value)

wb.save('test.xlsx')
6
9

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    openpyxl获取和设置单个单元格的数据文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200