To divulge a secret, especially to do so inadvertently or maliciously.
The derivation of this expression is sometimes said to be a voting system used in ancient Greece. The story goes that white beans indicated positive votes and black beans negative. Votes had to be unanimous, so if the collector 'spilled the beans' before the vote was complete and a black bean was seen, the vote was halted. That's plausible, but doesn't account for the fact that the phrase is first found in the early 20th century. It's probably best if we concentrate our search there and ignore ancient Greece.
'Spill' has been used as a verb with the meaning of 'divulge' or 'let out' since at least the 16th century. Edward Hellowes' Guevara's Familiar epistles, 1574, contains an example of that usage:
"Although it be a shame to spill it, I will not leaue to say that which... his friends haue said vnto me."
That 'let out' meaning was probably influenced by an earlier meaning of 'spill', that is, 'kill' and the subsequent usage 'spill blood', which was in common use by the 14th century.
The earliest uses of 'spill the beans' come from the USA. The meaning of the phrase was then something like 'spoil the beans' or 'upset the applecart', which harks back to the supposed Greek knocking over of a bean container. The first example I can find is from The Stevens Point Journal, June 1908:
"Tawney, when he came to congress, wasn't welcomed within the big tent. He had to wait around on the outside. Then the blacksmith [Jim Tawney] got busy. He just walked off the reservation, taking enough insurgent Republicans with him to spill the beans for the big five."
Soon after that the phrase was used with the meaning of 'upset a previously stable situation by talking out of turn', which is close to how we use it today. That is cited in The Van Wert Daily Bulletin, October 1911:
"Finally Secretary Fisher, of the President's cabinet, who had just returned from a trip to Alaska, was called by Governor Stubbs to the front, and proceeded, as one writer says, to 'spill the beans'."
We have 'spill', meaning 'divulge', but why beans? Well, it could have been almost anything. In fact, there are several 'spill the' variants - 'spill the soup', 'spill your guts', or simply, just 'spill'.