close

How do I add a column to an existing excel file using python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I add a column to an existing excel file using python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I add a column to an existing excel file using python?

  1. How do I add a column to an existing excel file using python?

    You don't need to use another library to accomplish what you are trying to do. Here is another option for accomplishing what you want.

  2. add a column to an existing excel file using python

    You don't need to use another library to accomplish what you are trying to do. Here is another option for accomplishing what you want.

Method 1

It is easier to use the Pandas package

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

Method 2

From your updated question I have rewrote my answer.

You don’t need to use another library to accomplish what you are trying to do. Here is another option for accomplishing what you want.

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.')

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read