I have the well-built legend in the QGIS print composer, as my project includes more than 20 layers. Because the legend in front layout doesn't match our legend patterns produced in Excel I am wondering about the option of exporting these legend items to MS Excel.
Is there any reasonable and quite quick way of exporting the print layout legend items to Excel?
Best Answer
Interesting question. I couldn't resist having a play around with this. I have hacked together a Python script (cobbled from different sources) which should take care of this for you.
Note: you will need to install one third party Python module: XlsxWriter. The best way to do this may vary depending on your OS and your QGIS version and installation. I installed QGIS on Windows with the new OSGeo4W installer, but with some tweaking this should work for any Windows install.
Option 1: I use a batch file which looks like this:
You can copy this into a text editor and edit if necessary. The line
SET OSGEO4W_ROOT=
should point to the directory containing thebin
folder where your QGIS application is located (in my case it isC:\OSGeo4W
. Next, this batch file calls another batch file (the one QGIS uses to set the pyqgis environment) so check that there is apython-qgis.bat
file located in the bin folder. Depending on your version it may bepython-qgis-ltr.bat
so edit the batch file above accordingly. Save this batch file somewhere (give it a name likeOSGeo4W_pyqgis.bat
) and double click to run. The shell will open up to a Python prompt. typequit()
and hit enter. Now typepip install XlsxWriter
and hit enter. That is how I installed XlsxWriter and it worked for me.Option 2: Alternatively, you could try running the following lines inside the QGIS Python console (this may indeed be the most straight forward):
You can check this thread and related ones for more info but again, depending on your installation, some discussions may be out of date because with the new OSGeo4W installer, there is no longer a
py3_env.bat
.Assuming you have managed to install
XlsxWriter
in the Python used by QGIS, you can now paste the following script into an editor in the Python console, change the export path and layout name, and click run.See below for example results with a test layout legend. My legend in the layout looks like this:
The resulting spreadsheet looks like this:
References:
Python: convert QT QIcon into jpeg?
https://xlsxwriter.readthedocs.io/example_images.html
https://xlsxwriter.readthedocs.io/example_images_bytesio.html
xlsxwriter: how to load a BytesIO png files created with matplotlib.pyplot