The electronic structure and absorption spectrum of the wurtzite Zn1-xMgxO(x=0, 00625, 0125, 025) alloys have been calculated by means of the first-principles method. The doping of magnesium leads to an apparent change of the electronic structure of ZnO. The electron density of the oxygen atoms near the magnesium atom increases obviously, and the oxygen atoms transfer some of the electrons to Zn atoms nearby. This weakens the interactions between zinc and oxygen atoms, the band gap becomes broader, which has been validated by the extent of shift of Zn 4s in the same alloys. Theoretical calculation also reveals a blue shift in the absorption spectrum of Mg-doped ZnO, and the absorption edges were located at 379，366，357 and 333nm, respectively, with increasing doping of magnesium in ZnO. The results are discussed in detail.