1. 程式人生 > >openpyxl方法記錄

openpyxl方法記錄

hello title row 使用 style tle import 工作 入庫

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方法記錄