Certainly! If you want to combine files from the same folder in Power Query (M-Code), you can follow these steps either through the Power BI interface or write/edit the M code manually. Combining files is useful when you have multiple files (like Excel, CSV, etc.) in one folder and want to consolidate them into one table.
I'll walk you through both the concept and show you an example M-code you can use or adapt.
🔄 Overview: Combine Files from a Folder
- Use Power Query's "Folder" connector.
- Filter for the files you want (optional).
- Extract the content from each file.
- Transform if necessary (e.g., promote headers).
- Combine the results into one table.
✅ Steps in Power Query UI (Behind the scenes in M-Code):
- Go to Home > Get Data > Folder.
- Browse to select your target folder.
- Power Query will return a table with file metadata.
- Click Combine or manually expand the
Content column.
✍️ Example M-Code
Here's an M-code example for combining multiple CSV files in the same folder:
let
// Step 1: Get all files from the folder
Source = Folder.Files("C:\Users\YourName\Documents\MyFolder"),
// Step 2: Filter only CSV files (optional)
FilteredFiles = Table.SelectRows(Source, each Text.EndsWith([Name], ".csv")),
// Step 3: Import each file as a table by accessing its content
AddedCustom = Table.AddColumn(FilteredFiles, "Data", each Csv.Document([Content], [Delimiter=",", Columns=5, Encoding=65001, QuoteStyle=QuoteStyle.None])),
// Step 4: Optional - Promote headers for each imported table
PromotedHeaders = Table.TransformColumns(AddedCustom, {"Data", each Table.PromoteHeaders(_, [IgnoreErrors=true])}),
// Step 5: Combine (expand) all the individual tables into one
CombinedData = Table.Combine(PromotedHeaders[Data])
in
CombinedData
🔧 Customization Notes:
- Replace
"C:\Users\YourName\Documents\MyFolder" with your actual path.
- Adjust delimiter, encoding, or number of columns if you're importing CSV files.
- If you're loading Excel files, you’ll want to use
Excel.Workbook([Content]) instead of Csv.Document(...).
🧩 Example with Excel Files (with single sheet):
let
Source = Folder.Files("C:\Users\YourName\Documents\ExcelFiles"),
Filtered = Table.SelectRows(Source, each Text.EndsWith([Name], ".xlsx")),
AddCustom = Table.AddColumn(Filtered, "Data", each Excel.Workbook([Content])),
ExpandSheets = Table.ExpandTableColumn(AddCustom, "Data", {"Data", "Name"}, {"Data", "SheetName"}),
Combined = Table.Combine(ExpandSheets[Data])
in
Combined
🏁 Final Tips
- Be mindful of inconsistent headers or structure across files.
- Consider adding a column using file name to track origin:
WithFileName = Table.AddColumn(CombinedData, "SourceFile", each [Name])
- You can also filter by file name, date, or folder path if needed.
Would you like a version tailored for Excel files with multiple sheets or only specific sheet names?