2

The following code allows me to save a text file with .xls extension in Python. When I open it, I receive the following warning:

The file you are trying to open, is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

def saveExcel (layer,name):
 # get the path
 pathSave=getDirectoryPath()
 chdir(pathSave)
 filename=name+".xls"
 f=open(filename,"w")
 # Save fields'names
 for field in layer.fields():
 f.write(field.name()+ "\t")
 f.write("\n")
 # Save attributes
 for element in layer.getFeatures():
 for field in layer.fields():
 f.write(str(element.attribute(field.name()))+ "\t")
 f.write("\n")
 f.close()
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Sep 27, 2018 at 10:18
2

1 Answer 1

7

If you are in QGIS environment you could make a QgsVectorLayer with your data and export that as xlsx:

QgsVectorFileWriter.writeAsVectorFormat(layer, path, "utf-8", layer.crs(), 'xlsx')
answered Jan 18, 2019 at 9:48
1
  • this command seems to not work any idea why? I have already made the QgsVectorLayer Commented Jan 12, 2022 at 7:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.