Excel Solver in Python: Step-by-Step Guide
In this article
You do not get Excel's Solver inside Python by clicking a button. Instead you rebuild the same idea with a Python optimisation library, or you drive Excel's own Solver engine from Python if it is available to you. The shortest working path is to install SciPy (which includes scipy.optimize), write your objective and constraints as plain functions, pick a solver such as linprog for linear problems or minimize for smooth nonlinear ones, and read the result object's success flag and values. That gets you the same answer Solver produces for most everyday spreadsheet models, with a script you can rerun and version control.
This guide assumes you are comfortable running a Python script and understand what a solver does: it changes decision variable cells until an objective cell reaches its best value subject to constraints. Menu and function names vary slightly by library version, so always check the docs for the version you install.
What You'll Need
- Python 3 installed, plus the ability to run
pip installpackages. - SciPy (
pip install scipy) for the solvers, and NumPy, which SciPy pulls in as a dependency. - Optionally
openpyxlto read model data straight from an .xlsx workbook, andpandasif you prefer loading tables that way. - A written-down model: which variables are free to change, what you are maximising or minimising, and each constraint as a mathematical inequality or equality.
- If you want to run the actual Excel Solver engine, a Windows machine with Excel and the Solver add-in installed and enabled, plus
pywin32.
Step-by-Step
- Write the model on paper first. Name every decision variable (for example
x1,x2,x3), write the objective as a formula, and list each constraint with its direction (<=, >=, =). Converting a vague spreadsheet into explicit algebra is where most of the work happens, and it is far easier to do before touching code. - Install the libraries. Run
pip install scipy openpyxlin your terminal or virtual environment. Confirm the install withpython -c "import scipy; print(scipy.__version__)". - Decide whether your problem is linear or nonlinear. If the objective and every constraint are sums of variable times a constant, it is linear (LP), and you should use
scipy.optimize.linprog. If variables multiply each other, are squared, or sit inside functions like log or exp, it is nonlinear and you should usescipy.optimize.minimize. Choosing the wrong family is the most common reason results look wrong. - Encode the linear model as arrays. For a linear problem, put the objective coefficients in one vector
c, the constraint coefficients in a matrixA, and the right-hand sides in a vectorb. UseA_ub/b_ubfor <= constraints,A_eq/b_eqfor equalities, andboundsfor each variable's allowed range (use(0, None)for non-negative variables). Then calllinprog(c, A_ub=A, b_ub=b, bounds=bounds, method="highs"). In recent SciPy versions,method="highs"is the recommended solver and handles many problem types reliably. - Read the result properly. Check
result.successfirst. If it isTrue, readresult.funfor the optimal objective value andresult.xfor the variable values. If it isFalse, readresult.message, which usually says whether the problem is infeasible or unbounded. - Encode a nonlinear model with functions and constraints. Define a function
objective(x)that returns the value to minimise (negate it if you want to maximise). Create each constraint withscipy.optimize.LinearConstraintorNonlinearConstraint, or use the older dict form withtype,funandargs. Setboundsas a list of (lower, upper) pairs, then callminimize(objective, x0, constraints=cons, bounds=bounds, method="SLSQP"). SLSQP is a common choice for smooth problems with equality and inequality constraints. - Choose a sensible starting point.
minimizeneedsx0. Use realistic ballpark numbers (production quantities you already run, prices near current levels) rather than all zeros, especially for nonlinear models. A poor start can cause slow convergence or a report of failure even when a solution exists. - Cross-check the answer. Plug
result.xback into your objective formula by hand or in a spreadsheet and confirm the objective value matchesresult.fun. Then check each constraint numerically: a solution that violates a constraint usually means a sign error or a constraint entered in the wrong direction. - Optionally load data from Excel. With
openpyxlyou can open a workbook, read the cells holding coefficients and limits, and pass those into your arrays. Keep the model logic in Python and treat the workbook as data input, so you do not have to rewrite formulas in two places. - Optionally drive Excel's Solver itself from Python. On Windows with Excel and the Solver add-in enabled,
pywin32lets you open the workbook, set the Solver objective cell, variable cells and constraints through Excel's automation interface, run it, and read back the result. This is only practical on a machine with Excel licensed and installed; it will not work on a server without Excel, and it inherits Excel Solver's own limits.
Common Mistakes
- Wrong constraint direction. Writing
b_ubwhen you needed a lower bound flips the meaning of the model silently. Re-read each constraint after encoding it. - Unbounded variables. Variables that should be non-negative are unbounded by default, which can produce absurd answers or an "unbounded" message. Set
boundsexplicitly. - Using a nonlinear solver on a linear problem. It may work but is slower and less reliable than
linprog, and can mislead you about whether a global optimum exists. - Ignoring
result.success. Readingresult.xafter a failed run gives meaningless numbers. Always gate on the success flag. - Forgetting to negate for maximisation.
minimizeminimises, so a maximum objective must be returned as its negative, then sign-flipped when you report it. - Very different variable scales. Mixing coefficients in the millions with coefficients in thousandths can destabilise the numerical solve. Rescale units so numbers are of similar magnitude.
Tips
- Start by solving a small problem whose answer you already know, so you can confirm your encoding is right before scaling up.
- Keep objective and constraint functions in their own module with clear names; you will reuse them when the model changes.
- For integer decisions (whole numbers of trucks, units or people), standard SciPy solvers return fractions. SciPy includes
milpfor mixed-integer linear problems; for richer integer models consider the third-partyPuLPorPyomopackages, which are well documented. - Print or log
result.messageevery run. It is the cheapest diagnostic you have. - Version-control the script. Unlike a spreadsheet, changes are traceable and reviewable.
Troubleshooting
"Infeasible" or success is False. Remove constraints one at a time and rerun to find the one that cannot be satisfied. A common cause is a typo in a right-hand side value or a constraint that contradicts another.
The answer violates a constraint. Check the sign and direction of that constraint, and for nonlinear models check that you passed it correctly to the constraints list.
Values look wildly wrong but the solver reports success. Re-evaluate the objective with the returned values. If it does not match result.fun, the function and the reported optimum disagree, usually because of a units or scaling problem.
Nonlinear solve fails or stops early. Try a different starting point, try method="trust-constr", and check that your functions handle the starting values without division by zero or log of a negative number.
Excel-driven Solver fails. Confirm the Solver add-in is enabled in Excel's add-ins settings, that the workbook is not protected, and that the automation call names match your Excel version. Run the script while Excel is not otherwise busy.
Frequently Asked Questions
Can I run Excel's own Solver from Python?
Yes on Windows, by automating an installed copy of Excel through pywin32 with the Solver add-in enabled. It will not work without a licensed Excel installation.
Which SciPy function replaces Solver for linear models?
scipy.optimize.linprog, using the HiGHS method for most problems.
How do I maximise instead of minimise?
Return the negative of your objective and negate the reported optimum, since the minimisers only minimise.
Do SciPy solvers give whole-number answers?
Not by default. Use scipy.optimize.milp for mixed-integer linear problems, or a package such as PuLP or Pyomo.
Why does my nonlinear solve stop with "success: False"?
Often a bad starting point, a discontinuous function, or poorly scaled variables. Change x0, rescale units, and read the message for the reason.
Can I keep the model in the spreadsheet and just solve from Python?
You can read coefficients with openpyxl, but the constraints and objective must be expressed as functions in Python. Only the Excel automation route uses the spreadsheet's own formulas.