按换行符拆分(Power Query)
问题:按换行符拆分,左表拆分成右表
思路1:
let
源 = Excel.CurrentWorkbook(){[Name="表1"]}[Content],
已添加索引 = Table.AddIndexColumn(源, "索引", 0, 1, Int64.Type),
按分隔符拆分列 = Table.ExpandListColumn(Table.TransformColumns(已添加索引, {"列1", Splitter.SplitTextByDelimiter("#(lf)")}), "列1"),
分组的行 = Table.Group(按分隔符拆分列, {"索引"}, {"计数", each Table.AddIndexColumn(_,"辅助",-1,1)}),
展开 = Table.ExpandTableColumn(分组的行, "计数", {"列1", "列2", "辅助"}),
已插入分隔符之间的文本 = Table.AddColumn(展开, "分隔符之间的文本", each Text.BetweenDelimiters([列2], "#(lf)", "#(lf)", [辅助], 0)),
删除的列 = Table.RemoveColumns(已插入分隔符之间的文本,{"索引", "列2", "辅助"}),
重命名的列 = Table.RenameColumns(删除的列,{{"分隔符之间的文本", "列2"}})
in
重命名的列
思路2:
let
源 = Excel.CurrentWorkbook(){[Name="表1"]}[Content],
已添加索引 = Table.AddIndexColumn(源, "索引"),
列1拆分 = Table.ExpandListColumn(Table.TransformColumns(已添加索引, {"列1", Splitter.SplitTextByDelimiter("#(lf)")}), "列1"),
列2拆分 = Table.AddColumn(列1拆分, "拆分列2", each Text.Split([列2],"#(lf)")),
分组的行 = Table.Group(列2拆分, {"索引"}, {"计数", each Table.AddIndexColumn(_, "表内索引")}),
展开组 = Table.ExpandTableColumn(分组的行, "计数", {"列1", "拆分列2", "表内索引"}),
列2提取 = Table.AddColumn(展开组, "提取列2", each List.Range([拆分列2],[表内索引],1)),
展开列2 = Table.ExpandListColumn(列2提取, "提取列2"),
删除的其他列 = Table.SelectColumns(展开列2,{"列1", "提取列2"}),
更改的类型 = Table.TransformColumnTypes(删除的其他列,{{"列1", type text}, {"提取列2", type text}})
in
更改的类型
思路3(可用于多列):
let
源 = Excel.CurrentWorkbook(){[Name="表1"]}[Content],
两列重组 = Table.AddColumn(源, "自定义", each List.Zip({Text.Split([列1],"#(lf)"), Text.Split([列2],"#(lf)")})),
展开 = Table.ExpandListColumn(两列重组, "自定义"),
提取值 = Table.TransformColumns(展开, {"自定义", each Text.Combine(List.Transform(_, Text.From), ":")}),
按分隔符拆分列 = Table.SplitColumn(提取值, "自定义", Splitter.SplitTextByDelimiter(":"), {"新列1", "新列2"}),
删除的其他列 = Table.SelectColumns(按分隔符拆分列,{"新列1", "新列2"})
in
删除的其他列
思路4(可用于多列且每个单元格内分隔符数量不固定):
let
源 = Excel.CurrentWorkbook(){[Name="表1"]}[Content],
已添加索引 = Table.AddIndexColumn(源, "索引"),
逆透视的其他列 = Table.UnpivotOtherColumns(已添加索引, {"索引"}, "属性", "值"),
按分隔符拆分列 = Table.SplitColumn(逆透视的其他列, "值", Splitter.SplitTextByDelimiter("#(lf)"), {"值.1", "值.2", "值.3", "值.4"}),
分组的行 = Table.Group(按分隔符拆分列, {"索引"}, {"内容", each Table.PromoteHeaders(Table.Skip(Table.Transpose(_),1))}),
展开 = Table.ExpandTableColumn(分组的行, "内容", {"列1", "列2", "列3"}),
删除的列 = Table.RemoveColumns(展开,{"索引"}),
已删除的空行 = Table.SelectRows(删除的列, each not List.IsEmpty(List.RemoveMatchingItems(Record.FieldValues(_), {"", null})))
in
已删除的空行