Three-dimensional dynamics of vortex-lattice formation in Bose-Einstein condensates