1

We have 100's of shapefiles for which we have to generate excel reports based on few (combination of) parameters in the attribute table. I am using SQL query to achieve this and when i run the query in the "Create Virtual layer" process, it works fine and the output has been generated, which will be saved as an excel file. Instead of this process, i am trying to run this through python console. Though the code didn't show any error, the output is not being printed. Do i have to change the SQL query format in the code ?

Image 1: For the shapefile final_bdry, Total_Area has to be calculated based on two other columns - MS_Area, Ground_Con (similar to Pivot_Table in excel, sum of a column based on unique count of other two columns). No issues with the query and i am getting the desired output in the virtual_layer. enter image description here.

Image 2: But, if i run the same query within python console, result is "None" enter image description here Ref: Used this as ref SQL queries in shapefiles using python/gdal return none result

1

You could try directly inserting your SQL query when creating a virtual layer:

query = """ SELECT "MS_Area", "Ground_Con", sum("Area_Ha") as Total /*:ini*/ from final_bdry group by "MS_Area", "Ground_Con" """

vlayer = QgsVectorLayer( "?query={}".format(query), "vlayer", "virtual" )
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

Example:

Example

[UPDATE for QGIS 3.0]

QgsMapLayerRegistry object was changed in QGIS 3.0 for QgsProject. So, last line in 3.0 should be:

QgsProject.instance().addMapLayer(vlayer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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