29using namespace Qt::StringLiterals;
39 const QStringList formattersAllowList { u
"KeyValue"_s, u
"List"_s, u
"ValueRelation"_s, u
"ValueMap"_s };
41 for (
int i = 0; i < mLayer->fields().count(); ++i )
43 const QgsEditorWidgetSetup setup = mLayer->fields().at( i ).editorWidgetSetup();
45 if ( formattersAllowList.contains( fieldFormatter->
id() ) )
47 mFormatters[i] = fieldFormatter;
48 mConfig[i] = setup.
config();
58 const int idx = mLayer->fields().indexFromName( field.
name() );
59 if ( mFormatters.contains( idx ) )
61 QgsField newField( field.
name(), QMetaType::Type::QString );
62 newField.setAlias( field.
alias() );
68 QVariant
convert(
int i,
const QVariant &value )
override
70 const QgsFieldFormatter *formatter = mFormatters.value( i );
75 if ( mCaches.contains( i ) )
77 cache = mCaches.value( i );
81 cache = formatter->
createCache( mLayer.data(), i, mConfig.value( i ) );
85 return formatter->
representValue( mLayer.data(), i, mConfig.value( i ), cache, value );
88 FieldValueConverter *
clone()
const override
94 QPointer<QgsVectorLayer> mLayer;
95 QMap<int, const QgsFieldFormatter *> mFormatters;
96 QMap<int, QVariantMap> mConfig;
97 QMap<int, QVariant> mCaches;
100QString QgsExportToSpreadsheetAlgorithm::name()
const
102 return u
"exporttospreadsheet"_s;
105QString QgsExportToSpreadsheetAlgorithm::displayName()
const
107 return QObject::tr(
"Export to spreadsheet" );
110QStringList QgsExportToSpreadsheetAlgorithm::tags()
const
112 return QObject::tr(
"microsoft,excel,xls,xlsx,calc,open,office,libre,ods" ).split(
',' );
115QString QgsExportToSpreadsheetAlgorithm::group()
const
117 return QObject::tr(
"Layer tools" );
120QString QgsExportToSpreadsheetAlgorithm::groupId()
const
122 return u
"layertools"_s;
125void QgsExportToSpreadsheetAlgorithm::initAlgorithm(
const QVariantMap & )
129 addParameter(
new QgsProcessingParameterBoolean( u
"FORMATTED_VALUES"_s, QObject::tr(
"Export formatted values instead of raw values" ),
false ) );
131 outputParameter->
setMetadata( QVariantMap( { { u
"widget_wrapper"_s, QVariantMap( { { u
"dontconfirmoverwrite"_s,
true } } ) } } ) );
132 addParameter( outputParameter );
137QString QgsExportToSpreadsheetAlgorithm::shortHelpString()
const
139 return QObject::tr(
"This algorithm collects a number of existing layers and exports them to a spreadsheet document.\n\n"
140 "Optionally the layers can be appended to an existing spreadsheet as additional sheets.\n\n" );
143QString QgsExportToSpreadsheetAlgorithm::shortDescription()
const
145 return QObject::tr(
"Collects a number of existing layers and exports them to a spreadsheet document." );
148QgsExportToSpreadsheetAlgorithm *QgsExportToSpreadsheetAlgorithm::createInstance()
const
150 return new QgsExportToSpreadsheetAlgorithm();
155 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u
"LAYERS"_s, context );
158 mLayers.emplace_back( layer->clone() );
161 if ( mLayers.empty() )
162 feedback->
reportError( QObject::tr(
"No layers selected, spreadsheet will be empty" ),
false );
169 const bool overwrite = parameterAsBoolean( parameters, u
"OVERWRITE"_s, context );
170 const QString outputPath = parameterAsString( parameters, u
"OUTPUT"_s, context );
171 if ( outputPath.isEmpty() )
174 const bool useAlias = parameterAsBoolean( parameters, u
"USE_ALIAS"_s, context );
175 const bool formattedValues = parameterAsBoolean( parameters, u
"FORMATTED_VALUES"_s, context );
176 bool createNew =
true;
178 if ( overwrite && QFile::exists( outputPath ) )
180 feedback->
pushInfo( QObject::tr(
"Removing existing file '%1'" ).arg( outputPath ) );
181 if ( !QFile( outputPath ).remove() )
186 else if ( QFile::exists( outputPath ) )
191 const QFileInfo fi( outputPath );
194 OGRSFDriverH hDriver = OGRGetDriverByName( driverName.toLocal8Bit().constData() );
197 if ( driverName ==
"ods"_L1 )
205 if ( !QFile::exists( outputPath ) )
209 throw QgsProcessingException( QObject::tr(
"Creation of spreadsheet %1 failed (OGR error: %2)" ).arg( outputPath, QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
212 bool errored =
false;
216 QStringList outputLayers;
218 for (
const auto &layer : mLayers )
223 multiStepFeedback.setCurrentStep( i );
229 feedback->
pushDebugInfo( QObject::tr(
"Error retrieving map layer." ) );
234 feedback->
pushInfo( QObject::tr(
"Exporting layer %1/%2: %3" ).arg( i ).arg( mLayers.size() ).arg( layer ? layer->name() : QString() ) );
236 FieldValueConverter converter( qobject_cast<QgsVectorLayer *>( layer.get() ) );
238 if ( !exportVectorLayer( qobject_cast<QgsVectorLayer *>( layer.get() ), outputPath, context, &multiStepFeedback, driverName, createNew, useAlias, formattedValues ? &converter :
nullptr ) )
242 outputLayers.append( u
"%1|layername=%2"_s.arg( outputPath, layer->name() ) );
251 outputs.insert( u
"OUTPUT"_s, outputPath );
252 outputs.insert( u
"OUTPUT_LAYERS"_s, outputLayers );
273 feedback->
reportError( QObject::tr(
"Exporting layer failed: %1" ).arg( error ) );
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
bool isCanceled() const
Tells whether the operation has been canceled already.
Base class for all map layer types.
Contains information about the context in which a processing algorithm is executed.
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void pushDebugInfo(const QString &info)
Pushes an informational message containing debugging helpers from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
Processing feedback object for multi-step operations.
A multi-layer output for processing algorithms which create map layers, when the number and nature of...
A boolean parameter for processing algorithms.
void setMetadata(const QVariantMap &metadata)
Sets the parameter's freeform metadata.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
A parameter for processing algorithms which accepts multiple map layers.
Interface to convert raw field values to their user-friendly values.
FieldValueConverter()=default
virtual QVariant convert(int fieldIdxInLayer, const QVariant &value)
Convert the provided value, for field fieldIdxInLayer.
virtual QgsVectorFileWriter::FieldValueConverter * clone() const
Creates a clone of the FieldValueConverter.
virtual QgsField fieldDefinition(const QgsField &field)
Returns a possibly modified field definition.
Options to pass to QgsVectorFileWriter::writeAsVectorFormat().
QString fileEncoding
Encoding to use.
QString driverName
OGR driver to use.
QString layerName
Layer name. If let empty, it will be derived from the filename.
QgsVectorFileWriter::FieldValueConverter * fieldValueConverter
Field value converter.
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
QgsVectorFileWriter::FieldNameSource fieldNameSource
Source for exported field names.
QgsFeedback * feedback
Optional feedback object allowing cancellation of layer save.
static QgsVectorFileWriter::WriterError writeAsVectorFormatV3(QgsVectorLayer *layer, const QString &fileName, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QString *errorMessage=nullptr, QString *newFilename=nullptr, QString *newLayer=nullptr)
Writes a layer out to a vector file.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
@ PreferAlias
Use the field alias as the exported field name, wherever one is set. Otherwise use the original field...
@ Original
Use original field names.
@ CreateOrOverwriteLayer
Create or overwrite layer.
@ CreateOrOverwriteFile
Create or overwrite file.
Represents a vector layer which manages a vector based dataset.
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.