The phrase "spill the beans" implies divulging information indiscreetly. The verb spill had been used figuratively as early as the 16th century to mean "to divulge or pass on information." It did so, however, without the sense of indiscretion that "the beans" has imparted to "spill the beans." In other words, when you spill the beans, it is usually a "insert-foot-into-mouth" moment, whereas when you're told to "spill it," you're usually coerced into it.
The phrase originated in the U.S. as a slang expression in the early part of the 20th century, and the use of beans is a bit puzzling. In this phrase, they represent valuable—or at least desirable—bits of information, while in most English idioms the bean is a measure of worthlessness: "He doesn't know beans" or "It isn't worth a hill of beans," and so forth. The simplest—and rather uninteresting—explanation is that "the beans" is a nonsensical filler.
A bit more interesting is that early print evidence occurs in horse racing or baseball.
Ethylene was 15 to 1 one day and would have won sure had Battiste been up. He was set down by the starter in St. Louis and I had to ride a bad boy. Then we put Battiste up later and got down. Kiley told him to take her back a bit. He did, and in some manner the field ran around and over her so that she was shut in, cut off and lost. So the beans were spilled.
— The St. Louis Republic, 25 Nov. 1902
At this point the game began to get interesting, as Logan was just two scores behind, and we're beginning to find Farrow's delivery with ease, but the "beans were spilled" in the eighth when Jones, who played sensational ball all during the game, erred on Murphy and Kelley, first two up....
— The Democrat-Sentinel, 29 Aug. 1907
In short time, it was used outside of sports with the connotation of causing a different kind of upset—one caused by revealing secret information.
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."
— The Van Wert Daily Bulletin, October 1911
"Spill the beans" was also once a favorite cliché among writers of detective stories, in which it appears in statements like "Wilson, in a moment of weakness, spilt the beans." That use is most familiar today, and people often use it informally when they want someone to reveal information about something meant to be a surprise.