2

I have created some code to select a specific layer in the Layers Panel. Now I want to export the selected features to an Excel document. Is there a way to do this?

Code so far:

#Select layer to export selected features
name = 'Individual Trees'

view = iface.layerTreeView()
m = view.model()

listIndexes = m.match(m.index(0, 0), Qt.DisplayRole, name, Qt.MatchFixedString)
    
if listIndexes:
    i = listIndexes[0]
    view.selectionModel().setCurrentIndex(i, QItemSelectionModel.ClearAndSelect)

#Export to excel file: C:\\Users\\MatthewWhitehead\\OneDrive - Innovative Forestry Ltd\\Arboricultural Reports\\Tree Condition Survey\\Tree_Condition_Ind_Export.xlsx

1 Answer 1

7

No need to programmatically select your layer in the layers panel- you can access the layer you want to export simply by its name. To export the layer to a .xlsx, you can call the 'Export to spreadsheet' processing algorithm from the Python console.

See docs for the algorithm here.

However, to only export selected features, I think you will need to create a temporary layer containing only the selected features of your permanent layer. You can try the script below:

lyr_name = 'Individual Trees'
out_path = 'C:\\Users\\MatthewWhitehead\\OneDrive - Innovative Forestry Ltd\\Arboricultural Reports\\Tree Condition Survey\\Tree_Condition_Ind_Export.xlsx'

lyr = QgsProject.instance().mapLayersByName(lyr_name)[0]

wkb = QgsWkbTypes.displayString(lyr.wkbType())
crs = lyr.crs().authid()
tmp_lyr = QgsVectorLayer(f'{wkb}?crs={crs}', f'{lyr_name}', 'memory')
tmp_lyr.dataProvider().addAttributes(lyr.fields())
tmp_lyr.updateFields()
tmp_lyr.dataProvider().addFeatures([f for f in lyr.selectedFeatures()])

processing.run("native:exporttospreadsheet", {
    'LAYERS' : [tmp_lyr],
    'USE_ALIAS' : False,
    'FORMATTED_VALUES' : False,
    'OUTPUT' : out_path,
    'OVERWRITE' : True
    })
2
  • Hi, when it exports the records, the fields which were multiple values show as numbers instead as the text, is their a way of fixing this? Nov 2, 2022 at 16:46
  • 1
    @matthew whitehead, I'm not entirely sure what you mean, but you could try setting the 'FORMATTED_VALUES' parameter to True.
    – Ben W
    Nov 5, 2022 at 0:56

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.