1. 程式人生 > >Python--openpyxl模組新版老版使用對比

Python--openpyxl模組新版老版使用對比

openpyxl模組介紹
  openpyxl模組是一個讀寫Excel文件的Python庫,能同時讀取和修改Excel文件。

openpyxl使用方法更新
  openpyxl 2.4及後續版本對使用方法做了一部分的更新,使用老方法可能會報warning或error。Workbook提供的方法比對如下:

1.get_sheet_names:獲取所有表格的名稱(新版不建議使用,通過Workbook的sheetnames屬性即可獲取)

2.get_sheet_by_name:通過表格名稱獲取Worksheet物件(新版不建議使用,通過Worksheet[‘表名‘]獲取)

3.get_active_sheet:獲取活躍的表格(新版建議通過active屬性獲取)

4.remove_sheet:刪除一個表格(新版不建議使用,通過wb.remove(worksheet) or del wb[sheetname]).)

5.create_sheet:建立一個空的表格

6.copy_worksheet:在Workbook內拷貝表格

7.get_highest_row, get_highest_column:獲取行列的最大值(新版只能通過max_row和max_column兩個方法)

8.get_column_letter, column_index_from_string:行列的字母/數字互轉(新版只能通過openpyxl.utils匯入,而非openpyxl.cell)

9.設定字型方法,老版(有style物件,通過style/styleObj方法):

wb = openpyxl.Workbook()
sheet = wb['Sheet']
italic24Font = Font(size = 24, italic = True)
styleObj = Style(font = italic24Font)
sheet['A'].style/styleObj

新版(沒有style物件,通過style/styleObj方法):

wb = openpyxl.Workbook()
sheet = wb['Sheet']
italic24Font = Font(size = 24, italic = True)
sheet['A1'].font = italic24Font

10.建立圖表,老版:

refObj = openpyxl.charts.Reference(sheet, (1,1), (10, 1))
 
seriesObj = openpyxl.charts.Series(refObj, title = 'First series')
 
chartObj = openpyxl.charts.BarChart()
chartObj.append(seriesObj)
chartObj.drawing.top = 50           # set the position
chartObj.drawing.left = 100
chartObj.drawing.width = 300        # set the size
chartObj.drawing.height = 200
 
sheet.add_chart(chartObj)

新版:

refObj = openpyxl.chart.Reference(sheet, min_row = 1, min_col = 1, max_row = 10, max_col = 1)
 
seriesObj = openpyxl.chart.Series(refObj, title = 'First series')
 
chartObj = openpyxl.chart.BarChart()
chartObj.title = 'My Chart'
chartObj.append(seriesObj)
 
sheet.add_chart(chartObj, 'C5')    #C5表示圖示開始位置

11.獲取表中列(行)。老版:

sheet.columns[1]

新版(拿到的是生成器物件,必須藉助列表或者列字母,得到的型別都是元組):

list(sheet.columns)[2]
sheet["B"]


--------------------- 
作者:brahmsjiang 
來源:CSDN 
原文:https://blog.csdn.net/brahmsjiang/article/details/82947949 
版權宣告:本文為博主原創文章,轉載請附上博文連結!