Combine or Append Data from Files

Combine or Append Data from Files

Author: Skillwave Training

The Scenario

If you ever need to:

  • Append Data,
  • Consolidate Data, or
  • Combine Data

that comes from either an Excel, text, or CSV file, then this is the best solution for you to do so.

In this pattern you’ll get the most optimal and easiest way to combine your files from an specific folder and combine them all together if you’d like. That’s right! Combine data from text, CSV, and Excel files all together. There are no limits on the size of the file or how many files you’d like to combine – it’ll simply work!

Our Goal

AppendGoalWhat we need is a way to extract all the data from our files like:

  • CSV Files
  • Text Files
  • Excel Files

and then somehow consolidate or append data in one tall table. This was a rather complex scenario that we could solve with VBA or SQL, but now we have a more efficient and user friendly way of doing this. Don’t forget to download the workbook in order to follow along!

Step 1: Explaining the Files

Let’s say you have a list of files as shown in the image above, inside a folder called PQExample which is basically the folder where we’re going to point our Power Query solution to work on. The file that contains the actual Power Query solution is called Ultimate Combination.xlsx.

Overall, the files all share the same column header names:

  • Product
  • Date
  • Gross Sales
  • Amount

Now we can head over to the real Pattern.

Step 2: Find the Query that does the Magic

Once you open the Ultimate Combination.xlsx file, you’ll notice that it has no data. The Power Query solution has been stored as a connection only and its awaiting your command to load its data to your Excel workbook. In order to view this query, you’ll need to go to the Power Query ribbon, click on the Show Pane icon and then on the right side you’ll see the Query Pane with a query called Ultimate Combination. Right click that query and then click on Edit to open the Query Editor Window and analyze the solution.
You’ll immediately notice that there is an error with the query, but don’t be alarmed. The reason behind such error its because the solution is pointing at my (Miguel) local folder instead of yours. In order to fix that you’ll need to head over to the first step called Source and click on the gear icon right next to it. That should pop up a new window with a user friendly folder browser. Go ahead and find the folder called PQExample.
FromFolderAnd once you do that, you’ll notice that the solution will start to run and do its magic.

You could end it here and call it a day since all the files were combined already (click on the step called Expanded to see the final result), but instead, we’re going to show how simple creating a solution like this was.

Understanding the Query

Instead of writing a long paragraph, we’ve divided this into sections so you can understand each step of the query on its own.


The way that we start the query is by selecting the folder where all my files are stored. This is easily done through the Power Query Ribbon as shown in the next picture:
FromFolderPQOne thing to take in consideration is that Power Query will also grab the files from any subfolder, but you can filter those out by using the Path field.

Get the files

In this step we simply filter the file extension file so we only get the following extensions:

  • extension equals .csv
  • extension equals .txt
  • extension begins with .xls

The way that you’d do this is by selecting the filter icon from the field and simply do a filter like you’d normally do in Excel.FilterField

Remove Other Columns

In this case, we’ll be removing some columns that we don’t need. However, instead of selecting the columns that we don’t want, we’ll be selecting the ones that we want and tell Power Query that we just want to keep those. Take a look at the following picture to find the button that does the trick but make sure that you first select the columns that you want to keep.


Here’s where we’ll need to get to know a bit about Power Query functions. We know that we have some Excel files in our query but, how do we extract the data from them?

Take a look at the columns that we have available. You’ll notice that we have a column called Content that holds a binary. That binary is the actual Excel file and in order to interpret that binary we need a function called Excel.Workbook(). 
Using the following formula:
if Text.StartsWith([Extension], ".xls") then Excel.Workbook( [Content]) else null

we get a new column that is basically the one that shows me all the data that the Excel file (on each row) holds.
You can click on any of the Table values found on the Custom column to find out what’s inside of each of them.
More often, we deal with 3 different kinds of Data inside an Excel Workbook:

  1. A Sheet
  2. A Table
  3. A Named Range

