Australia beat Russia 11-8 to secure the No. 1 spot in Group B behind four goals from Nicola Zagame.
Spain, which is making its Olympic debut, had to win by at least two goals to ensure itself the top spot in the group ahead of the United States, the 2008 silver medallist and one of the favourites in London.
The Spanish almost let the top seed slip away in the last minute after Dora Czigany scored for Hungary at the near post with 49 seconds to play to pull within 12-11. Furious with herself, Spain goalkeeper Laura Ester Ramos repeatedly slapped the post with her hand before retrieving the ball from the net.
But Spain got a final chance to push the margin to two goals after a Hungary turnover with 12 seconds left, and Espar Llaquet took advantage by slotting the final goal past goalkeeper Edina Gangl.
"It's the first time we have come to the Olympics, and we have come here not just to play but to win," Espar Llaquet said. "We train a lot so I think that we deserve to be there, fighting with teams like Australia or U.S.A."
Spain's win assured it the top seed even before the U.S. hit the pool for its final Group A match against China, which the Americans won 7-6 behind three goals from Maggie Steffens.
The U.S. finished second in the group, and will play Italy, which beat Britain 10-5 on Friday, in the quarterfinals on Sunday.
Britain, meanwhile, wrapped up the group stage winless and in last place in Group B, earning it a matchup with Spain in the knockout stage. Spain will be without coach Miguel Angel Oca for the game, after he received a red card against Hungary and one-game suspension.
Australia, which along with the U.S. was considered the gold medal-favourite coming into the competition, locked up the top seed on the other side of the bracket by beating previously undefeated Russia.
The Australians jumped out to a 6-4 lead in a fast-paced first quarter before the game settled down into the physical contest that was expected out of the medal contenders.
"We've come here for one job, and that's to get the gold medal, so just six games — three down — and just ticking the boxes really as we keep going," Zagame said. "Hopefully we'll finish on the podium, hopefully on the top."
In the quarterfinals, Australia will face China, who is assured a fourth-place finish in Group B. While the Chinese have been in poor form so far in London, the other teams remain wary of the 2011 world championship runners-up.
"They're a very strong team," said Australia coach Greg McFadden. "Unfortunately they haven't played that well here — or fortunately, I hope they continue that way — it's going to be a tough game, and we know each other very well because we play against each other a lot and we used to train together, so it's going to be very difficult, and like I said, it's sudden death now, so the pressure's going to be on everyone."
Ryan Lucas can be reached on twitter at www.twitter.com/relucasz