如何使用python将列添加到现有的Excel文件中?

这是我的代码:

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文件当前有三列:“日期,伽玛,θ”.我要添加第四列,称为“比率”,即gamma /θ的比率.如何使用python在现有的Excel文档中添加另一列?
此代码创建一个Excel文档,并将4个元素打印到一个单元格中

解决方法:

使用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
上一篇:python-如何使用openpyxl获取位置(行,列)处单元格的值?


下一篇:C# 获取程序运行目录