I can suggest a PyQGIS solution. It utilizes the openpyxl
Python package.
Let's assume there is an Excel file called 'testbook' with the following data provided on the 'Sheet1':
Proceed with Plugins > Python Console > Show Editor
(see documentation) and paste the script below:
# imports
from os.path import realpath, isfile
from openpyxl import load_workbook
from qgis.core import QgsVectorLayer, QgsField, QgsFeature, QgsPointXY
from qgis.PyQt.QtCore import QVariant
from qgis.utils import iface
# providing a path to the Excel file
path_to_excel = realpath("D:/qgis_test/testbook.xlsx")
# loading Excel file with a coresponding sheet
if isfile(path_to_excel):
book = load_workbook(path_to_excel)
sheet = book.get_sheet_by_name("Sheet1")
# getting field names and data from the Excel file
data = [list(value) for value in sheet.values]
attrs, records = data[0], data[1:]
# creating a vector layer
layer = QgsVectorLayer("LineString?crs=epsg:4326", "flows", "memory")
# accessing the vector layer provider
provider = layer.dataProvider()
layer.startEditing()
# adding attributes to the vector layer
for attr in attrs:
if attr == 'id':
provider.addAttributes([QgsField(attr, QVariant.Int)])
elif any(i in attr for i in 'XY'):
provider.addAttributes([QgsField(attr, QVariant.Double)])
else:
provider.addAttributes([QgsField(attr, QVariant.String)])
layer.updateFields()
# adding data to the vector layer attributes
for record in records:
feat = QgsFeature() # creating a feature
feat.setAttributes(record) # feeding feature with attribute values
pt_from = QgsPointXY(record[4], record[3]) # starting point geometry
pt_to = QgsPointXY(record[6], record[5]) # ending point geometry
feat.setGeometry(QgsGeometry.fromPolylineXY([pt_from, pt_to])) # creating line geometry
if feat.isValid():
# adding feature to the vector layer
provider.addFeature(feat)
layer.updateExtents()
layer.commitChanges()
if layer.isValid():
# adding layer to the Project
QgsProject.instance().addMapLayer(layer)
iface.zoomToActiveLayer()
In the code above, please do not forget to change the "D:/qgis_test/testbook.xlsx"
and "Sheet1"
variables before running it.
Press Run script
and get the following output:
References: