Question

How to defind attributes with python from excel file?

  • 19 September 2019
  • 2 replies
  • 9 views

Badge
Hello,

 

I would like to process an excel file within FME, using python caller.

First of all I wold like to find a string srt= "number: " in the excel, get the position of it (like A1) and define a cell that containes the value (like A2) and save the value as an attribute number and the value. Could you give me an example python script, please?


2 replies

Badge +3

@gylona

 

There are a couple of libraries that provide tools for that.

Like openpyXL etc.

 

There are a lot of examples or small tuts showing how to. Like at datacamp.

Badge

Hi Gylona,

 

My algorithm to implement your question is like this. Even though I think we could have better ways to do that with ListBuilder->ListSearcher/ListIndexer-> PythonCaller, but if you like to have the pure pythonCaller solution, this is my solution for your question. Please don't hesitate to comment or discuss about this if you have any question.

import fme
import fmeobjects

def processFeature(feature):
    pass

class FeatureProcessor(object):

    def __init__(self):
        self.initNumber = 1
        self.attrAllNames = []
        self.specificAttrName = ''
        self.specificAttrValue = ''
        self.featureArray = []

    def input(self,feature):
        if self.initNumber == 1:  # get all attributes' names just once
            self.attrAllNames = feature.getAllAttributeNames()
            self.initNumber = 0
        #loop every attribute of each feature, and get the value
        for attrName in self.attrAllNames:
            valueOfSpecificAttr = feature.getAttribute(attrName)  
            if valueOfSpecificAttr == 'number:': #when found your 'number'
                self.specificAttrName = attrName  #record this attribute name
                self.specificAttrValue = valueOfSpecificAttr #record attribute's value
                break
        #push all row/feature into array for setting value and final output
        self.featureArray.append(feature)
 
    def close(self):
        # here define your A2 or A3 or etc.... up to you
        # index started from 0, careful don't out of range
        index = 1 
        # here set your defined A2 or A3... values got from A1
        self.featureArray[index].setAttribute(self.specificAttrName, self.specificAttrName + ' ' + self.specificAttrValue) 
        for f in self.featureArray: #output
            self.pyoutput(f)

 

Reply