Python openpyxl模块使用方法更新
上一篇 /
下一篇 2020-12-08 11:45:44
/ 个人分类:Python
openpyxl模块介绍
openpyxl模块是一个读写Excel文档的Python库,能同时读取和修改Excel文档。
openpyxl使用方法更新
openpyxl 2.4及后续版本对使用方法做了一部分的更新,使用老方法可能会报warning或error。Workbook提供的方法比对如下:
- get_sheet_names:获取所有表格的名称(新版不建议使用,通过Workbook的sheetnames属性即可获取)
- get_sheet_by_name:通过表格名称获取Worksheet对象(新版不建议使用,通过Worksheet[‘表名‘]获取)
- get_active_sheet:获取活跃的表格(新版建议通过active属性获取)
- remove_sheet:删除一个表格(新版不建议使用,通过wb.remove(worksheet) or del wb[sheetname]).)
- create_sheet:创建一个空的表格
- copy_worksheet:在Workbook内拷贝表格
- get_highest_row, get_highest_column:获取行列的最大值(新版只能通过max_row和max_column两个方法)
- get_column_letter, column_index_from_string:行列的字母/数字互转(新版只能通过openpyxl.utils导入,而非openpyxl.cell)
- 设定字体方法,老版(有style对象,通过style/styleObj方法):
italic24Font = Font(size =24, italic =True)
styleObj = Style(font = italic24Font)
sheet['A'].style/styleObj
新版(没有style对象,通过style/styleObj方法):
italic24Font = Font(size =24, italic =True)
sheet['A1'].font = italic24Font
创建图表,老版:
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.left =100
chartObj.drawing.width =300
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')
- 获取表中列(行)。老版:
sheet.columns[1]
新版(拿到的是生成器对象,必须借助列表或者列字母,得到的类型都是元组):
收藏
举报
TAG: