Python openpyxl模块使用方法更新

上一篇 / 下一篇  2020-12-08 11:45:44 / 个人分类:Python

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方法): 
    1. wb = openpyxl.Workbook()
    2. sheet = wb['Sheet']
    3. italic24Font = Font(size =24, italic =True)
    4. styleObj = Style(font = italic24Font)
    5. sheet['A'].style/styleObj

    新版(没有style对象,通过style/styleObj方法):

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

     

  10. 创建图表,老版:

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

    新版:

    1. refObj = openpyxl.chart.Reference(sheet, min_row =1, min_col =1, max_row =10, max_col =1)
    2. seriesObj = openpyxl.chart.Series(refObj, title ='First series')
    3. chartObj = openpyxl.chart.BarChart()
    4. chartObj.title ='My Chart'
    5. chartObj.append(seriesObj)
    6. sheet.add_chart(chartObj,'C5')#C5表示图标开始位置

     

  11. 获取表中列(行)。老版: 
    sheet.columns[1]

    新版(拿到的是生成器对象,必须借助列表或者列字母,得到的类型都是元组):

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

     


TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-02-22  
    123
45678910
11121314151617
18192021222324
2526272829  

数据统计

  • 访问量: 1804
  • 日志数: 4
  • 建立时间: 2020-11-29
  • 更新时间: 2020-12-08

RSS订阅

Open Toolbar