Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to perform excel spreadsheet operation in Python?
Excel spreadsheets contain cells with values, formulas, or cell references. In Python, we can simulate this by processing a 2D matrix where each cell can contain a number, a cell reference (like "B1"), or a formula (like "=A1+A2").
Problem Understanding
Given a 2D matrix representing an Excel spreadsheet, we need to evaluate all formulas and cell references to get the final computed values. Columns are labeled A, B, C... and rows are numbered 1, 2, 3...
| Input Matrix | Output Matrix | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
Solution Approach
We need several helper functions to process different types of cell content:
- resolve() ? Converts cell references to actual values
- getIdx() ? Converts cell references like "A1" to matrix indices [0,0]
- do() ? Performs arithmetic operations
- solve() ? Main function to evaluate each cell
Implementation
class Solution:
def solve(self, matrix):
def resolve(s):
try:
return int(s)
except:
return solve(*getIdx(s))
def getIdx(s):
return [int(s[1:]) - 1, ord(s[0]) - ord("A")]
def do(a, b, op):
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/":
return a / b
def solve(i, j):
try:
return int(matrix[i][j])
except:
s = matrix[i][j]
if s[0] == "=":
for c in s[2:]:
if c in "+-/*":
op = c
break
a, b = s[1:].split(op)
aRes, bRes = resolve(a), resolve(b)
return do(aRes, bRes, op)
else:
return solve(*getIdx(s))
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] = str(solve(i, j))
return matrix
# Test the solution
ob = Solution()
matrix = [
["B1", "7", "0"],
["3", "5", "=A1+A2"]
]
result = ob.solve(matrix)
print(result)
[['7', '7', '0'], ['3', '5', '10']]
How It Works
The algorithm processes each cell based on its content type:
- Numbers ? Return as-is after converting to integer
- Cell references (like "B1") ? Convert to matrix coordinates and recursively solve
- Formulas (like "=A1+A2") ? Parse the operation, resolve operands, and compute result
Example Walkthrough
For the cell "=A1+A2":
- A1 refers to matrix[0][0] which contains "B1"
- B1 refers to matrix[0][1] which contains "7"
- A2 refers to matrix[1][0] which contains "3"
- Final calculation: 7 + 3 = 10
Supported Operations
| Operation | Symbol | Example |
|---|---|---|
| Addition | + | =A1+B1 |
| Subtraction | - | =A1-B1 |
| Multiplication | * | =A1*B1 |
| Division | / | =A1/B1 |
Conclusion
This solution recursively evaluates Excel-like formulas by parsing cell references and arithmetic operations. The recursive approach handles nested cell references efficiently, making it suitable for complex spreadsheet calculations.
