Search code examples
excelpowerbipowerquerym

Automatically Expand all "Table Columns" with specific name


I'm a beginner in coding and am not familiar with "M" modeling language. I have an XML file that I want to use to load the data in Query Editor. In the Query, I need to expand only the table columns with a specific name below:

  1. view
  2. viewfolder
  3. Attribute:name

I have found the following post where they give a function by Chris Webb for expanding all the lists(below code).

= (TableToExpand as table, optional ColumnNumber as number) =>
    let
     ActualColumnNumber = if (ColumnNumber=null) then 0 else ColumnNumber,
     ColumnName = Table.ColumnNames(TableToExpand){ActualColumnNumber},
     ColumnContents = Table.Column(TableToExpand, ColumnName),
     ColumnsToExpand = List.Distinct(List.Combine(List.Transform(ColumnContents, each if _ is table then Table.ColumnNames(_) else {}))),
     NewColumnNames = List.Transform(ColumnsToExpand, each ColumnName & "." & _),
     CanExpandCurrentColumn = List.Count(ColumnsToExpand)>0,
     ExpandedTable = if CanExpandCurrentColumn then Table.ExpandTableColumn(TableToExpand, ColumnName, ColumnsToExpand, NewColumnNames) else TableToExpand,
     NextColumnNumber = if CanExpandCurrentColumn then ActualColumnNumber else ActualColumnNumber+1,
     OutputTable = if NextColumnNumber>(Table.ColumnCount(ExpandedTable)-1) then ExpandedTable else ExpandAll(ExpandedTable, NextColumnNumber)
    in
     OutputTable

But how to expand only desired lists/tables?

Query Editor Screenshot update


Solution

  • You should be able to simply put a filter on the old ColumnsToExpand line.

    That is,

     TableColumns = //This is the old ColumnsToExpand definition renamed.
         List.Distinct(List.Combine(List.Transform(ColumnContents, each if _ is table then Table.ColumnNames(_) else {}))),
     ColumnsToExpand =
         List.Select(TableColumns, each (_ = "view" or _ = "viewfolder" or _ = "Attribute:name")),
    

    Or in one line like this,

     ColumsToExpand = List.Select(List.Distinct(List.Combine(List.Transform(ColumnContents, each if _ is table then Table.ColumnNames(_) else {}))), each (_ = "view" or _ = "viewfolder" or _ = "Attribute:name")),