一魂奥、認識表格的基本組成
1.工作簿(workbook)
2.表單(worksheet)
3.行(橫著的)松申、列(豎著的)(row,column)
4.單元格(cell)
二、安裝openpyxl庫
pip install openpyxl
三、讀取工作簿
import openpyxl
wb = openpyxl.load_workbook('XXX.xlsx')
四媳维、操作表單
1.打印所有的表單名稱底扳,儲存在列表中
print(wb.sheetnames)
2.遍歷所有表單
for sheet in wb:
print(sheet.title)
3.新建一個表單
wb.create_sheet('mySheet')
4.根據(jù)表單名稱讀取表單
sheet1 = wb.get_sheet_by_name('Sheet1') #不推薦使用
sheet2 = wb['sheet2']
ws = wb.active() #活躍表單
五铸抑、讀取單元格
1.根據(jù)單元格坐標讀取單元格
print(ws['A1'])
2.指定行列讀取單元格
print(ws.cell(row=1, column=2))
3.讀取單元格的屬性
print(ws['A1'].value) #讀取單元格的值
print(ws['A1'].row) #讀取的表格的行數(shù)
print(ws['A1'].column) #讀取的表格的列數(shù)
print(ws['A1'].coordinate) #讀取的表格的行列數(shù)。輸出的值為'A1'
4.遍歷整列
colC = ws['C'] #遍歷C列
for cell in colC:
print(cell.value)
colrange = ws['C:D'] #切片遍歷C-D列
for col in colrange:
for cell in col:
print(cell.value)
5.遍歷整行
row6 = ws[6] #遍歷第6行
for cell in row6:
print(cell.value)
rowrange = ws['2:5'] #切片遍歷2-5行
for row in rowrange:
for cell in row:
print(cell.value)
6.遍歷某個區(qū)間
for row in ws.iter_rows(min_row=5,max_row=34, min_col=1, max_col=5):
for cell in row :
print(cell.value)
7.全表遍歷
table = tuple(ws.columns) #全表遍歷(一列一列的遍歷) ws.rows為一行一行遍歷
for i in table:
for cell in i:
print(cell.value)
8.指定范圍遍歷
cell_range= ws['A1:C3']
for i in cell_range:
for cell in i:
print(cell.coordinate,cell.value)
9.獲取最大行衷模、最大列
ws.max_row
ws.max_column
10.字母與數(shù)字相互轉化
from openpyxl.utils import get_column_letter, column_index_from_string
print(get_column_letter(99)) #輸出結果AU
print(column_index_from_string('DC')) #輸出結果107