python控制excel笔记1


title: python控制excel笔记1
date: 2020-05-10 20:39:35
tags: python, 人脸识别


python & excel & openpyxl

使用的库

openpyxl

import openpyxl

作用的对象

文件后缀名为 .xlsx

excel几个操作单元

  • 工作簿 workbook
  • 表单 wooksheet
  • 行、列、单元格 row, column, cell

常见操作

  • 读取文件

    path = '../file/CIBES48配件统计.xlsx'
    wb = openpyxl.load_workbook(path)
    

wb --> wookbook

  • 获取表单

    print(wb.sheetnames)
    
  • 遍历表单

    for sheet in wb:
        print(sheet.title)
    
  • 创建表单

    mySheet = wb.create_sheet('mySheet')
    
  • 得到具体某个表单

    sheet4 = wb.get_sheet_by_name('sheet4')
    sheet3 = wb['mySheet']
    
  • 获得激活的表单

    ws = wb.active
    
  • 获得具体的某个单元格

    ws = wb.active
    print('Row {}, Column {} is {}'.format(c.row, c.column, c.value))
    print('Cell {} is {}\n'.format(c.coordinate, c.value))
    print(ws.cell(row=4, column=1))
    print(ws.cell(row=4, column=1).value) // .value 是取值
    
  • 遍历整行信息

    a = wb['Sheet1']
    for i in range(1, 39, 1):
        print(i, a.cell(row=1, column=i).value)
    
  • 获取整行或者整列信息

    colC = a['C']
    print(colC[2].value)
    row6 = a[6]
    row_range = a[2:6]
    for cow in row_range:
        for cell in cow:
            print(cell.value)
    

    高级一点的遍历

    for row in a.iter_rows(min_col=1, max_col=2, max_row=2):
        for cell in row:
            print(cell)
    
  • 打印列

    print(tuple(a.rows))
    

    每一列(或行)是一个生成器,这边用元组tuple来包起来;

    这里面打印的是一个元组,元组里面每一个都是一个元组,要想获得具体的值,需要两次遍历;

    for i in tuple(a.rows):
        for val in i:
            print(val.value)
    
  • 切片

    cell_range = a['A1:B3']
    

    先行后列遍历切片

    for rowOfCwllObjects in cell_range:
        for cellObj in rowOfCwllObjects:
            print(cellObj.coordinate, cellObj.value)
        print('------本行结束------')
    
  • 利用属性获得表格行列

    print('{} * {}'.format(a.max_row, a.max_column))
    
  • 处理列标 AA AB的问题 -->将列标改为数字

    导包

    from openpyxl.utils import get_column_letter, column_index_from_string
    

    分别为 字母变数字 和 数字变字母 的包

    print(get_column_letter(2), get_column_letter(47), get_column_letter(900))
    

    打印第2列、第47列和第900列的字母是啥;

    print(column_index_from_string('AAH'))
    

    打印 AAH 列是多少列;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容