It’s just basic thermodynamics.
The energy (calories) you take in has to go somewhere. Some of it gets used for daily activity, but if you take in more than you burn, your body has to store the extra—it doesn’t have any other way to deal with it.
At the end of the day, it really is just a matter of calories in vs. calories out.
Exercise just helps burn more of your excess energy so that it doesn’t get converted into (weight) storage.