Referring to the FBD as shown in figure, we have four forces (N, mg, `F_(spring)` and `F_(ext)` acting on the particle.
Initially, the block is at equilibrium.
`kx_i=mg sin thetaimpliesx_i=(mgsintheta)/(k)`
When the block is pulled by an external force to bring the spring to relaxed length `x_f=0`
Hence, work done by spring force,
`W_(sp)=-1/2k(x_f^2-x_i^2)`
`=-1/2[0-((mgsintheta)/(k))^2]`
`=1/2((mgsintheta)^2)/(2k)`