Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel Solver in Python: Step-by-Step Guide

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 install packages.
  • SciPy (pip install scipy) for the solvers, and NumPy, which SciPy pulls in as a dependency.
  • Optionally openpyxl to read model data straight from an .xlsx workbook, and pandas if 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

  1. 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.
  2. Install the libraries. Run pip install scipy openpyxl in your terminal or virtual environment. Confirm the install with python -c "import scipy; print(scipy.__version__)".
  3. 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 use scipy.optimize.minimize. Choosing the wrong family is the most common reason results look wrong.
  4. Encode the linear model as arrays. For a linear problem, put the objective coefficients in one vector c, the constraint coefficients in a matrix A, and the right-hand sides in a vector b. Use A_ub/b_ub for <= constraints, A_eq/b_eq for equalities, and bounds for each variable's allowed range (use (0, None) for non-negative variables). Then call linprog(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.
  5. Read the result properly. Check result.success first. If it is True, read result.fun for the optimal objective value and result.x for the variable values. If it is False, read result.message, which usually says whether the problem is infeasible or unbounded.
  6. 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 with scipy.optimize.LinearConstraint or NonlinearConstraint, or use the older dict form with type, fun and args. Set bounds as a list of (lower, upper) pairs, then call minimize(objective, x0, constraints=cons, bounds=bounds, method="SLSQP"). SLSQP is a common choice for smooth problems with equality and inequality constraints.
  7. Choose a sensible starting point. minimize needs x0. 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.
  8. Cross-check the answer. Plug result.x back into your objective formula by hand or in a spreadsheet and confirm the objective value matches result.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.
  9. Optionally load data from Excel. With openpyxl you 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.
  10. Optionally drive Excel's Solver itself from Python. On Windows with Excel and the Solver add-in enabled, pywin32 lets 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_ub when 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 bounds explicitly.
  • 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. Reading result.x after a failed run gives meaningless numbers. Always gate on the success flag.
  • Forgetting to negate for maximisation. minimize minimises, 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 milp for mixed-integer linear problems; for richer integer models consider the third-party PuLP or Pyomo packages, which are well documented.
  • Print or log result.message every 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.