Note: You’ll notice that in some files we’ll have tables, sheets and in others we’ll only have sheets. This is the moment where we define if we just want to combine the tables, the sheets, the named ranges or a combination of them. Be sure to check that you’re not combining the same data twice as a table is part of a sheet and could potentially get combined in the wrong way.


Now we need to expand that Custom column so we can get all the Excel data in our Query and choose the ones that we want.
ExpandExcelThe result of that gives us 4 new columns:

  • Custom.Data = the actual data found inside the Excel workbook (represented as a table)
  • Custom.Name = the name of the worksheet where the data is stored
  • Custom.Item = this is the name of the item, if it’s a named Range then it’ll be the name of that range, for Sheets then it’ll be the name of the Sheet and for Tables it’ll be the name of the table
  • Custom.Kind = it’s the name of the object that was found from the excel workbook. Most commons are Sheet, Table and DefinedName

The Formula and Other Steps

So far we managed to extract the data from the Excel workbook into objects. Now we need to find a way to extract the data from the CSV and TXT file and being able to combine that with the data found in the Excel file.

We’ll create a new column with this formula that will do the trick:

if [Extension] = ".csv" then
else if [Extension] = ".txt"
then Table.PromoteHeaders(Csv.Document([Content],null,"," ))
else if [Custom.Kind] <> "Table"
then Table.PromoteHeaders([Custom.Data])

Note: we are assuming that the txt file is delimited by a comma, but you can change that by changing the comma in this line of code for something else like a pipe (|), bars (/), semicolon or other.
Csv.Document([Content],null,"," ))

The result of that formula gives us a column that holds only tables with the correct headers. You might be tempted to expand this column right now, but we won’t do that just yet. Instead, we’ll clean the table that we currently have and delete unnecessary columns like Content and Custom.Data since all the data that I need is stored on the Custom column. We will also add a new column that will give us some important information, total row count, about the tables that we’re about to combine. Using this formula we get the total row count for those tables:

And this is what you see at the Almost there step.
Almost there

Dynamically Get a List of All Headers in Files

Fundamentally, that’s what the formula at the MyList step does. It basically grabs all the headers from all the tables found in the previous step, gathers them in a table and then creates a table of distinct values. It later transform that Table into a List as we’ll need that List later. That list will become a parameter so we can dynamically combine all the files regardless if they have all the same structure or not.

A common use case to do something like this is that perhaps we have some columns in some files but that are not present in others, but those columns might be needed for that specific analysis and this MyList pattern does just that. It dynamically creates a unique list of all the headers found thorough all the tables in the previous step.

