0% found this document useful (0 votes)
29 views6 pages

Program 7

The document provides a Python program that performs various operations on an Excel spreadsheet using the openpyxl library. It includes functions for reading the first five rows, appending/deleting rows and columns, and performing aggregate functions such as sum, average, max, and min on specified columns. The program also demonstrates these operations and saves the modified workbook as 'modified_excel_file.xlsx'.

Uploaded by

Nomita Chawla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views6 pages

Program 7

The document provides a Python program that performs various operations on an Excel spreadsheet using the openpyxl library. It includes functions for reading the first five rows, appending/deleting rows and columns, and performing aggregate functions such as sum, average, max, and min on specified columns. The program also demonstrates these operations and saves the modified workbook as 'modified_excel_file.xlsx'.

Uploaded by

Nomita Chawla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Introduction to Python Programming

7. Implement a Python program to perform the following


operations on an Excel spreadsheet:
I. Reading the first 5 rows of all columns
II. Appending a new row / new column
III. Delete row/column
IV. To perform aggregate functions
# P7.py
import openpyxl

# Load the workbook and select the sheet


def load_workbook(file_path, sheet_name='Sheet1'):
wb = openpyxl.load_workbook(file_path)
sheet = wb[sheet_name]
return wb, sheet

# I. Reading the first 5 rows of all columns


def read_first_5_rows(sheet):
rows = []
for row in sheet.iter_rows(min_row=1, max_row=5, values_only=True):
rows.append(row)
return rows

# II. Appending a new row or column


def append_row(sheet, data):
sheet.append(data)

def append_column(sheet, data):


max_row = sheet.max_row

Prof. Nomitha Chawla - BIET


Introduction to Python Programming

for i, value in enumerate(data, start=1):


sheet.cell(row=i, column=max_row + 1, value=value)

# III. Deleting a row or column


def delete_row(sheet, row_num):
sheet.delete_rows(row_num)

def delete_column(sheet, col_num):


sheet.delete_cols(col_num)

# IV. Performing aggregate functions


def sum_column(sheet, col_num):
col_sum = 0
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row,
min_col=col_num, max_col=col_num, values_only=True):
col_sum += row[0] if isinstance(row[0], (int, float)) else 0
return col_sum

def average_column(sheet, col_num):


total = 0
count = 0
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row,
min_col=col_num, max_col=col_num, values_only=True):
if isinstance(row[0], (int, float)):
total += row[0]
count += 1
return total / count if count != 0 else 0

Prof. Nomitha Chawla - BIET


Introduction to Python Programming

def max_column(sheet, col_num):


max_value = None
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row,
min_col=col_num, max_col=col_num, values_only=True):
if isinstance(row[0], (int, float)):
if max_value is None or row[0] > max_value:
max_value = row[0]
return max_value

def min_column(sheet, col_num):


min_value = None
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row,
min_col=col_num, max_col=col_num, values_only=True):
if isinstance(row[0], (int, float)):
if min_value is None or row[0] < min_value:
min_value = row[0]
return min_value

# Main function to demonstrate the operations


def main():
# Load the workbook and the sheet
file_path = 'C:\\Users\\Desktop\\example.xlsx' # Replace with your Excel
file path
wb, sheet = load_workbook(file_path)

# I. Reading the first 5 rows of all columns


print("First 5 rows of all columns:")
first_5_rows = read_first_5_rows(sheet)
for row in first_5_rows:
print(row)
Prof. Nomitha Chawla - BIET
Introduction to Python Programming

# II. Appending a new row


new_row = ['New', 'Row', 123, 456.78] # Example new row to append
append_row(sheet, new_row)
print("\nAppended new row:", new_row)

# II. Appending a new column


new_column = ['New Data', 10, 20, 30, 40, 50] # Example new column to
append
append_column(sheet, new_column)
print("\nAppended new column:", new_column)

# III. Deleting a row (e.g., delete row 6)


delete_row(sheet, 6)
print("\nDeleted row 6")

# III. Deleting a column (e.g., delete column 5)


delete_column(sheet, 5)
print("\nDeleted column 5")

# IV. Aggregate functions


print("\nSum of column 2:", sum_column(sheet, 2))
print("Average of column 2:", average_column(sheet, 2))
print("Max of column 2:", max_column(sheet, 2))
print("Min of column 2:", min_column(sheet, 2))

# Save the modified workbook


wb.save('modified_excel_file.xlsx')

Prof. Nomitha Chawla - BIET


Introduction to Python Programming

print("\nWorkbook saved as 'modified_excel_file.xlsx'")

if __name__ == "__main__":
main()
#SAMPLE OUTPUT

Prof. Nomitha Chawla - BIET


Introduction to Python Programming

Explanation of the Operations:


1. Reading the First 5 Rows:

o read_first_5_rows(sheet) reads the first 5 rows from all columns


using iter_rows with min_row=1 and max_row=5. The
values_only=True ensures we only get cell values (not formatting).

2. Appending New Row or Column:

o append_row(sheet, data) appends a new row of data.

o append_column(sheet, data) appends a new column by iterating


through rows and placing each value in the new column.

3. Deleting Row or Column:

o delete_row(sheet, row_num) deletes a specific row.

o delete_column(sheet, col_num) deletes a specific column.

4. Aggregate Functions:

o sum_column(sheet, col_num) calculates the sum of a specific


column.

o average_column(sheet, col_num) calculates the average of the


values in a specific column.

o max_column(sheet, col_num) finds the maximum value in a


column.

o min_column(sheet, col_num) finds the minimum value in a column.

Notes:
• Replace ' file_path ' variable with the path to your actual Excel file.
• The operations modify the workbook in-place, and after the operations,
the workbook is saved as 'modified_excel_file.xlsx'.

Prof. Nomitha Chawla - BIET

You might also like