Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
5 years ago
Solved

Calculate Week number difference in header column

Hello   I'm receiving Excel files every weeks with some columns named for example "Feb 15", "Feb 21", etc. (5 columns having this format). As time forwards, the first column is every week shifted ...
  • Jimmy801's avatar
    5 years ago

    Hello Anonymous 

     

    It's not 100% clear what you need. But if you have a table with all column names that can be transformed in dates and you would like to use the first column as as start and rename the other with the time distance in weeks then you can use this approach. But bear in mind that you will have problems whenever you have

    - other column names that are not dates and should not be considered in the renaming

    - if you have another date-format (like Feb 15) you need to find a way to transform your date into a week

    - when you are crossing a year, my approach will not work anymore

    Here the code

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTICYmOl2FgA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"15.02.21" = _t, #"22.02.21" = _t, #"02.03.21" = _t]),
        GetFirstColumnAsDate = Date.From(Table.ColumnNames(Source){0},"de-DE"),
        GetRenamedColumns = Table.TransformColumnNames
        (
            Source,
            (columnName) => if Date.From(columnName, "de-DE") = GetFirstColumnAsDate then columnName else "W+" & Text.From(Date.WeekOfYear(Date.From(columnName))-Date.WeekOfYear(GetFirstColumnAsDate))
        )
        
    in
        GetRenamedColumns

    before

    after

    Copy paste this code to the advanced editor in a new blank query to see how the solution works.

    If this post helps or solves your problem, please mark it as solution (to help other users find useful content and to acknowledge the work of users that helped you)
    Kudoes are nice too

    Have fun

    Jimmy