Here’s the code:

       List.Transform(#"Almost there"[Custom], 

In order to insert this code you’ll need to create a custom step. You can create a custom step by clicking on the fx icon in the formula bar. Once you activate that custom step, you’ll have to paste the code above to make it work.

This is a custom code that:

  1. Converts the column of the previous table that has the “Table” values into a list with just table values
  2. What List.Transform does it that it transforms that list into a List of Lists where each list inside that List contains the column names of a specific table
  3. List.Combine does just that – it combines all of the lists into a single single
  4. List.Distinct is a function that simply remove the duplicated values from a list in order to keep unique values.

This is BY FAR the most efficient way to extract all of the column names from a list of tables. We need this specific list of column names for the final steps.

The Final Steps

The 2 final steps:

  • Here we go
  • Expanded

The Here we go step simply does some renaming on the columns by just double clicking the name of those columns and the Expanded just simply expands the Custom column by simply clicking on the opposite arrows icon next to the name of that column.

The result of this solution / query should look like this:
Load To
All you have to do now is select where you want to load this, either to a Worksheet or your Data Model!


Merge Tables

Merging Tables

Author: Skillwave

The Scenario

If you’ve worked with Excel for any length of time, it’s almost certain that you’ve ended up with one table that has your base information, and a few more tables that contain related records. We call those other tables “lookup” or “reference” tables as they contain the missing information that we often want to pull into our main data table, allowing us to make better use of Excel’s rich toolsets. This process is commonly called enriching a table or de-normalizing a table, and is solved by most Excel users via a combination of formulas including:

  • HLOOKUP, or
  • a combination of INDEX/MATCH functions.

This time, we’re going to create a dynamic process with Power Query that runs faster and is more intuitive than VLOOKUP. So prepare to say goodbye to the VLOOKUP era and say hello to Power Query for Excel

Our Goals

We have three single tables that we want to merge together:

  1. An Orders table containing the products that were purchased in each sale, as well as the date and the price of the components that were sold,
  2. A Products table containing a list of products and their attributes, and
  3. A Customer table containing information about each unique customer.

Our goal is to merge all three tables using the Orders table as our base, adding the related records and attributes from the other two tables to each row from the Orders table. Our end result will be one large table with all the related columns housed together.

Step 1: Get the Data into Power Query

In our scenario, our data is already highly organized for us, with all tables defined as tables in Excel. So our next step is to take advantage of that, and create pointers to those tables inside Power Query.

In order to reference those tables in Power Query we:

  1. Click any cell in the Orders table
  2. Select the Power Query tab
  3. Click on the From Table button
  4. Once the Power Query Editor window pops up, click the bottom half of the Close & Load button, then choose Close & Load To…
  5. Now we get a new window that will let us choose where to load the Data. Select Only Create Connection and click OK
  6. Repeat steps 1-5 for the Products and Customers tables


Step 2: Merging Magic – Merge Tables Together!

For this second part all we have to do is reference our base table (or query) and in this case we’re going to use our Orders table as our base.

We go to the Power Query tab and select Show Pane so we can see the Query Pane on our right hand. Then we right click on the Orders query and select Reference.

This essentially just pulls the results of the first query into a completely new query, which you’ll see in the Query Pane as Orders (2). Right click that new query and choose Edit to start the merging process.

Once you’re in the Power Query Editor Window, click the Merge button. This will pop up a new window that will guide us through the process of merging our tables together.

We need to define which table to merge with our current table and which columns contain the info to be matched.

This is the tricky part of the merge. Like working with VLOOKUP, we are trying to take a table that has a column with many values in it, and look up those values in a column that has a unique list of values. It’s important that your base query starts as the “many” side of the relationship, and that your “lookup” column is the “one” side of the relationship.

In this case our Orders table has many products in it, but our Products table has a unique list of products. So in the bottom portion of the window, we’ll choose to merge the Products table with our base table (Orders).

Next we need to identify the column that is common between the two tables (ProductID in this case). Then we simply select the ProductID columns in both tables so that they are highlighted, and click OK.
Merge example

Repeat the same process to Merge the Customer table on the CustomerID column as shown in the picture above. The result should look a bit like this:

As you can see from the picture above, we added two columns containing the word Table in a green font. But it’s more than just a word… these are actually truly tables that contain each row of data from the corresponding rows of the Customer and Products Table!

We can peek inside by clicking the white space beside the word table, or we can expand those tables so we can get the columns from each.

Now that we know what’s inside of those table values for each row, let’s expand them into columns. Simply click on the directional arrows icon next to the name of the column to Expand the column, as shown in the following image:

From the picture above, you can see that you are able to choose which columns you want to keep, and which you don’t want. (Un-check the box that states Use original column name as prefix, or you’ll get columns named NewColumn.ProductID instead of just ProductID!)

Expand the other column as well – and don’t forget to un-check the Use original column name as prefix box again if it’s checked.

The final step of our cleanup is to force the Date column’s data type. Select the Date column, go to the Home tab, and set the data type to Date:


Step 3: Load it to Excel!

And that’s it! All you have to do now is go to the Home tab, click Close & Load and choose where to land your output (an Excel Worksheet or the Data Model.)

Check the Results Worksheet in the sample file to see the output of the query as constructed in this pattern.