4

I followed this tutorial to build a plugin and finished all without any problems.

(the plugin's function is exporting attribute table to csv file) https://www.qgistutorials.com/en/docs/3/processing_python_plugin.html

But I want to add a new function that can output specific fields to a csv-file.

Effect like this:

enter image description here

I tried using for cycle to fix the problem but failed and also read this post

Exporting attribute table to Excel from QGIS?

Unfortunately, XY tools can't import on version 3.14, even though I read this plugin's code.

# -*- coding: utf-8 -*-

"""
/***************************************************************************
 ZonalAverageRainfall
                                 A QGIS plugin
 this is to test
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-11-05
        copyright            : (C) 2020 by tong
        email                : zcc22592590@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'tong'
__date__ = '2020-11-05'
__copyright__ = '(C) 2020 by tong'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

from qgis.PyQt.QtCore import * ##QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFileDestination)


class ZonalAverageRainfallAlgorithm(QgsProcessingAlgorithm):
    """
    This is an example algorithm that takes a vector layer and
    creates a new identical one.

    It is meant to be used as an example of how to create your own
    algorithms and explain methods and variables used to do it. An
    algorithm like this will be available in all elements, and there
    is not need for additional work.

    All Processing algorithms should extend the QgsProcessingAlgorithm
    class.
    """

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    OUTPUT = 'OUTPUT'
    INPUT = 'INPUT'

    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # 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]
            )
        )
        
        # We add a feature sink in which to store our processed features (this
        # usually takes the form of a newly created vector layer when the
        # algorithm is run in QGIS).
        self.addParameter(
            QgsProcessingParameterFileDestination(
                self.OUTPUT,
                self.tr('Output file'), 
                'CSV files(*.csv)', 
            )
        )

##
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        source = self.parameterAsSource(parameters, self.INPUT, context)
        csv = self.parameterAsFileOutput(parameters, self.OUTPUT, context)
        # 用for迴圈把將與資料滾動式寫入至source後,
        # 讓fieldnames更新成新的資料,也就是我們要輸出成csv的降雨資料
        
        fieldnames = [field.name() for field in source.fields()]

        # Compute the number of steps to display within the progress bar and
        # get features from source
        total = 100.0 / source.featureCount() if source.featureCount() else 0
        features = source.getFeatures()

        with open(csv, 'w') as output_file:
            #write header
            line = ','.join(name for name in fieldnames) + '\n'
            output_file.write(line)
            
            for current, f in enumerate(features):
                #Stop the algorithm if cancel button has been clicked
                if feedback.isCanceled():
                    break
                #Add a feature in the sink
                line = ','.join(str(f[name]) for name in fieldnames) + '\n'
                output_file.write(line)
                
                #Update the progress bar
                feedback.setProgress(int(current * total))
        return {self.OUTPUT: csv}
        
##       

    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'calculate_average_rainfall'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr(self.name())

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr(self.groupId())

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return ''

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return ZonalAverageRainfallAlgorithm()

    def selectAll(self):
        for item in self.items:
            item.setCheckState(Qt.Checked)

    def unselectAll(self):
        for item in self.items:
            item.setCheckState(Qt.Unchecked)

    def getSelectedFields(self):
        selected = filter(lambda item: item.checkState() == Qt.Checked,
                          self.items)
        return map(lambda item: item.text(), selected)
1
  • 1
    @Taras just updated! thx!
    – tong
    Nov 7, 2020 at 10:27

1 Answer 1

6

You should add QgsProcessingParameterField to select field from the input layer. This returns selected field names as a string list. I've removed comments and unnecessary parts of the script.

from qgis.PyQt.QtCore import *
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterField,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFileDestination)


class ZonalAverageRainfallAlgorithm(QgsProcessingAlgorithm):

    OUTPUT = 'OUTPUT'
    FIELDS = 'FIELDS' ##### (1) #####
    INPUT = 'INPUT'

    def initAlgorithm(self, config):
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT,
                self.tr('Input layer'),
                [QgsProcessing.TypeVectorAnyGeometry]
            )
        )
        
        ##### (2) Add QgsProcessingParameterField #####
        self.addParameter(
            QgsProcessingParameterField(
                self.FIELDS,
                self.tr('Fields to export'),
                None,
                'INPUT',
                QgsProcessingParameterField.Any,
                True
            )
        )
        #####
        
        self.addParameter(
            QgsProcessingParameterFileDestination(
                self.OUTPUT,
                self.tr('Output file'), 
                'CSV files(*.csv)', 
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        csv = self.parameterAsFileOutput(parameters, self.OUTPUT, context)

        ##### (3) Selected feild names as string list #####
        fieldnames = self.parameterAsFields(parameters, self.FIELDS, context)        
        #####

        total = 100.0 / source.featureCount() if source.featureCount() else 0
        features = source.getFeatures()

        with open(csv, 'w') as output_file:
            line = ','.join(name for name in fieldnames) + '\n'
            output_file.write(line)
            
            for current, f in enumerate(features):
                if feedback.isCanceled():
                    break
                line = ','.join(str(f[name]) for name in fieldnames) + '\n'
                output_file.write(line)
                
                feedback.setProgress(int(current * total))
        return {self.OUTPUT: csv}

    def name(self):
        return 'Export selected fields to CSV'

    def displayName(self):
        return self.tr(self.name())

    def group(self):
        return self.tr(self.groupId())

    def groupId(self):
        return ''

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return ZonalAverageRainfallAlgorithm()
0

Your Answer

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

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