今天開始學習用python處理excel表
1、初識
首先認識一下在excel表的基本類型
- 1 工作薄workbook即整個excel文件
- 2 表單worksheet即excel文件中各個sheet表單
- 3 行(row)列(column)單元格(cell)瓜晤,這是基本元素
行號是1,2,3,列號是ABC
不管是python還是VB驱犹,處理excel表時一定要弄清楚處理的對象是什么足画,是怎么樣的屬性和順序,例如行是從上到下遍歷荠医,列是從左到右遍歷
2桑涎、創(chuàng)建表單
對于創(chuàng)建一個新的Excel文檔兼贡,直接進行Workbook類的調(diào)用即可,對于一個已經(jīng)存在的Excel文檔等曼,可以使用openpyxl模塊的load_workbook函數(shù)進行讀取
import openpyxl
wb =openpyxl.load_workbook('ss.xlsx',)
print(wb.sheetnames)
for sheet in wb:
#遍歷表單
print(sheet.title)
#增加sheet表
add_sheet = wb.create_sheet("Mysheet")
print(wb.sheetnames)
運行結(jié)果
['Sheet1']
Sheet1
['Sheet1', 'Mysheet']
可以給wb.create_sheet()加索引凿蒜,
add_sheet = wb.create_sheet("Mysheet",0)
得到
['Sheet1']
Sheet1
['Mysheet', 'Sheet1']
新建成表的位置就變化了
注意,這樣load_workbook沒有改變原表格的內(nèi)容州泊,只是讀取了表格內(nèi)容放在內(nèi)存漂洋,所有原表格沒有變化
但是如果我們將wb另存,則可以看到變化
import openpyxl
wb =openpyxl.load_workbook('ss.xlsx',)
print(wb.sheetnames)
for sheet in wb:
#遍歷表單
print(sheet.title)
#增加sheet表
# add_sheet = wb.create_sheet("Mysheet",0)
for i in range(4):
sheet = wb .create_sheet(str(i))
#另存文件演训,則新文件與源文件不一樣
wb.save('s1.xlsx')
print(wb.sheetnames)
選擇表單
#選擇表單
# sheet3 =wb.get_sheet_by_name('sheet3')
# sheet5 = wb['']
3贝咙、處理單元格
print(ws['A1'].value)
c = ws['B1']
#c.row,c.column,c.value分別表示行數(shù)、列數(shù)窟她、值
print('Row{},Colum{} is {}'.format(c.row,c.column,c.value))
#c.coordinate坐標,可以直接得到行列表示的值
print('cell {} is {}'.format(c.coordinate,c.value))
print(ws.cell(row =1,column=2).value)
借此機會把格式化字符串鞏固一下
各種取單元格礁苗、區(qū)域和遍歷的方式
#取行和列
#取第c列
colc =ws['c']
#注意,索引是從0開始嘁信,行標是從一開始疏叨,所以ws['c'][0]=ws['c1']
print(colc[2].value)
#取序列值
#訪問B到C所有單元格
col_range =ws['B:C']
#訪問2到6行
row_range = ws[2:6]
#遍歷
#循環(huán)先從列開始B——C
for col in col_range:
#然后逐列從上往下取單元格
for cell in col:
print(cell.value)
#先行后單元格
for row in row_range:
for cell in row:
print(cell.value)
對區(qū)域進行處理
#取區(qū)域
#注意用iter_rows()取范圍的方式
for row in ws.iter_rows(min_row=1,max_row=2,max_col=2):
for cell in row:
print(cell)
cell_range = ws['A1:C3']
#區(qū)域內(nèi)的遍歷蚤蔓,先行后列
for rowofcellobjiect in cell_range:
for cellobj in rowofcellobjiect:
print(cellobj)
#最大行最大列
print('{}*{}'.format(ws.max_row,ws.max_column))
#列的表示不僅是A——Z,超過Z之后比較麻煩,所以改為數(shù)字
from openpyxl.utils import get_column_letter,column_index_from_string
#數(shù)字變列
print(get_column_letter(2),get_column_letter(900))
#字母變數(shù)字
print(column_index_from_string("AAH"))
4秀又、寫數(shù)據(jù)
import openpyxl
from openpyxl.utils import get_column_letter
wb = openpyxl.Workbook()
#當前活動頁
sheet = wb.active
print(sheet.title)
sheet.title = 'happy2020'
print(wb.get_sheet_names())
#新建表單
wb.create_sheet(index = 0,title='firstsheet')
wb.create_sheet(index = 1,title='secsheet')
print(wb.get_sheet_names())
#移除表單
wb.remove_sheet(wb.get_sheet_by_name('secsheet'))
print(wb.get_sheet_names())
#保存
wb.save('sss.xlsx')
#寫入單元格
#單元格有點類似字典變量吐辙,根據(jù)key索引
sheet['A1'] ='hello,world'
print(sheet['A1'].value)
ws1 = wb.create_sheet('rangename')
for row in range(1,40):
ws1.append(range(17))
ws2 = wb.create_sheet('List')
rows =[
['number','batch1','batch2'],
[2,4,6],
[3,40,5],
[4,50,33],
]
for row in rows:
ws2.append(row)
ws3 = wb.create_sheet(title='bata')
for row in range(5,30):
for col in range(15,54):
ws3.cell(column=col,row= row,value=get_column_letter(col))
wb.save('sss.xlsx')
5、根據(jù)條件修改單元格數(shù)據(jù)
原表
現(xiàn)在要重新給不同的名字賦值
'zs':15,
'ls':20,
'ww':22,
import openpyxl
changemessage = {
'zs':15,
'ls':20,
'ww':22,
}
wb = openpyxl.load_workbook('name.xlsx')
ws =wb.active
for rowNum in range(2,ws.max_row+1):
name = ws.cell(row= rowNum,column=1).value
if name in changemessage:
ws.cell(row = rowNum,column=2).value = changemessage[name]
#一定要另存尊沸,不要覆蓋原文件
wb.save('name2.xlsx')