[GIS] Exporting Geopackage table to directory as CSV with PyQGIS

csvgeopackagepyqgis

I have the following extract from a PyQGIS script showing the final function. This script actually form part of a plugin tool for QGIS. I create three geopackage layers and save them into the chosen directory (out_dir_gpkg).

I would also like the ability to export each geopackage table as a CSV to a chosen directory (out_dir_gpkg), before I load the geopackages into QGIS which the script already includes.

Question

So my question is how would I achieve this below the line that reads:

#Export Geopackage table as CSV file to CSV output directory

Script (function)

    def save_and_load_res_layers(self):
    """ Save result layers as GPKG and load them.
        Copy the CSV files to their output dir. """

    for name, switch in self.process.items():
        if not switch:
            continue

        if not self.res[name]:
            continue

        gpkg_path = os.path.join(self.out_dir_gpkg, "{}.gpkg".format(self.res_names[name]))
        error = QgsVectorFileWriter.writeAsVectorFormat(
            self.res[name],
            gpkg_path,
        )
        if error[0] != QgsVectorFileWriter.NoError:
            self.uc.show_warn('Saving result layer {} failed. Is it opened?'.format(name))
            continue

        # Export Geopackage table as CSV file to CSV output directory

        # load GPKG
        res = QgsVectorLayer(gpkg_path, self.res_names[name], "ogr")
        loaded_lyr = QgsProject.instance().addMapLayer(res)
        if not loaded_lyr:
            self.uc.show_warn('Couldn\'t load result layer {}.'.format(name))
            continue

Best Answer

I think, this code will solve your requirements

from osgeo import gdal

gdal.VectorTranslate('/path/test.xlsx', '/ruta/the_gpkg_path.gpkg', options='-f XLSX layer1 layer2 layer3')

Remember that layer1 layer2 and layer3 have to have the same name inside the geopackage name.

I use this geopackage to the example:

enter image description here

And obtain this result:

enter image description here

Related Question