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方法):

扫描二维码关注公众号,回复: 4549933 查看本文章
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 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/yetugeng/article/details/84836877