Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
4 years ago
Solved

How to change column names for a query with 200+ columns

Hello, I have a table with about 200 columns, and I do not want to have to manually change all of my entries. About 15 columns are individual, where the column name starts with a unique text st...
  • AlexisOlson's avatar
    4 years ago

    Here's an example that you can paste into the Advanced Editor:

     

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSlTSUaoAYkMQNgASRnqGJkqxOtFKSUBOJUgAiE1BsnqWFkqxsQA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t, Column2 = _t, field_Col3 = _t, field_Col4 = _t, field_Col5 = _t]),
        NewColNames = List.Transform(Table.ColumnNames(Source), each if Text.Start(_, 6) = "field_" then Text.AfterDelimiter(_, "_") else _),
        ChangeColNames = Table.FromColumns(Table.ToColumns(Source), NewColNames)
    in
        ChangeColNames

     

     

    This takes the Table.ColumnNames as a list and transforms is according to the rule you specified. It then splits the table into columns and recombines them back into a table using the new column names.

     

    The key bits of code are the list transformation rule (the underscore represents each column name):

    each if Text.Start(_, 6) = "field_" then Text.AfterDelimiter(_, "_") else _

    and the recombination

    Table.FromColumns(Table.ToColumns(Source), NewColNames)