首页 > 解决方案 > 从特定行开始通过 Python 编写公式

问题描述

我正在尝试编写一个代码,该代码将插入一个从特定行开始但没有运气的公式。当前代码为整列创建公式,而我需要它从第 5 行开始,一直到数据集的末尾。如果您有解决方案,请告诉我

    wb = openpyxl.load_workbook(file, keep_vba = True)
    sheet = wb.get_sheet_by_name('Roster')
    for I, cell in enumerate(sheet['V'], 1):
        cell.value = '=Left($U{0},1)'.format(I)
    wb.save(file)

标签: pythonpandas

解决方案


试试这个,首先加载 excel 作为数据框,然后只选择你需要的记录

from  openpyxl.utils.dataframe import dataframe_to_rows
book = pd.read_excel("file.xlsx",sheet_name="Roster")
df = book.iloc[5:,:]

接下来将数据框转换为 openpyxl 对象,您可以完成剩下的工作

sheet = dataframe_to_rows(df)
//do your operations

推荐阅读