1. <em id="yud1w"><acronym id="yud1w"><u id="yud1w"></u></acronym></em>
      
      
      <button id="yud1w"></button>

      python

      当前位置:首页?>?openpyxl教程?>?当前文章

      openpyxl教程

      openpyxl获取sheet对象的方法

      2020-10-29 90赞 python中国网
      每篇文章努力于解决一个问题!python高级、python面试全套、操作系统经典课等可移步文章底部。

        openpyxl操作excel,excel本身是一个对象,每个sheet也都是一个对象。在创建一个excel的时候默认会产生一个Sheet,如何获取这个默认Sheet对象呢?看官网说明

        A workbook is always created with at least one worksheet. You can get it by using theWorkbook.activeproperty:

      	  ws = wb.active

        openpyxl创建excel后,通过wb.active属性即可返回该sheet对象。

        那么创建多个sheet后如何获取其他sheet对象呢?看官网说明

             Once you gave a worksheet a name, you can get it as a key of the workbook
             You can loop through worksheets

        1、可以通过sheet名字获取指定sheet对象

        2、可以直接循环wb对象依次获取所有sheet对象

        获取sheet对象的代码如下:

      # -*- coding: utf-8 -*-
      from openpyxl import Workbook
      
      wb = Workbook() # 默认生成一个名为Sheet的sheet
      ws = wb.active
      print('默认sheet',ws)
      
      for name in ['a','b']:
          wb.create_sheet(name)
      
      # 获取sheet对象
      for sheet in wb:
          print('sheet:',sheet)
      
      # 通过sheet名获取
      sheet_names = wb.sheetnames
      for sheet_name in sheet_names:
          ws = wb[sheet_name]
          print('ws:',ws)
      
      
      wb.save('test.xlsx')
      
      
      
      D:python3installpython.exe D:/pyscript/py3script/python66/test2/test.py
      默认sheet <Worksheet "Sheet">
      sheet: <Worksheet "Sheet">
      sheet: <Worksheet "a">
      sheet: <Worksheet "b">
      ws: <Worksheet "Sheet">
      ws: <Worksheet "a">
      ws: <Worksheet "b">
      
      Process finished with exit code 0
      
      
      
      

      文章评论

      openpyxl获取sheet对象的方法文章写得不错,值得赞赏
      国产99视频精品免视看6