zoukankan      html  css  js  c++  java
  • Python函数-操作Excel

    1、写Excel

    import xlwt
    
    book = xlwt.Workbook()  # 生成一个Workbook
    sheet = book.add_sheet('sheet1')  # 一个sheet页
    sheet.write(0, 0, '学生姓名')  # 行、列
    sheet.write(1, 0, '大白')
    sheet.write(2, 0, '小白')
    sheet.write(3, 0, '小黑')
    book.save('student.xls')  # 用office只能用xls结尾的,如果用wps,可以用.xlsx
    
    # 小练习
    data = {
        "1": ["小花", 99, 100, 98.5],
        "2": ["小王", 90, 30.5, 95],
        "3": ["小明", 67.5, 49.6, 88]
    }
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    title = ['学号', '姓名', '语文', '数学', '英文', '总分', '平均分']
    # 处理表头
    row = 0
    for t in title:
        sheet.write(0, row, t)
        row += 1
    
    # 优化一
    data = [
        ["1", "小花", 99, 100, 98.5],
        ["2", "小王", 90, 30.5, 95],
        ["3", "小明", 67.5, 49.6, 88]
    ]
    rows = 1
    for row in data:  # 行循环
        col = 0
        sum_score = sum(row[2:])  # 算总分
        avg_score = round(sum_score / 3, 2)  # 算平均分
        row.append(sum_score)
        row.append(avg_score)
        for column in row:  # 列循环
            sheet.write(rows, col, column)
            col += 1
        rows += 1
    
    # 优化之后(enumerate)
    for rows, row in enumerate(data, 1):  # 行循环,用枚举将二维数组转成带下标的值
        sum_score = sum(row[2:])  # 算总分
        avg_score = round(sum_score / 3, 2)  # 算平均分,取两位小数点
        row.append(sum_score)
        row.append(avg_score)
        for col, column in enumerate(row):  # 列循环
            sheet.write(rows, col, column)
    
    book.save('student.xls')

    2、读Excel

    import xlrd
    
    book = xlrd.open_workbook('student.xls')
    sheet = book.sheet_by_index(0)  # 根据下标来取
    # sheet = book.sheet_by_name('sheet1')  # 根据名字来取
    print(sheet.cell(0, 0).value)  # 指定单元格的内容
    print(sheet.row_values(1))  # 取整行的数据
    print(sheet.col_values(0))  # 取整列的数据
    print(sheet.nrows)  # 多少行
    print(sheet.ncols)  # 多少列

    3、修改Excel

    from xlutils import copy
    import xlrd
    import os
    
    book = xlrd.open_workbook('student.xls') #open这个文件
    new_book = copy.copy(book)  #将book拷贝到xlutils模块的book
    sheet = new_book.get_sheet(0)
    sheet.write(0, 0, 'id')  #一个单元格改
    sheet.write(0, 1, 'name')
    os.rename('student.xls', 'student_bak.xls')   #备份一哈
    new_book.save('student.xls')  #保存

    4、小练习

  • 相关阅读:
    Leetcode 191.位1的个数 By Python
    反向传播的推导
    Leetcode 268.缺失数字 By Python
    Leetcode 326.3的幂 By Python
    Leetcode 28.实现strStr() By Python
    Leetcode 7.反转整数 By Python
    Leetcode 125.验证回文串 By Python
    Leetcode 1.两数之和 By Python
    Hdoj 1008.Elevator 题解
    TZOJ 车辆拥挤相互往里走
  • 原文地址:https://www.cnblogs.com/ccxm/p/13532457.html
Copyright © 2011-2022 走看看