3

I made a Plugin containing features for a specific workflow. As the last function I wanted to add the qgis processing tool "ExportToSpreadsheet" (Layertool) into my plugin. It's a native processing tool (algorithm_id = native:exporttospreadsheet)

I can't seem to figure out how to add it. It would be enough if the button just starts the processing tool, for example the same way as the added buttons "measureLine" or "addFeature".

Here's my code so far:

from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt, QFile, QFileInfo, QIODevice
from qgis.PyQt.QtGui import QIcon, QGuiApplication
from qgis.PyQt.QtWidgets import qApp,  QApplication,  QAction, QCheckBox, QComboBox, QFileDialog, \
                                                          QLabel, QMessageBox, QStyle
from qgis.core import *
from qgis.core import QgsProcessingParameterFeatureSource
import processing
from qgis.analysis import QgsNativeAlgorithms
from qgis.gui import QgsMapToolCapture, QgsCheckableComboBox, QgsGui, QgsLayoutItemAbstractGuiMetadata


# Initialize Qt resources from file resources.py
from .resources import *

# Import the code for the dialog
from .unterhalt_dialog import UnterhaltDialog
from .unterhalt_utils import *
from .gpkg_project_file_changer import GPKGProjectFileChanger
from .interlis_import_export_dialog import InterlisImportDialogBase
from .map_tool_copy_from_av import MapToolCopyFromAV
import os.path
import os


# # Access the processing algorithm
# QgsApplication.setPrefixPath('C:/OSGeo4W64/apps/qgis', True)
# qgs = QgsApplication([],False)
# qgs.initQgis()

# Processing.initialize()
# QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())



