But they soon capitulated and Spain enjoyed a golden period, throwing in seven consecutive goals over an eight-minute period to lead 10-6.
The half ended with another good spell for Sweden as three successive strikes saw them reduce the deficit to 11-10 at the interval.
The second half was a much more even affair as the two sides traded goals throughout and the scoreboard had advanced to 20-20 with 10 minutes remaining.
Sweden knew it was all or nothing, but Spain seized the initiative in the final two minutes by gaining a crucial two-goal lead.
That was eventually reduced to one at the end, but Spain held on to secure a spot in the last eight.
Nely Alberto Francisca and Marta Mangue Gonzalez both threw in six for Spain, while Fogelstrom top scored with five for Sweden, who bow out of the competition having lost all four of their games.
Meanwhile, reigning Olympic Games and world champions Norway booked their place in the quarter-finals with a winning goal 11 seconds from the end of an all-Scandinavian battle with Denmark, who are now knocked out.
In a topsy-turvy battle that could have gone either way, Karoline Dyhre Breivang scored the decisive goal at the end to break Danish hearts as it finished 24-23.
Croatia won a battle of European sides in Group A, edging out Montenegro by a single goal, 27-26.
A mixed first half saw Croatia earn an 8-5 lead after five successive goals, but Montenegro scored seven of the last 11 goals to square it at 12-12 at the break.
The tight nature of the of the game continued well into the second half with the two sides trading goals throughout.
But Croatia made their move with two successive strikes with five minutes remaining and they held the advantage right until the end, despite a nervy finish.
Indeed, Montenegro could have levelled right at the end, but Jovanka Radicevic mishandled the ball with the goal gaping in the final 30 seconds.
In the day's other games, France continued their unbeaten record by inflicting a first defeat on Republic of Korea, 24-21, ensuring they finish top of Group B.
The French struck with two decisive goals in a row to grab control of the game in the final 10 minutes and they extended that to win by a three-goal margin in the concluding minutes, with Alexandra Lacrabere top-scoring with four goals.
Angola completed a 31-25 win over Great Britain in the first game of the morning at the Copper Box, while Russia edged past Brazil 31-27 in Group A.