• python-操作Excel


    一、读取 Excel 表格数据

    1、导入open_workbook

    from xlrd import open_workbook

    2、打开Excel,得到xlrd.Book对象

    book = open_workbook('simple.xlsx')

    3、xlrd.Book对象

    print(sheet.name)  # 获得sheet的名字
    print(sheet.nrows)  # 获得该sheet的行数
    print(sheet.ncols)  # 获得该sheet的列数
    sheet = book.sheets()[0]  # 根据下标,获得sheet对象
    sheet = book.sheet_by_index(0)  # 根据下标,获得sheet对象
    sheet = book.sheet_by_name("工作表1")  # 根据名字,获得sheet对象

    4、循环获取所有sheet对象

    for sheet_index in range(book.nsheets):
        print(book.sheet_by_index(sheet_index))  # 循环获取所有sheet对象
    
    for sheet_name in book.sheet_names():
        print(book.sheet_by_name(sheet_name))  # 循环获取所有sheet对象
    
    for sheet in book.sheets():
        print(sheet)  # 循环获取所有sheet对象

    5、sheet对象

    nrows = sheet.nrows  # 获取sheet的行数
    ncols = sheet.ncols  # 获取sheet的列数
    print(sheet.row_values(1))  # 根据下标获得整行的值,返回一个list
    print(sheet.col_values(1))  # 根据下标获得整列的值,返回一个list
    
    # 循环行,得到所有行的值
    for rownum in range(sheet.nrows):
        print(sheet.row_values(rownum))

    6、根据索引获取单元格的值

    cell_A4 = sheet.cell(0, 4).value
    cell_C4 = sheet.cell(2, 4).value
    cell_A1 = sheet.row(0)[0].value
    cell_B2 = sheet.col(1)[0].value

    二、新建一个 Excel 文件

    1、导入Workbook

    from xlwt import Workbook

    2、新建一个Excel文件

    # 新建一个excel文件
    book = Workbook()

    3、新建一个sheet

    # 新建一个sheet
    sheet = book.add_sheet('sheet name')

    4、在单元格写入数据

    # 写入数据sheet.write(行,列,value)
    sheet.write(0, 0, 'test')

    5、循环在单元格写入数据

    row = 0
    for r in result:
        col = 0
        for i in r:
            sheet.write(row, col, i)
            col = col + 1
        row = row + 1

    6、保存这个Excel文件

    # 保存文件
    book.save('demo.xls')
  • 相关阅读:
    「2021.08 实战」Springboot wagon 2.x 部署线上(自动重启)
    Springboot 使用 CacheManager(缓存是储存到内存中去的,程序结束,缓存也没了)
    [Linux]在CentOS中安装Python3的方法
    [VS2015]关闭_CRT_SECURE_NO_WARNINGS警告
    STL源码剖析-智能指针shared_ptr源码
    透明网桥-消除循环功能
    MPEG-PS封装格式
    RTP timestamp与帧率及时钟频率的关系
    Pyhton @staticmethod
    Python @classmethod
  • 原文地址:https://www.cnblogs.com/lilyo/p/12017027.html
Copyright © 2020-2023  润新知