In my attribute table there is a large number of fields. I want to export the data with selected fields.
How to do this in QGIS?
Two ways:
You can probably set up a graphical model to do all this if you are going to be doing this a number of times.
I could suggest a PyQGIS way of implementing this task.
# referring to a needed layer
layer = iface.activeLayer()
# creating a temporal layer from selected features
temp_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.selectedFeatureIds()))
# specifying important fields
needed_fields = ["id"]
all_fields = [field.name() for field in layer.fields()]
other_fields = list(set(all_fields) - set(needed_fields))
# getting indexes of other fields
idx = [temp_layer.fields().indexFromName(field) for field in other_fields]
# deleting other fields based on their indexes
temp_layer.dataProvider().deleteAttributes(idx)
temp_layer.updateFields()
# adding temporal output to the map canvas
QgsProject.instance().addMapLayer(temp_layer)
References:
Save only selected features
inSave Vector Layer as ...