Planetary formation theories suggest that the giant planets formed on circular and coplanar orbits. The eccentricities of Jupiter, Saturn and Uranus, however, reach values of 6 per cent, 9 per cent and 8 per cent, respectively. In addition, the inclinations of the orbital planes of Saturn, Uranus and Neptune take maximum values of ~2 degrees with respect to the mean orbital plane of Jupiter. Existing models for the excitation of the eccentricity of extrasolar giant planets have not been successfully applied to the Solar System. Here we show that a planetary system with initial quasi-circular, coplanar orbits would have evolved to the current orbital configuration, provided that Jupiter and Saturn crossed their 1:2 orbital resonance. We show that this resonance crossing could have occurred as the giant planets migrated owing to their interaction with a disk of planetesimals. Our model reproduces all the important characteristics of the giant planets' orbits, namely their final semimajor axes, eccentricities and mutual inclinations.