Sub topic 17
Combining All Files in a Folder
This chapter assumes you can already append queries with the same columns, import a CSV file with Get Data, and read Applied Steps. You will use those skills to load every file in a folder as one table. When a new file arrives, a refresh adds it.
Why use a folder query
Appending two queries works when you know how many files exist. It stops being practical when a new monthly export lands in a folder every month. A folder query reads the folder's file list, applies one set of cleaning steps to each file, and appends the results. You never edit the query to add a file.
The working model
Folder.Files returns a table with one row per file. The Content column holds each file's raw bytes as a binary value. Other columns include Name, Extension, Date modified, and Folder Path.
The combine process does four things:
- List the files in the folder.
- Parse each
Contentvalue into a table, using a sample file as the model. - Apply your cleaning steps to every parsed table.
- Append all the tables into one result.
Using the built-in Combine command
- Go to Data > Get Data > From File > From Folder.
- Choose the folder and select OK.
- In the preview, select Combine & Transform Data.
- Choose the sample file (the first file by default) and check the delimiter and encoding. Select OK.
Excel creates several objects in the Queries pane, usually grouped in a folder named after your query:
| Object | What it is | When you edit it |
|---|---|---|
| Parameter (Sample File Parameter) | Holds the file that serves as the sample | Rarely |
| Sample File | A query that returns one file's content | Rarely |
| Transform Sample File | The cleaning steps for one file | Often |
| Transform File (function) | The same steps wrapped as a function | Never directly |
| Your main query | Calls the function for every file and appends the results | For steps that apply to the combined table |
The main rule is this: put per-file steps in Transform Sample File, and put steps for the combined table in the main query. Transform Sample File is the usual place to promote headers or remove a title row that appears at the top of every file. The function reflects any change you make there, so every file gets the change.
Steps such as setting types, removing duplicates across all files, and adding totals belong in the main query. Duplicates between files cannot be found if each file is cleaned in isolation.
Writing the query by hand
The built-in command is convenient but creates five objects. For simple CSV folders, one query is easier to read and maintain. This version filters out junk files, parses each one, and records the source file name.
let
Source = Folder.Files("C:\Data\Monthly"),
CsvOnly = Table.SelectRows(Source, each Text.Lower([Extension]) = ".csv" and not Text.StartsWith([Name], "~$")),
Parsed = Table.AddColumn(CsvOnly, "Data", each Table.PromoteHeaders(Csv.Document([Content], [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv]), [PromoteAllScalars=true])),
Kept = Table.SelectColumns(Parsed, {"Name", "Data"}),
Renamed = Table.RenameColumns(Kept, {{"Name", "SourceFile"}}),
Expanded = Table.ExpandTableColumn(Renamed, "Data", {"OrderID", "Date", "Amount"}),
Typed = Table.TransformColumnTypes(Expanded, {{"OrderID", Int64.Type}, {"Date", type date}, {"Amount", type number}})
in
TypedPoints to notice:
Table.AddColumnruns the parse once per row. Each cell inDatathen holds a whole table.Table.ExpandTableColumnnames the columns to keep. Columns not listed are dropped silently.- Types are set after the combine, as the data types chapter advised. Setting them once on the combined table is simpler than doing it per file.
SourceFilelets you trace a bad row back to its file.
For Excel files, replace the parse step with Excel.Workbook([Content], true). This returns a table of sheets and tables inside that workbook, and you then pick the one you want.
Common errors and how to fix them
Temporary files break the refresh
When someone has a workbook open, Excel creates a hidden lock file whose name starts with ~$. It has the .xlsx extension but is not a valid workbook. Parsing it produces an error for that row. The filter on Name in the code above prevents this.
Subfolders are included
Folder.Files returns files from the chosen folder and all subfolders. An Archive subfolder of old exports will be loaded too. Filter on [Folder Path], or use Folder.Contents, which lists only the top level.
let
Source = Folder.Files("C:\Data\Monthly"),
TopLevel = Table.SelectRows(Source, each [Folder Path] = "C:\Data\Monthly\")
in
TopLevelA column is missing or renamed in one file
If a new file has Amt instead of Amount, the expand step fails with an error that the column was not found. Check the file, or fix the header in Transform Sample File only if every file has the problem. Silent data loss is the opposite risk. If you expand only some columns, an extra column in later files is ignored without warning. Review the column list after a new file arrives.
Wrong delimiter, encoding, or locale
The sample file sets the parse options for all files. If one file uses semicolons or a different encoding, its rows will have a single column or garbled text. Keep the exports consistent, or add a filter that routes unusual files to a separate query.
Header row is repeated as data
If you promote headers once after appending, the header rows from files 2 and onward remain as data rows. Promote headers per file, inside the parse step, as the manual example does.
Hard-coded path breaks on another computer
C:\Data\Monthly is stored in the query. A colleague with a different folder gets an error. The parameters chapter shows how to make the path an editable value.
Refreshing and checking the result
Choose Data > Refresh All. Excel lists the folder again, so new files are added and deleted files disappear. Before trusting totals, check the row count and look at the SourceFile column to confirm every expected file appears.
Folder queries do not fold, because the source is a file system and not a database. Every refresh reads every file. For a large folder, that cost grows with each added file. The folding chapter covers performance in more detail.
Exercise
A folder query worked for months. After a refresh, it fails with "The column 'Amount' of the table wasn't found." Name two likely causes and one place to check first.
Show answer
Likely causes: a new file has a renamed or missing Amount column, or a temporary "~$" lock file or a non-data file (for example a different CSV layout) was picked up and parsed. Check the SourceFile column or, if the query fails earlier, the file list in the Folder.Files step, to find which file's headers differ. Then filter that file out or fix the file.
Exercise
You need to remove a three-line title block from the top of every file in a folder, and also remove duplicate OrderID values across all files. Where does each step go in the built-in Combine setup?
Show answer
Removing the title block is a per-file step, so it goes in Transform Sample File. Removing duplicates across files must see all rows together, so it goes in the main query after the append.