Seems to be two different theories that I can find.
The first is that it is a toned down version of an oath which involves Holy and insert name of one of the Trinity. It seems to have originated in the 20th century and is said by people to make the blasphemous saying sound innocent. Same kind of idea as darn, heck or shoot.
The other idea is that it is a kind of joke against the Hindu religion of considering cows sacred.