Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
2 years ago
Solved

Formatting tables in the same sheet independently

I have this file with multiple tables I want to format and I have the M code to format them. The problem is they have to be formatted individually. Is there a way in power query to separate them into...
  • Anonymous's avatar
    Anonymous
    2 years ago

    I think I have an answer. Now im gonna test it in folders and not just individual files. I will leave my code so far here anyway.

    Let

        // Load the workbook and sheet

        Source = Excel.Workbook(File.Contents("C:\Users\FEM6CLJ\Desktop\Excel\Teste panasonic.xlsx"), null, true),

        Sheet = Source{[Item="Sheet1", Kind="Sheet"]}[Data],

     

        // Remove unnecessary columns

        RemoveColumns = Table.RemoveColumns(Sheet, {"Column1","Column7", "Column8"}),

     

        // Remove blank rows

        RemoveBlankRows = Table.SelectRows(RemoveColumns, each List.NonNullCount(Record.FieldValues(_)) > 0),

     

        // Find the positions where "Machine Name" appears to split the table

        AddIndex = Table.AddIndexColumn(RemoveBlankRows, "Index", 0, 1, Int64.Type),

        MachineNamePositions = Table.SelectRows(AddIndex, each [Column2] = "Machine Name")[Index],

     

        // Function to split and process each sub-table

        ProcessSubTables = (start, end) =>

        let

            SubTable = Table.Range(AddIndex, start, end - start),

            RemoveIndex = Table.RemoveColumns(SubTable, {"Index"}),

            PromoteHeaders = Table.PromoteHeaders(RemoveIndex),

            AddFileName = Table.AddColumn(PromoteHeaders, "File Name", each "Teste panasonic"),

            ReorderColumns = Table.ReorderColumns(AddFileName, {"File Name", "Machine Name", "Table", "Slot", "SubSlot", "Part"}, MissingField.Ignore),

            PivotedTable = Table.UnpivotOtherColumns(ReorderColumns, {"File Name", "Machine Name", "Table", "Slot", "SubSlot", "Part"}, "Part Number", "Value")

        in

            PivotedTable,

     

        // Split the main table into sub-tables based on the positions

        TableRanges = List.Zip({MachineNamePositions, List.Skip(MachineNamePositions,1) & {Table.RowCount(AddIndex)}}),

        ProcessedTables = List.Transform(TableRanges, each ProcessSubTables(_{0}, _{1})),

        // Combine all processed tables

        CombinedTable = Table.Combine(ProcessedTables)

    in

        CombinedTable