How does ion exchange work? Why does it remove calcium ions (Ca2+) and magnesium ions (Mg2+) from hard water?

If you want a thorough explanation your best bet is to Google the subject and read, read, read. In simple terms, an ion exchange bed (or resin) is an organic polymer that has sites built within it that contain a particular ion. When a solution is passed through this resin certain ions, such as Ca^2+ and Mg^2+ are held up. In place of those ions other ions take their place. Often these other ions are Na^+. Resins of this type are good for replacing the calcium and magnesium of hard water with sodium ions to make it soft water. Other resins are on the market that exchange other ions. One nice thing about the hard water exchange of Ca and Mg ions for Na ions is that the resin becomes ineffective when all of the exchange sites have been used BUT it can be reversed and returned to it's initial status. So the resin can be used over and over.