According to the Oxford English Dictionary, it was first used in 1858 after English cricketer H.H. Stephenson took three wickets in three consecutive deliveries during a game between an all-England team and Hallam.
A collection was held afterwards, with money being placed into a hat before being presented to Stephenson.
There are also connotations associated with the practice of magicians conjuring unexpected items from a hat.
Nimegoogle