The incident happened in Heidingsfeld, a part of the city of Wurzburg in southern Germany.
Local German media reports that three people were seriously injured, one lightly injured and 14 went into shock. A police spokesman said the attacker was shot dead while fleeing the scene.
Bavarian Interior Minister Joachim Herrman told media that the suspect, whose name has not been released, was a 17-year-old Afghan boy who came to Germany as an unaccompanied refugee.
The train line between Wurzburg-Heidingsfeld and Ochsenfurt is closed, the BBC reports.
This is a developing story. Check back for updates.