class Unterhalt:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        self.processing = processing
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # Save reference to QGIS settings
        self.qgis_settings = QSettings()
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'Unterhalt_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        # self.dlg = UnterhaltDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Unterhalt')

        #declare instance attributes
        # self.dlg.directory.clear()
        # self.dlg.push_directory.clicked.connect(self.output)
        # self.dlg.button_box.clicked.connect(self.ExportToSpreadsheet)

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('Unterhalt', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        
        """Create and name toolbar"""

        self.toolCopyFromAV = MapToolCopyFromAV( self.iface, self.iface.mapCanvas() )

        self.toolbar = self.iface.addToolBar(self.tr('Unterhalt'))

        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        self.actionUpdatePathes = QAction(QIcon(':/plugins/unterhalt/icons/update_layer_path.svg'), self.tr('Pfade der Layer aktualisieren'))
        self.actionUpdatePathes.triggered.connect(self.updatePathes)
        self.toolbar.addAction(self.actionUpdatePathes)
        
        self.actionInterlisImport = QAction(QIcon(':/plugins/unterhalt/icons/interlis.png'), self.tr('Interlis importieren'))
        self.toolbar.addAction(self.actionInterlisImport)
        self.actionInterlisImport.triggered.connect(self.interlis_import_export)

        saveLayerEdits = self.iface.actionSaveEdits()
        saveLayerEdits.setToolTip(self.tr('Änderungen speichern'))
        self.toolbar.addAction(saveLayerEdits)       

        toggleEditing = self.iface.actionToggleEditing()
        all_widgets = QApplication.instance().allWidgets()
        for widget in all_widgets:
            if widget.windowTitle() == 'Digitizing Toolbar':
                for action in widget.actions():
                    if action.objectName() == 'mActionToggleEditing':
                        action.trigger()
        self.toolbar.addAction(toggleEditing)

        addFeature = self.iface.actionAddFeature()
        addFeature.setToolTip(self.tr('Objekt Hinzufügen'))
        self.toolbar.addAction(addFeature)   

        self.copyFromAV = QCheckBox( self.tr('Aus AV kopieren'))
        self.toolbar.addWidget(self.copyFromAV)

        #self.toolbar.addWidget( QLabel(self.tr('AV Layer')))
        self.avLayerComboBox = QComboBox()
        avItemText = [self.tr('Liegenschaften'),self.tr('Selbstrechte'),self.tr('Bodenbedeckung'),self.tr('Fixpunkte'),self.tr('Grenzpunkt'),self.tr('Einzelobjekte Linien'),self.tr('Gemeindegrenze'),self.tr('Einzelobjekte Fläche'),self.tr('Flurnamen'),self.tr('Gebäudeeingang')]
        avItemData = ['Liegenschaften','Selbstrechte','Bodenbedeckung','Fixpunkte','Grenzpunkt','Einzelobjekte Linien','Gemeindegrenze','Einzelobjekte Fläche','Flurnamen','gebaeudeeingang']
        nAVItems = min(len(avItemData),len(avItemText))
        for i in range(nAVItems):
            self.avLayerComboBox.addItem(avItemText[i],avItemData[i])
        self.avLayerComboBox.currentTextChanged.connect(self.switchAVLayer)
        self.switchAVLayer()
        self.toolbar.addWidget(self.avLayerComboBox)

        self.copyFromAV.stateChanged.connect(self.avLayerComboBox.setEnabled)
        self.copyFromAV.stateChanged.connect(self.setCaptureTool)
        self.copyFromAV.setChecked(False)
        self.avLayerComboBox.setEnabled(False)

        moveAction = self.iface.actionMoveFeature()
        moveAction.setToolTip(self.tr('Objekte/Beschriftungen verschieben'))
        self.toolbar.addAction(moveAction)

        self.actionRotate = QAction(QIcon(':/plugins/unterhalt/icons/rotate.svg'), self.tr('Beschriftung rotieren'))
        self.actionRotate.setCheckable(True)
        self.actionRotate.toggled.connect(self.enableRotationTool)
        self.toolbar.addAction(self.actionRotate)

        measureLine = self.iface.actionMeasure()
        measureLine.setToolTip(self.tr('Linie/Distanz messen'))
        self.toolbar.addAction(measureLine)

        measureArea = self.iface.actionMeasureArea()
        measureArea.setToolTip(self.tr('Fläche messen'))
        self.toolbar.addAction(measureArea) 

        self.WmsComboBox=QComboBox()
        self.toolbar.addWidget(self.WmsComboBox)
        self.WmsComboBox.addItem('WMS AV-ZH Farbe', 'url=http://wms.zh.ch/OGDAVfarbigZH&format=image/png&layers=OGDAVfarbigZH&styles=&crs=EPSG:2056')
        self.WmsComboBox.addItem('WMS AV-ZH sw', 'url=http://wms.zh.ch/OGDAVswZH&format=image/png&layers=OGDAVswZH&styles=&crs=EPSG:2056')
     #   self.WmsComboBox.addItem('WMS AV AG', 'url=https://wms.geo.ag.ch/')
        self.WmsComboBox.activated.connect(self.addWMS)

        addWmsLayer = self.iface.actionAddWmsLayer()
        addWmsLayer.setToolTip(self.tr('Weitere WMS hinzufügen'))
        self.toolbar.addAction(addWmsLayer)

        self.actionExportToExcel = QAction(QIcon(':/plugins/unterhalt/icons/excel.svg'), self.tr('In Excel exportieren'))
        self.actionExportToExcel.triggered.connect(self.ExportToSpreadsheet)
        self.toolbar.addAction(self.actionExportToExcel)


        # self.actionExportToSpreadsheet = QAction(QIcon(':/plugins/unterhalt/icons/icon.png'), self.tr('In Excel exportieren'))
        # self.toolbar.addAction(self.actionExportToSpreadsheet)
        # self.actionExportToSpreadsheet.triggered.connect(self.ExportToSpreadsheet)


       # icon_path = ':/plugins/unterhalt/icon.png'
       # self.add_action(
        #    icon_path,
        #    text=self.tr(u'Unterhalt'),
        #    callback=self.run,
        #    parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        # remove the toolbar
        del self.toolbar


    def interlis_import_export(self):
        self.import_export_dialog = InterlisImportDialogBase()
        self.import_export_dialog.show()

    def addWMS(self, Index):
        rlayer = QgsRasterLayer(self.WmsComboBox.currentData(), 'WMSLayer', 'wms')
        QgsProject.instance().addMapLayer(rlayer, True)
        print(self.WmsComboBox.currentData())

    def setCaptureTool(self):
        if self.copyFromAV.isChecked():
            self.iface.mapCanvas().setMapTool(self.toolCopyFromAV)
        else:
            self.iface.actionAddFeature().trigger()


    def switchAVLayer(self):
            self.toolCopyFromAV.setAVLayer(self.avLayerComboBox.currentData())

    def enableRotationTool(self, active):
        if active:
            self.iface.mapCanvas().setMapTool(self.rotate_label)    

    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = UnterhaltDialog()

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
        

    def updatePathes(self):
        #let the user select a gpkg file
        lastGPKGPath = self.qgis_settings.value('unterhalt/lastGPKGPath')
        gpkgFile = QFileDialog.getOpenFileName( None, self.tr('GPKG-Datei auswählen'), lastGPKGPath , self.tr("Geopackage (*.gpkg);;Alle Dateien(*)"))[0]
        if not gpkgFile:
            return
        
        #Make sure to open the second dialog in same directory
        lastGPKGPath = QFileInfo(gpkgFile).path()
        avGPKGFile = QFileDialog.getOpenFileName( None, self.tr('AV GPKG-Datei auswählen'), lastGPKGPath , self.tr("Geopackage (*.gpkg);;Alle Dateien(*)"))[0]
        
        
        QGuiApplication.setOverrideCursor(Qt.WaitCursor)
        self.iface.newProject()
        
        self.iface.mainWindow().statusBar().showMessage(self.tr('Aktualisiere Datenpfade in {}').format(gpkgFile))
        
        #GPKGProjectFileChanger
        storage = QgsApplication.projectStorageRegistry().projectStorageFromType( 'geopackage' )
        pfChanger = GPKGProjectFileChanger( gpkgFile, storage )
        pfChanger.adaptLayerPathes(avGPKGFile, self.iface.statusBarIface())
        
        QGuiApplication.restoreOverrideCursor()


    # def initAlgorithm(self, config=None):
    #     self.addParameter(QgsProcessingParameterFeatureSource(
    #         self.INPUT_VECTOR, "Input vector"))
    #         # We add the input vector features source. It can have any kind of
    # # geometry.
    #     self.addParameter(
    #         QgsProcessingParameterFeatureSource(
    #             self.INPUT,
    #             self.tr('Input layer'),
    #             [QgsProcessing.TypeVectorAnyGeometry]
    #         )
    #     )    

    def ExportToSpreadsheet(self):
        """Export all selected layers in into excel sheets xlsx"""

        params = {
             'INPUT': input,
             'OUTPUT' : output
         }
        
        processing.run("native:exporttospreadsheet", params)

One of the last things I tried was adding a button myself:

self.actionExportToExcel = QAction(QIcon(':/plugins/unterhalt/icons/excel.svg'), self.tr('In Excel exportieren'))
self.actionExportToExcel.triggered.connect(self.ExportToSpreadsheet)
self.toolbar.addAction(self.actionExportToExcel)

and then call or run the processing tool:

def ExportToSpreadsheet(self):
    """Export all selected layers in into excel sheets xlsx"""

    params = {
         'INPUT': input,
         'OUTPUT' : output
     }
    
    processing.run("native:exporttospreadsheet", params)

but everything I tried failed (giving parameters, making separate plugin, etc) The reason I want this feature is because one can select several layers to be exported into excel sheets at once. If I make my own plugin I can only export 1 layer as csv atm...

Does anyone know how I can add this specific processing tool to my plugin? Is this even possible?

2
  • 1
    What is multilayers in ExportToSpreadsheet? Where do you define it? Dec 16, 2022 at 8:58
  • this was something I tried and forgot to delete before posting the code. sorry for the confusion
    – geofreak
    Dec 16, 2022 at 9:35

2 Answers 2

6

You need to use self.iface.layerTreeView().selectedLayers(). Define ExportToSpreadsheet as follows and connect an action to the method.

def ExportToSpreadsheet(self):
    """Export all selected layers in into excel sheets xlsx"""
    
    selected_layers = self.iface.layerTreeView().selectedLayers()
    
    params = {
            'LAYERS': selected_layers,
            'USE_ALIAS': False,
            'FORMATTED_VALUES': False,
            'OVERWRITE': False,
            'OUTPUT' : "./output.xlsx"
        }
    
    processing.run("native:exporttospreadsheet", params)
3
  • Thank you for the hint. I tried this but now I get the following error: "_core.QgsProcessingException: Unable to execute algorithm Incorrect parameter value for LAYERS" But I'm sure this was a step in the right direction at least. thank you
    – geofreak
    Dec 16, 2022 at 9:42
  • Thank you for your help. unfortunately I still get the same error. Maybe it's a problem with the layer type. I'll try to find out..
    – geofreak
    Dec 16, 2022 at 10:58
  • interestingly, if I print the output print(self.iface.layerTreeView().selectedLayers()) the console returns the selected layers. But it still gives out the same error messages about the incorrect parameter value for layers. So it's probably something else ^^
    – geofreak
    Dec 16, 2022 at 12:26
0

So at last it works - My script now also has a function so one can actually choose a Filepath and Name.

here's the code for the few lines that are the ExcelToSpreadsheet part:

def initGui(self):
        
        """Create and name toolbar"""

        self.toolbar = self.iface.addToolBar(self.tr('Unterhalt'))

        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        self.actionExportToExcel = 
        QAction(QIcon(':/icons/excel.png'), self.tr('Export to Excel'))
        self.actionExportToExcel.triggered.connect(self.ExportToSpreadsheet)
        self.toolbar.addAction(self.actionExportToExcel)

def ExportToSpreadsheet(self):
    """Export all selected layers in into excel sheets xlsx"""
    
    selected_layers = self.iface.layerTreeView().selectedLayers()
    output = self.select_output_file()
    print(self.iface.layerTreeView().selectedLayers())

    
    params = {
            'LAYERS': selected_layers,
            'USE_ALIAS': False,
            'FORMATTED_VALUES': False,
            'OVERWRITE': False,
            'OUTPUT': output
        }
    
    processing.run("native:exporttospreadsheet", params)
    
    self.iface.messageBar().pushMessage(
        "Speichern erfolgreich", level=Qgis.Success, duration=3)


def select_output_file(self):
    filename, _filter = QFileDialog.getSaveFileName(
        self.dlg, "Speicherort wählen ","", 'Microsoft Excel (*.xlsx)')
    self.dlg.lineEdit.setText(filename)
    return filename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.