我需要将Power Query中列的所有值放入由逗号分隔的1个单元格字符串中,如下例所示:
为此,我有以下代码:
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"
此代码的问题在于它假定总会有3列,但情况并非总是如此。如何将所有列(无论有多少列)合并到一个列中?
答案 0 :(得分:4)
您可以使用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
您还可以使用Table.ColumnNames
获取所有列名称的列表。您可以将其传递到Table.CombineColumns
,因此您修改的解决方案将是:
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"
答案 1 :(得分:2)
您还可以使用更短的代码:
let
Source=Excel.CurrentWorkbook( {]Name="Table1"]}[Content],
Result = Text.Combine(Source[User], ",")
in
Result