简体   繁体   English

用 python 编写 excel 公式所有列

[英]Write an excel formula all column with python

I have existing excel document and want to update M column according to A column.我有现有的 excel 文档,想根据 A 列更新 M 列。 And I want to start from second row to maintain first row 'header'.我想从第二行开始维护第一行“标题”。

Here is my code;这是我的代码;

import openpyxl
wb = openpyxl.load_workbook('D:\Documents\Desktop\deneme/formula.xlsx')
ws=wb['Sheet1']

for i, cellObj in enumerate(ws['M'], 1):
    cellObj.value = '=_xlfn.ISOWEEKNUM(A2)'.format(i)

wb.save('D:\Documents\Desktop\deneme/formula.xlsx')

When I run that code;当我运行该代码时;

-first row 'header' changes. -第一行“标题”更改。

-all columns in excel "ISOWEEKNUM(A2)", but I want it to change according to row number (A3,A4,A5... "ISOWEEKNUM(A3), ISOWEEKNUM(A4), ISOWEEKNUM(A5)....") - excel "ISOWEEKNUM(A2)" 中的所有列,但我希望它根据行号 (A3,A4,A5..."ISOWEEKNUM(A3), ISOWEEKNUM(A4), ISOWEEKNUM(A5).... ")

Edit:编辑:

I handled right now the ISOWEEKNUM issue with below code.我现在用下面的代码处理了 ISOWEEKNUM 问题。 I changed A2 to A2:A5.我将 A2 更改为 A2:A5。

import openpyxl
wb = openpyxl.load_workbook('D:\Documents\Desktop\deneme/formula.xlsx')
ws=wb['Sheet1']

for i, cellObj in enumerate(ws['M'], 1):
    cellObj.value = '=_xlfn.ISOWEEKNUM(A2:A5)'.format(i)

wb.save('D:\Documents\Desktop\deneme/formula.xlsx')

But still starts from first row.但仍然从第一行开始。

Here is an answer using pandas .这是使用pandas的答案。

Let us consider the following spreadsheet:让我们考虑以下电子表格:

在此处输入图像描述

First import pandas:首先导入pandas:

import pandas as pd

Then load the third sheet of your excel workbook into a dataframe called df :然后将 excel 工作簿的第三张表加载到名为df的 dataframe 中:

df=pd.read_excel('D:\Documents\Desktop\deneme/formula.xlsx', sheet_name='Sheet3')

Update column 'column_to_update' using column 'deneme'.使用列 'deneme' 更新列 'column_to_update'。 The line below converts the dates in the 'deneme' column from strings to datetime objects and then returns the week of the year associated with each of those dates.下面的行将 'deneme' 列中的日期从字符串转换为日期时间对象,然后返回与这些日期中的每一个相关联的一年中的第几周。

df['Column_to_update'] = pd.to_datetime(df['deneme']).dt.week

You can then save your dataframe to a new excel document:然后,您可以将 dataframe 保存到新的 excel 文档中:

df.to_excel('./newspreadsheet.xlsx', index=False)

Here is the result:结果如下:

在此处输入图像描述

You can see that the values in 'column_to_update' got updated from 1, 2 and 3 to 12, 12 and 18.您可以看到“column_to_update”中的值从 1、2 和 3 更新为 12、12 和 18。

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

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