The Swiss second seed was broken in the second and third set, but regained command to complete a 6-2 7-6 6-3 win at Roland Garros.
Following a straightforward opener, Federer was forced to work hard in the second set, breaking back before he edged out Granollers in the tie-break.
The Spaniard still had plenty of fight in the third and he fashioned another break, prompting a masterful response from the world No 2, who secured a string of games.
Granoller???s fate was sealed when he dumped a return of serve into the net and Federer will next face Damir Dzumhur following the Bosnian???s 6-4 6-3 4-6 6-2 win over Marcos Baghdatis.
“I think it was a really difficult match,??? said Federer, who has not won a major since Wimbledon in 2012.
???It looks like a routine match in three sets, but in the stands you see I had to work hard. The second set was the key,”
He was joined in the next stage by compatriot Stanislas Wawrinka, who claimed a 6-3 6-4 5-7 6-3 win over Dusan Lajovic, despite an erratic performance.
The eighth seed hit 11 aces and 53 winners, but served up nine double faults and committed 52 unforced errors.