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"]

     

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值