The long-standing problem of how the solar atmosphere is heated has been addressed by many theoretical studies, which have stressed the relevance of two specific mechanisms, involving magnetic reconnection and waves, as well as the necessity of treating the chromosphere and corona together1-7. But a fully consistent model has not yet been constructed and debate continues, in particular about the possibility of coronal plasma being heated by energetic phenomena observed in the chromosphere2,3,8-11. Here we report modelling of the heating of the quiet Sun, in which magnetic fields are generated by a subphotospheric fluid dynamo intrinsically connected to granulation. We find that the fields expand into the chromosphere, where plasma is heated at the rate required to match observations (4,500 watts per square metre) by small-scale eruptions that release magnetic energy and drive sonic motions. Some energetic eruptions can even reach heights of 10 million metres above the surface of the Sun, thereby affecting the very low corona. Extending the model by also taking into account the vertical weak network magnetic field allows for the existence of a mechanism able to heat the corona above, while leaving unchanged the physics of chromospheric eruptions. Such a mechanism rests on the eventual dissipation of Alfvén waves generated inside the chromosphere and that carry upwards the required energy flux of 300 watts per square metre. The model shows a topologically complex magnetic field of 160 gauss on the Sun's surface, agreeing with inferences obtained from spectropolarimetric observations12-14, chromospheric features (contributing only weakly to the coronal heating) that can be identified with observed spicules9and blinkers10,11, and vortices that may be possibly associated with observed solar tornadoes8.