Back to Python
2026-05-046 min read

Excel Relative Reference (Python Programming)

Learn Excel Relative Reference (Python Programming) step by step with clear examples and exercises.

Title: Excel Relative Reference (Python Programming)

Why This Matters

Excel relative references are crucial for creating dynamic formulas that change as data moves or grows. In Python, we can mimic Excel's relative referencing to make our code more flexible and reusable. Understanding how to use relative references in Python can save you time, reduce errors, and improve your overall productivity when working with Excel files.

Prerequisites

To follow this lesson, you should be familiar with the following:

  1. Basic Python programming concepts, such as variables, functions, loops, and conditional statements.
  2. Familiarity with data structures like lists and dictionaries.
  3. Understanding of exception handling in Python.
  4. The openpyxl library for reading and writing Excel files in Python. If you haven't installed it yet, do so using pip install openpyxl.

Core Concept

Excel relative references allow you to write formulas that adapt when cells are moved or copied. In Python, we can achieve similar functionality by using the openpyxl library and manipulating cell references within a formula.

Row and Column Notation

In Excel, relative references use row and column notation (e.g., A1, B2). In Python, when working with openpyxl, we can use similar notation to reference cells:

worksheet['A1'] # Reference cell A1 in the active worksheet
workbook['Sheet2']['A1'] # Reference cell A1 in Sheet2 of the current workbook

Relative References

To create a relative reference in Python, we simply write our formula as if the cells were in their original position. When the formula is applied to another cell, openpyxl will adjust the references automatically:

In this example, we're adding the values of A1 and B1 and placing the result in C1

worksheet['C1'] = worksheet['A1'].value + worksheet['B1'].value


If we copy this formula to another cell (e.g., D1), openpyxl will adjust the references accordingly:

Now we're adding the values of A2 and B2 and placing the result in D2

worksheet['D1'] = worksheet['A2'].value + worksheet['B2'].value


### Absolute References

Sometimes, you may want to create an absolute reference that remains unchanged regardless of where the formula is copied. In Excel, we use the dollar sign ($) to make a cell reference absolute: A$1 or $A$1. In Python, we can achieve this by using the `ref` attribute:

This formula will always reference cell A1, regardless of where it's copied

worksheet['C1'] = worksheet['A1'].value # Reference cell A1 as an absolute reference


### Mixed References

Mixed references are a combination of relative and absolute references. For example, if we want to create a formula that always references column A but adjusts for rows, we can use:

This formula will always reference column A but adjust for rows

worksheet['C1'] = worksheet['A1'].value # Reference cell A1 as an absolute column and relative row


### Cell References in Formulas

When writing formulas directly in a cell using openpyxl, you can use relative references by simply referencing the cells as if they were in their original position. For example:

worksheet['C1'].formula = '=A1+B1' # Write the formula '=A1+B1' to cell C1

Worked Example

Let's create a simple Python script that reads an Excel file, calculates the total sales for each product category, and writes the results back to the worksheet.

import openpyxl

Load the workbook

workbook = openpyxl.load_workbook('sales.xlsx')

Select the active worksheet (assuming it's Sheet1)

worksheet = workbook['Sheet1']

Find the headers for product and sales columns

product_col = next(cell for cell in worksheet[1] if cell.value == 'Product')

sales_col = next(cell for cell in worksheet[1] if cell.value == 'Sales')

Initialize a dictionary to store the total sales for each product category

total_sales = {}

Iterate through rows starting from the second row (skipping headers)

for row in worksheet[2:]:

Get the product and sales values for this row

product = row[product_col].value

sales = row[sales_col].value

If the product category is not already in our dictionary, add it with an initial value of 0

if product not in total_sales:

total_sales[product] = 0

Add the sales for this product to the running total for its category

total_sales[product] += sales

Write the total sales for each product category back to the worksheet

for category, total in total_sales.items():

Find the first empty cell in the row below the headers (assuming we're writing to column C)

next_row = next(cell for cell in worksheet[1] if cell.value is None)[0].row + 1

Write the product category and total sales to their respective cells

worksheet.cell(row=next_row, column=product_col['C'].column, value=category)

worksheet.cell(row=next_row, column=sales_col['C'].column, value=total)

Save the workbook

workbook.save('sales_totals.xlsx')

Common Mistakes

  1. Forgetting to import the openpyxl library at the beginning of your script.
  2. Not properly installing the openpyxl library before running your script.
  3. Referencing cells incorrectly, either using absolute, relative, or mixed references improperly.
  4. Failing to handle empty cells when iterating through a worksheet.
  5. Forgetting to save the workbook after making changes.
  6. Not properly handling exceptions that may occur during file operations.
  7. Not closing the workbook after making changes and saving it. You can do this by calling workbook.close() at the end of your script.

Practice Questions

  1. Write a Python script that calculates the average sales for each product category in an Excel file named sales.xlsx. Save the results in a new worksheet called "Averages".
  2. Modify the worked example to handle multiple product categories and subcategories (e.g., 'Fruits' -> 'Apples', 'Oranges'). Write the total sales for each subcategory back to the original worksheet, next to their respective product categories.
  3. Create a Python script that reads an Excel file with employee data (name, age, salary) and writes a summary of the average age and total salary to the worksheet.
  4. Modify the worked example to handle cases where there are no sales for a specific product category by adding a check and handling it appropriately.
  5. Write a Python script that reads an Excel file with multiple worksheets, calculates the total sales for each worksheet, and writes the results in a new workbook called "TotalSales".

FAQ

Q: How do I handle errors when reading or writing Excel files in Python?

A: You can use exception handling to catch and handle errors that may occur during file operations. For example, you can wrap your code in a try block and include an except block to handle specific exceptions like FileNotFoundError.

Q: Can I use relative references when writing formulas directly in the Excel file using openpyxl?

A: Yes! You can create and write formulas as strings, including relative references, using the formula attribute of a cell object. For example:

worksheet['C1'].formula = '=A1+B1' # Write the formula '=A1+B1' to cell C1

Q: How can I read and write an Excel file with multiple worksheets in Python?

A: To work with multiple worksheets, you can access them by name or index. For example, to select the second worksheet named "Sheet2", use workbook['Sheet2']. You can also iterate through all the worksheets in a workbook using a for loop:

for worksheet in workbook.worksheets:
print(worksheet.title) # Print the title of each worksheet

Q: How do I close the workbook after making changes and saving it?

A: You can call workbook.close() at the end of your script to ensure that the workbook is properly closed.

Q: What if there are no sales for a specific product category in the Excel file? How should I handle this case?

A: In the worked example, you may want to add a check to see if there are any sales for a specific product category before calculating its total. If there are no sales, you can choose to either leave the cell empty or write a message indicating that there were no sales. Here's an example of how you might handle this case:

Check if there are any sales for this product category

if sales == 0:

Write a message indicating that there were no sales

worksheet.cell(row=next_row, column=product_col['C'].column, value='No sales for this category')

else:

Write the total sales for this product category

worksheet.cell(row=next_row, column=product_col['C'].column, value=category)

worksheet.cell(row=next_row, column=sales_col['C'].column, value=total)

Excel Relative Reference (Python Programming) | Python | XQA Learn