openpyxl修改excel列数据

思路:先加载表,获取sheet再用max_row获取做大行数进行遍历,再用cell获取与修改数据。

from openpyxl import load_workbook
import os
files = []
file_path = r'路径'
for dirpath,dirnames,filenames in os.walk(file_path):
    for file in filenames:
        if file.endswith('.xlsx') or file.endswith('.xls'):
            files.append(dirpath+'\\'+file)
for file in files:
    work_book = load_workbook(filename=file)  # 加载excel表格
    wa = work_book.active
    xl_sheet = work_book['Sheet1']
    row = xl_sheet.max_row #获取行数
    for i in range(2,row+1):
        if(xl_sheet.cell(i,2).value!=""):
            if(len(xl_sheet.cell(i,2).value)<13):
                xl_sheet.cell(i, 2).value = '0'+xl_sheet.cell(i, 2).value
    work_book.save(file)

你可能感兴趣的:(Python应用,python)