dpkg -l
lists all installed packages (at list when you filter it right). You can get the same list with dpkg --get-selections
(which requires no further filtering).
This loses information about manually vs. automatically-installed packages. It's very convenient to have libraries and other packages marked as only indirectly-needed. Packages marked as automatically installed can be removed or replaced by different packages without fuss. Dpkg doesn't know about automatically-installed packages, only apt does.
To list the manually-installed packages, you can use aptitude:
aptitude search -F %p '~i !~M' >reinstallList.txt
Without aptitude, it's a bit more complicated.
dpkg --get-selections | awk '$2 == "install" {print $1}' >installed.txt
apt-mark showauto >automatic.txt
comm -32 installed.txt automatic.txt >reinstallList.txt
To install all the packages that were formerly installed:
apt-get install $(cat reinstallList.txt)
Alternatively, you can use the more roundabout method of copying the list of installed packages, and then restoring the list of packages marked as automatic. To back up:
dpkg --get-selections >selections.txt
apt-mark showauto >automatic.txt
To restore:
dpkg --set-selections <selections.txt
apt-get dselect-upgrade
apt-mark markauto $(cat automatic.txt)