Convert column to cell string Power Query

假装没事ソ 提交于 2020-01-16 05:14:08

问题


I need to fit all the values of a column in Power Query into a 1-cell string separated by commas, as the example below:

To do this, I have the following piece of code:

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Transposed Table" = Table.Transpose(Source),
    #"Merged Columns" = Table.CombineColumns(#"Transposed Table",{"Column1", "Column2", "Column3"},Combiner.CombineTextByDelimiter(",", QuoteStyle.None),"Merged"),
    #"KeepString" = #"Merged Columns"[Merged]{0}
in
    #"KeepString"

The problem with this code is that it assumes there will always be 3 columns, which is not always the case. How can I merge all columns (regardless of how many there are) into one?


回答1:


You can do this with List.Accumulate:

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    KeepString = List.Accumulate(Source[User], "", (state, current) => if state = "" then current else state & "," & current)
in
    KeepString

You can also use Table.ColumnNames to get the list of all the column names. You can pass this into Table.CombineColumns, so your modified solution would be:

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Transposed Table" = Table.Transpose(Source),
    #"Merged Columns" = Table.CombineColumns(#"Transposed Table", Table.ColumnNames(#"Transposed Table"),Combiner.CombineTextByDelimiter(",", QuoteStyle.None),"Merged"),
    #"KeepString" = #"Merged Columns"[Merged]{0}
in
    #"KeepString"



回答2:


You can also use a shorter code:

let
    Source=Excel.CurrentWorkbook( {]Name="Table1"]}[Content],
    Result = Text.Combine(Source[User], ",")
in
    Result


来源:https://stackoverflow.com/questions/33111443/convert-column-to-cell-string-power-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!