openpyxl方法记录

Posted codeunknown

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了openpyxl方法记录相关的知识,希望对你有一定的参考价值。

1)引入库
  • import openpyxl #引入整个库,调用对应时使用openpyxl.xxx的形式
  • from openpyxl import Workbook #引入Workbook对象,调用Workbook新建工作簿
  • from openpyxl import load_workbook #引入load_workbook,导入已经建成的工作簿

2)新建工作簿

  • wb = Workbook()
  • wb = openpyxl.Workbook()

3)打开已有工作簿

  • wb = load_workbook(‘sample.xlsx‘)
  • wb = openpyxl.load_workbook(‘sample.xlsx‘)

4)获得sheet控制句柄

  • ws = wb.active #取得活动页
  • ws = wb.create_sheet(‘NewSheet‘) #在已有sheet位置后新建sheet
  • ws = wb.create_sheet(‘NewSheet‘,0) #在已有sheet位置前新建sheet
  • ws = wb[‘OldSheet‘] #获得已有sheet

5)sheet属性

  • ws.title = ‘new title‘ #修改sheet名字
  • ws.sheetnames   #所有sheet名列表  例:print(ws.sheetnames) →  [‘Sheet1‘, ‘New Title‘, ‘Sheet3‘]

6)循环-Sheet

for sheet in wb:
    print(sheet.title)

7)选取Cell

  • c = ws[‘A4‘]
  • ws[‘A4‘] = 8
  • d = ws.cell(row=4, column=2, value=10)
  • cell_range = ws[‘A1‘:‘C2‘]
  • colC = ws[‘C‘]
  • col_range = ws[‘C:D‘]
  • row10 = ws[10]
  • row_range = ws[5:10]
  • ws.rows
  • ws.columns

8)循环-Cell

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
...    for cell in row:
...        print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>
>>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
...     for cell in col:
...         print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.A2>
<Cell Sheet1.B1>
<Cell Sheet1.B2>
<Cell Sheet1.C1>
<Cell Sheet1.C2>

9)数据保存

>>> c.value = hello, world
>>> print(c.value)
hello, world

>>> d.value = 3.14
>>> print(d.value)
3.14
>>> wb = Workbook(guess_types=True)
>>> c.value = 12%
>>> print(c.value)
0.12

>>> import datetime
>>> d.value = datetime.datetime.now()
>>> print d.value
datetime.datetime(2010, 9, 10, 22, 25, 18)

>>> c.value = 31.50
>>> print(c.value)
31.5

A)保存文件

  • wb.save(‘sample.xlsx‘)

 

以上是关于openpyxl方法记录的主要内容,如果未能解决你的问题,请参考以下文章

python3 openpyxl修改Excel的内容

python嵌入式版本安装openpyxl失败解决方法

Python之openpyxl模块的使用

python中openpyxl读取或写信excel文件

❤️小白必看❤️带你避开python大坑❤️在使用openpyxl时,出现ValueError: Unknown engine: openpyxl

Python_testAutoInterface_openpyxl