python如何與excel結合

2020-08-11 18:01:03

python與excel結合的方法:首先獲取工作表的方法和屬性,並建立或刪除工作表;然後定位單元格並存取;最後使用函數【copy_worksheet】拷貝工作表即可。

python與excel結合的方法:

step1 使用load_workbook(r’xlsx檔案路徑‘)

>>> import openpyxl
>>> wb = openpyxl.load_workbook(r'D:\PycharmProjects\requests\250.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>

相關學習推薦:

step2 獲取工作表的方法和屬性

get_sheet_names()或者sheetnames

>>> wb.get_sheet_names()
['Sheet']
>>> wb.sheetnames
['Sheet']
>>> ws = wb.get_sheet_by_name('Sheet')  # 工作表物件

step3 建立和刪除工作表

create_sheet 建立工作表

remove_sheet 刪除工作表(刪除工作表的物件)

>>> rnx = wb.create_sheet(index = 0,title = 'sheet1')
>>> wb.get_sheet_names()
['sheet1', 'Sheet']
#  注意刪除工作表時,要刪除工作表的物件  ws = wb.get_sheet_by_name('工作表')
>>> wb.remove_sheet(wb.get_sheet_by_name('sheet1'))
>>> wb.sheetnames
['Sheet']

step4 定位單元格

row 行

column 列

coordinate 座標

offset 偏移 offset(行偏移,列偏移)

>>> c = ws['A2']
>>> c.row 
2
>>> c.column
'A'
>>> c.coordinate
'A2'
>>> d = c.offset(2,0)
>>> d.value
'這個殺手不太冷'

step5 ’AA‘是多少

openpyxl.cell.cell.get_column_letter()

openpyxl.cell.cell.column_index_from_string()

>>> openpyxl.cell.cell.get_column_letter(27)
'AA'
>>> openpyxl.cell.cell.column_index_from_string('AA')
27

step6 存取多個單元格

先迭代行再去迭代列

>>> for each_movies in ws['A2':'B10']: # each_movies是一個元祖
    for each_cell in each_movies:
        print(each_cell.value,end = ' ')
    print('\n')
    
肖申克的救贖 9.6 
霸王別姬 9.6 
這個殺手不太冷 9.4 
阿甘正傳 9.4 
美麗人生 9.5 
泰坦尼克號 9.3 
千與千尋 9.3 
辛德勒的名單 9.5 
盜夢空間 9.3
>>> for each_rows in ws.rows:
    print(each_rows[1].value)
    
評分
9.6
9.6
9.4
9.4
....
8.6

還可以指定迭代多少個

>>> for each_row in ws.iter_rows(min_row = 2,min_col = 1,max_row = 4,max_col = 2):
    print(each_row[0].value)
    
肖申克的救贖
霸王別姬
這個殺手不太冷

step7 拷貝工作表

copy_worksheet(工作表)

>>> new = wb.copy_worksheet(ws)
>>> type(new)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> wb.save(r'D:\PycharmProjects\requests\250.xlsx') #注意先把原先開啓的excel檔案關閉再去執行程式碼

相關學習推薦:

以上就是python如何與excel結合的詳細內容,更多請關注php中文網其它相關文章!