1

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

1 Answer 1

1

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

2
  • Thanks but the directory contains 3 geopackages not 1 geopackage containing 3 layers.
    – AWGIS
    Dec 5, 2019 at 21:38
  • @AWGIS , only you have to use the same function in one loop. Only need the path of the Geopackages, what do you think ? Dec 5, 2019 at 21:46

Your Answer

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

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