Lewandowski was described by Bayern as "sickish" before the game but came on after the halftime break to score two goals and set up another in a topsy-turvy match that saw Bayern reduced to 10 men after 15 minutes and give up two goals in a three-minute span as Heidenheim fought back to make it 4-4.
"It was a wild, open game, which I don't like in this form. In the end we had the bit of luck that you need in the cup," Bayern coach Niko Kovac said. "I never experienced a game like it before." It had looked more likely to be a routine home win when Leon Goretzka gave Bayern the lead in 12th minute.
But Niklas Suele was sent off just afterward after bringing down Robert Andrich in front of the penalty area when the Heidenheim midfielder was through on goal. Heidenheim captain Marc Schnatterer, who had already hit the crossbar, crossed for the Munich-born Robert Glatzel to head in the equalizer in the 27th and then stunned the home fans when he fired inside the far post to grab a shock lead in the 39th.
Lewandowski's condition improved enough for coach Niko Kovac to bring him on for the second half and it paid off almost straight away with the forward setting up Thomas Mueller to equalize in the 53rd, two minutes before he put Bayern back in front.
Serge Gnabry thought he'd extinguished the visitors' hopes of an upset in the 66th, but Glatzel scored twice within three minutes - the second a penalty - to draw Heidenheim level again in the 77th. Gnabry twice hit the crossbar before Lewandowski finally sealed it with a penalty in the 84th.
"It was fun," Heidenheim coach Frank Schmidt said. "It was a crazy evening, with the wrong result from our point of view." Second-half goals from Milot Rashica and Davy Klaassen were enough for Werder Bremen to win 2-0 at Schalke in the last quarterfinal. The visitors had Nuri Sahin sent off late with a second yellow card.
Leipzig and Hamburger SV reached the semifinals on Tuesday.
More AP German soccer coverage: https://apnews.com/Bundesliga and https://twitter.com/AP_Sports