python使用openpyxl修改已存在表格的单元格的值

程序目的:

根据某个字段的值修改另一个字段的值,例如根据resource字段的值修改result的值

《python使用openpyxl修改已存在表格的单元格的值》

别忘记下载 openpyxl 对应的包  pip install openpyxl

import os
import openpyxl
#表格位置,所有表格都在一个文件夹下面
dir = "./excels"
excel_list = os.listdir(dir)

x = 1 #resource对应的列号
y = 2 #result对应的列号

def get_rank(value):
    #value是一个string
    value = int(value)
    rank = value//200
    return rank

def alter_excel(excelpath):
    wb = openpyxl.load_workbook(excelpath,data_only=True)
    sheet1 = wb.worksheets[0]  # 通过索引获取表格,一个文件里可能有多个sheet
    row_num = sheet1.max_row #获取表格行数
    #遍历每一行,对相应的字段进行处理
    for i in range(2,row_num+1):
        rank = get_rank(sheet1.cell(i,x).value)
        sheet1.cell(i, y).value = rank+1
    wb.save(excelpath)



if __name__ == '__main__':
    for excelfile in excel_list:
        excelpath = os.path.join(dir, excelfile)
        alter_excel(excelpath)

    print("success!")

 

    原文作者:PMPWDF
    原文地址: https://blog.csdn.net/PMPWDF/article/details/101420576
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