如何使用Python在现有的Excel文件中添加一列?

7

这是我的代码:

import openpyxl, pprint
wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA1.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')


data = {}
for row in range(1,sheet.max_row+1):


        date = sheet['A' +str(row)].value
        gamma = sheet['B' +str(row)].value
        theta = sheet['C' +str(row)].value
        ratio = float(gamma)/float(theta)
        resultFile = open('SSA2.csv' , 'w')
        resultFile.write( pprint.pformat(date))
        resultFile.write( pprint.pformat(gamma))
        resultFile.write( pprint.pformat(theta))

        resultFile.write( pprint.pformat(ratio))
        print(ratio)
        sheet['D1']=ratio
resultFile.close()
print('Done.')

我现有的Excel文件目前有三列:“日期,伽玛,西塔”。我想添加第四列名为“比率”,它是伽玛/西塔的比值。如何使用Python向现有的Excel文档中添加另一列?此代码创建一个包含4个元素打印到一个单元格中的Excel文档。

SSA2.csv 为什么是 CSV 格式而不是 XLSX 格式? - Mike - SMT
3个回答

12

使用Pandas软件包更容易

import pandas as pd
file_name = #Path to your file
df = pd.read_excel(file_name) #Read Excel file as a DataFrame

df['Ratio'] = df['Gamma']/df['Theta']
#Display top 5 rows to check if everything looks good
df.head(5)

#To save it back as Excel
df.to_excel("path to save") #Write DateFrame back as Excel file

非常感谢!这是我第一次看到代码“df.to_excel(“保存路径”)”,您能解释一下这行代码吗? - Sarah Porgess
以下是代码的功能:它将Excel文件读取为DataFrame,这是一种代表表格数据的数据结构。在将Excel文件读取为DataFrame之后,您可以进行很多操作,包括转换、连接、合并、数学运算等。 df.to_excel() 只是将DataFrame写回磁盘作为Excel文件。 - Rakesh Adhikesavan
虽然Pandas是一个很棒的库,但它并不是编辑Excel文件的最佳工具。 - Charlie Clark

2

根据你更新的问题,我重写了我的回答。

你不需要使用另一个库来完成你想要做的事情。这里有另一个选项可以实现你想要的目标。

import openpyxl
import pprint

wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA1.xlsx')
sheet = wb.active
# you may also use the wb.get_sheet_by_name('Sheet1') method here.


data = {}
for row in range(1,sheet.max_row+1):
        date = sheet.cell(row = row, column = 1) # use .cell() to get values of cells
        gamma = sheet.cell(row = row, column = 2)
        theta = sheet.cell(row = row, column = 3)
        print(date, gamma, theta)
        ratio = float(gamma)/float(theta)
        new_wb = openpyxl.Workbook() # creates new workbook to be saved as results
        # you can also open a wookbook here instead but I wrote it to create a results workbook as I didnt already have one.
        new_sheet = new_wb.active
        new_sheet['A1'] = pprint.pformat(date)
        new_sheet['B1'] = pprint.pformat(gamma)
        new_sheet['C1'] = pprint.pformat(theta)
        new_sheet['D1'] = pprint.pformat(ratio)
        print(ratio)
        # save new workbook as SSA2
        new_wb.save('/Users/sarahporgess/Desktop/SSA2.xlsx')

print('Done.')

打字错误!我是指列,谢谢! - Sarah Porgess
@SarahPorgess:我已经更新了我的答案,使用了你当前的导入。 - Mike - SMT

1
从你的代码中不清楚你是想打印结果还是编辑现有文件。如果你正在编辑一个Excel文件,那么你可能想创建一个公式并让Excel为你计算。
import openpyxl
wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA1.xlsx')
sheet = wb['Sheet1']

for row in sheet:
     date, gamma, theta = row
     ratio = theta.offset(column=1)
     ratio.value = "=B{0}/C{0}".format(theta.row) # if you want the formula
     # ratio.value = gamma/theta # if you just want the calculation

wb.save(…)

他正在将结果添加到另一个文件中。 - Mike - SMT
1
在这种情况下,问题是误导性的。 - Charlie Clark
有时候人们不能清楚地表达自己的问题。这就是为什么我要检查代码,从问题和代码内容来判断他们的问题到底是什么。这种方法被证明比不采用更准确。 - Mike - SMT
将数据保存到另一个文件只需将文件名传递给save()方法即可。更重要的是,为此类操作利用openpyxl API:不需要创建循环,也不需要使用pprint,而是使用offset方法。 - Charlie Clark
将原始代码与我的建议进行比较。openpyxl提供了所有必要的方法,因此不必创建计数器(max_row可能不可用)等。 - Charlie Clark
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接