WHAT IS IT?
Excommunication is a religious censuring of a person or group.  It certainly isn't when your drunken ex rings you in the middle of the night, again.  What actually happens when a person is excommunicated varies in each religion and depends on the various rules of the Church and the seriousness of the events. In the Catholic Church there are two different kinds of excommunication. The first is automatic which starts from the moment of the offense and the second is either imposed by a legitimate superior or a sentence of an ecclesiastical court.
WHERE DO YOU GET IT?
The short answer is from a church. The long answer is that you've actually got to be caught  doing something that breaks the Church Law. What actually breaks Church law? That's what you've got to find out for yourself 
USING IT IN REAL LIFE:
To the disapointment of many you can't just go around excommunicating people for littering or not cleaning up after their dogs.  There is an official process that a person must go through before excommunication is a) an option and b) made official.
History has given us many occurrences of people being excommunicated: Saint Jehanne la Pucelle  by Bishop Pierre Cauchon in 1431
Martin Luther in 1520 by the Pope 
Elizabeth 1 of England in 1570
All Catholics who participated in the creation of an independent church in the Philipines in 1902
USING IT IN WRITING:
It's a fact that wherever you have a large organization you are going to have all sorts of internal politics, cliques, nepotism, blackmail, espionage, deliberate sabotage and, if things are really going downhill, nights of the long knives.
Excommunication or even the threat of it can be a devasting weapon in the wrong hands and properly used it can be an extra level of threat for the hero and an ultimate punishment for the villain.
It might be used in the following situations:
The hero disobeys the village priest and sets out on his journey.
Perhaps a particular ceremony doesn't happen due to circumstances that are totally beyond the characters control.
Someone is not following the proscribed rituals and this has been noted.
Is there a ban on a particular type of food?  To be fair if eating something is going to get you kicked out then it had better be on the scale of cannibalism.