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)





>>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
...     for cell in col:
...         print(cell)





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')

 

转载于:https://www.cnblogs.com/CodeUnknown/p/9729480.html

你可能感兴趣的:(openpyxl方法记录)