Azure Logic App calculate Total Sum of a column from a CSV file

Viewed 1413

I'm using an Azure Logic App to get the blob contents from my storage account. The Blob-file is in .CSV file. The CSV file consists of a few columns and multiple rows. The file is basically an Invoice file which consists of a column named "PreTaxCost". I need to calculate the Total Sum of the all the entries within the "PreTaxCost" column in the CSV file to get the TOTAL BILLING COST.

Screenshot of the csv file (opened with notepad++) Any idea on how I can achieve this using Azure Logic Apps? Thanks!

2 Answers

According to our conversation and your requirements. Since you can't solve a problem when doing add number in JS inline code, so provide the add number steps below for your reference:

1. Delete the last few lines of the code in JS inline code action, return json directly.

2. Initialize two variables sum and tempItem.

enter image description here

3. Use "For each" to loop the Result from JS inline code action, and do set variable action in the "For each" loop.

enter image description here

4. The expression of fx add(...) is add(variables('tempItem'), float(items('For_each')?['PreTaxCost'])). If your "For each" loop named For each 2, the expression should be add(variables('tempItem'), float(items('For_each_2')?['PreTaxCost'])).

5. Please do not forget enable Concurrency Control, and set Degree of Parallelism as 1. Then run the logic app, you can get the sum result.

If you want to convert csv to json in Azure logic app, you can use Execute JavaScript Code action to run js code to implement it. The JS code is as below

function csvToJson(csv){

  var lines=csv.split("\r\n");

  var result = [];

  var headers=lines[0].split(",");
  for(var i=0; i<headers.length; i++){
    //remove space
    headers[i]=headers[i].split(" ").join("")
   
  }
  for(var i=1;i<lines.length;i++){

      var obj = {};
      var currentline=lines[i].split(",");

      for(var j=0;j<headers.length;j++){
          obj[headers[j]] = currentline[j];
      }

      result.push(obj);

  }

  return JSON.stringify(result);;
}
var content = "<csv content>";

var json = JSON.parse(csvToJson(content));
var sum = 0;

json.forEach(item=>{
    sum = sum + parseInt(item.PreTaxCost);
});
return sum;

For more details, please refer to here and here

Related