简体   繁体   English

将公式应用于excel python中的列

[英]Applying a formula to a column in excel python

On Python 3.9.在 Python 3.9 上。

So here's what I'm trying to do.所以这就是我想要做的。 I'm running reports almost every hour and they aren't formatted when exported to excel to the way I need them to be.我几乎每小时都在运行报告,并且在导出到 excel 时没有按照我需要的方式对其进行格式化。

I'm essentially trying to figure out a way to start on the second row (since I have headers) and apply =RIGHT(Ax, 10) to each row in the column A such as =RIGHT(A2, 10), =RIGHT(A3, 10), =RIGHT(A4, 10), and so on until the last row in the workbook.我基本上是想找出一种从第二行开始的方法(因为我有标题)并将 =RIGHT(Ax, 10) 应用于 A 列中的每一行,例如 =RIGHT(A2, 10), =RIGHT (A3, 10), =RIGHT(A4, 10),依此类推,直到工作簿中的最后一行。 Each workbook will have an arbitrary number of rows since it changes (increases) as the day goes on.每个工作簿都有任意数量的行,因为它会随着时间的推移而变化(增加)。

import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active  

with open(r'location\file.csv') as f: 
    reader = csv.reader(f, delimiter=',') 
    for row in reader:
        ws.append(row) 

wb.save(r'location\file.xlsx') 

wb = openpyxl.load_workbook(r'location\file.xlsx')
sheet = wb['Sheet']
maxr = sheet.max_row
tuple(sheet[f'A2:{maxr}'])
sheet[f'A2:A{maxr}'] = f"=RIGHT(A2:A{maxr}, 10)"

wb.save(r'location\file.xlsx') 

Replace代替

tuple(sheet[f'A2:{maxr}'])
sheet[f'A2:A{maxr}'] = f"=RIGHT(A2:A{maxr}, 10)"

with

for i in range(1,maxr+1):
    sheet[f'A{i}'].value = sheet[f'A{i}'].value[-10:]

Try to keep it simple.尽量保持简单。 Give the following a try.请尝试以下操作。

Change this section of your code更改代码的这一部分

maxr = sheet.max_row
tuple(sheet[f'A2:{maxr}'])
sheet[f'A2:A{maxr}'] = f"=RIGHT(A2:A{maxr}, 10)"

to a loop到一个循环

maxr = len(sheet['A'])
for curr_row in range(2, maxr  + 1):
    curr_value = sheet.cell(row=curr_row, column=4).value 
    new_value = curr_value[-10:]
    sheet.cell(row=curr_row, column=4) = new_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM