How To Import All Files In A Folder With Power Query

2016-12-09

WARNING!!! This post is full of POWER.

Power Query is a great tool for importing and transforming data in Excel. But unfortunately it’s missing a key feature out of the box to make it truly useful.

In this post we’re going to find out how to import data from multiple files in a folder using Power Query. To do this we will need certain conditions to be true.

  • We’ll need Power Query installed. Read this post to find out how to install it.
  • The data structure in each file must be the same.
    • Same number of columns with the same column headings.
    • Data is on the same sheet name in each file.
  • We will need all the files we want to import located in the same folder.

Step-001-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

For our example, we’re going to import 4 Excel files all from this location.

C:\Users\John\Google Drive - Excel\Excel Website\Power Query\How To Import All Files In A Folder With Power Query\Example

Step-002-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Each file is structure the same way. The column headings are all the same and in the same order. The data is in a sheet called Sheet1 for each file. Only the data is different for each file.

Step 1: Setting up the import query for one file.

Step-003-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Now we will set up the import query for one file.

  1. Go to the Power Query tab in the ribbon.
  2. In the Get External Data section press the From File button.
  3. Choose From Excel in the drop down.

Step-004-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Now choose a file to import. You can choose any of the files in this step as we are creating an import query that will work for all the files and all the files are structurally the same.

  1. Navigate to your folder and select any file.
  2. Press the OK button.

Step-005-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

A preview of your data will appear in the Navigator window.

  1. Select the sheet that contains your data. In our case Sheet1. Check the data preview to make sure you have the correct data.
  2. Press the Edit button.

Step 2: Edit the query.

Step-006-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Power Query will create the import code (in a custom language called M) behind the scenes, but we will need to edit it slightly.

  1. Go to the View tab.
  2. Press the Advanced Editor button.
  3. You will now see the code that has been created for your import.

Step-007-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

We can now edit the M code.

  1. Add the red bits of text into your code.
    
    let GetFiles=(Path,Name) =>
    
    let
        Source = Excel.Workbook(File.Contents(Path&Name), null, true),
        Sheet1_Sheet = Source{[Item="Sheet1",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(Sheet1_Sheet),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Customer ID", Int64.Type}, {"Order ID", Int64.Type}, {"Item", type text}, {"Quantity", Int64.Type}, {"Unit Price", Int64.Type}, {"Total", Int64.Type}})
    in
        #"Changed Type"
    
    in GetFiles
  2. Press the Done button.
  3. Rename the query to functionGetFiles.
  4. Go to the Home tab.
  5. Press the Load & Close button.

We have just changed the query to a function that takes a file path and name as inputs then returns the data from that file path and name.

Step 3: Create a query on the folder containing your files.

Step-008-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Now we will create a query on the folder containing all our files.

  1. Go to the Power Query tab.
  2. Press the From File button.
  3. Choose From Folder in the drop down.
  4. Browse to or enter the path of the folder.
  5. Press the OK button.

Step-009-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

This type of query outputs data about all the files in a folder such as the file name, location, date modified etc… A list of your files will be previewed and we can then press the Edit button if this preview looks ok.

Step 4: Add a column with your custom function.

Step-010-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Now we will add a column to this query.

  1. Go to the Add Column tab.
  2. Press the Add Custom Column button.
  3. Change the name of the column to GetData.
  4. Enter this formula into the Custom column formula.
    =functionGetFiles([Folder Path],[Name])
  5. Press the OK button.

This will call the function we created in step 2.

Step-011-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Now we need to expand the GetData column we just created to show its results.

  1. Click on the expand and filter icon in the column heading of our new GetData column.
  2. Select the expand radio button.
  3. Press the OK button.
  4. Now go to the Home Tab.
  5. Press the Close & Load button.

Step-012-How-To-Import-All-Files-In-A-Folder-With-Power-Query How To Import All Files In A Folder With Power Query

Now our data will be imported from all the files in our folder and combined into one table. If we add files to our folder later on, we can import these also by simply refreshing the query. Wow, the POWER!

  1. Here is our data from all 4 files combined into the same table.
  2. If we add files to our folder and want to import these as well, go to the Data tab.
  3. Press the Refresh All button.

About the Author

John MacDougall

John MacDougall

John is a Microsoft MVP and freelance consultant and trainer specializing in Excel, Power BI, Power Automate, Power Apps and SharePoint. You can find other interesting articles from John on his blog or YouTube channel.

Subscribe

Advertisement

Related Articles

Comments

19 Comments

  1. John

    Can you do this with .csv files?

    Reply
    • John

      Yes, but in step 1 select From CSV instead of From Excel. The rest of the steps will be the same.

      Reply
      • John

        This doesn’t seem to work on Excel 2016. It asks to provoke a parameter, am I missing something?

        Also, where does the Path&Name in this sequence Source = Csv.Document(File.Contents(“filepath\filename.csv”),[Delimiter=”,”, Columns=4, Encoding=1252, QuoteStyle=QuoteStyle.None]), go?

        I appreciate it!

        Reply
        • John

          I tried it out and it worked fine for me with CSV files. My Advice is start over and follow along step by step as sometimes the error that was made becomes a blind spot.

          This was the M code I had for the function.

          let GetFiles=(Path,Name) =>

          let
          Source = Csv.Document(File.Contents(Path&Name),[Delimiter=”,”, Columns=6, Encoding=1252, QuoteStyle=QuoteStyle.None]),
          #”Promoted Headers” = Table.PromoteHeaders(Source),
          #”Changed Type” = Table.TransformColumnTypes(#”Promoted Headers”,{{“Customer ID”, Int64.Type}, {“Order ID”, Int64.Type}, {“Item”, type text}, {“Quantity”, Int64.Type}, {“Unit Price”, Int64.Type}, {“Total”, Int64.Type}})
          in
          #”Changed Type”

          in GetFiles

          Reply
  2. LH

    Hello, I am getting the following message after trying to enter the custom column:

    “Expression.Error: The name ‘functionGetFiles’ wasn’t recognized. Make sure it’s spelled correctly.”

    Reply
    • John

      Yes, make sure it’s spelled exactly the same in the function query name as it is when you call it in the custom column. Use copy and paste to make sure it is the same.

      Reply
  3. Sophy

    Hello John,

    I’ve followed your guide step by step 3 times (download till finish Step 4 > Expend > Close & Load), and I got those data, but error message also come : “Initialization of the data source failed. Check the database server or contact your database administrator. Make sure the external database is available, and then try the operation again. If you see this message again, create a new data source to connect to the database.”

    PS: – Ms. Excel 2016
    – i didn’t try M code that you replied on 2017-01-22 at 10:42 . and didn’t try another article : How To Import Multiple Files With Multiple Sheets In Power Query

    Reply
    • John

      It sounds like an issue with access to the folder you’re trying to use. Try copying the folder to your desktop and use that location to pull the files from instead.

      Reply
  4. Kristine

    First off, WOW!! Thank you so much. It is my first time really using the PowerBI ( though I have a book and some video lessons to follow up) and I feel my life is about to change, for the better. I did have to figure out that I should ignore the parameters, and a few other things but no big. I think it might be that things have been changing at lighting speed over at MS.

    However, I do have a question about how to handle this with almost similar invoice, (a few columns are different) and therefore pull up as an error. How would I be able to almost do an if function or just a skip if not there?

    Reply
    • kristine

      Apologies when I mean invoices, its because it is the xml docs I am trying to convert. So really I should have said any documents that are slightly different columns/format.

      Reply
    • John

      Yes, power query is awesome and still amazes me with what it can do.

      I’m not sure I really understand your problems. Power query does have an XML parser, so I take it you’re using that and then trying to combine the results from a bunch of these files but some are missing columns?

      It definitely sounds like a good blog post topic. Unfortunately, I don’t know the solution off hand. I did recently write a post about a similar situation that you may find useful. I encountered missing columns but wasn’t dealing with XML or combining data from multiple files in a folder.

      https://www.howtoexcel.org/power-query/how-to-deal-with-changing-data-formats-in-power-query/

      Reply
  5. marisa

    WOW!
    Impressive article. Thank you so much. I was able to load a big amount of data using get data From Folder but the automatic code generated is so complex that it was difficult for me to do any kind of transformation to the data afterwards.
    This way is perfect. M code is simple and controlled and I can do any kind of transformations first to the single file import and after, to the whole input.

    Reply
    • John

      Yep, power query is awesome! Thanks Microsoft for making an amazing product.

      Reply
  6. DG

    I love the tool, Is there any way to get around the query failing when there is a file open in the folder? (one out of 180)

    Reply
  7. MarkV

    This was a great lesson in power query but i have a slightly different scenario that i would like to apply this to but can’t seem to get it.

    i have a csv file for every day of the month name for the date in the same folder, for example 2018.09.01.csv, 2018.09.02.csv, etc… .

    I would like to load the data from each one of these files into a different worksheet using the same query.

    so my first worksheet, called Summary, in column A had the dates in the same format as the filename, so A2=2018.09.01, A3=2018.09.02, etc.. the next sheet is named 1 for first day of month, the next one named 2, etc…. My summary worksheet will have additional columns with functions that will summarize the data from all the other day of month worksheets

    I would like to have 1 power query that uses the values in column A as the file source to populate all the other worksheets. so in a new month i just have to change the month in column A from 09 to 10 in this example. so the Worksheet for day of month 1, also named 1, will will use the value in A2 as the source filename in the query, worksheet 2 will use A3 as source filename, etc…

    I understand the the queries may need to be unique in each day of month worksheet to reference the correct cell is summary and i don’t mind defining it once in each of the 31 worksheets but i don’t want to have to change all 31 worksheets power query every month, just change the month in column A of the summary once a month.

    Any help is greatly appreciated.

    Reply
    • John

      You need to set up a parameter table. Create the query and in the last step filter on the correct day. Copy and paste that query 31 times and then reference each parameter for the filter.

      I’m always curious why people separate data. Maybe a better approach is to use load all the data into a pivot table and then you can look at whatever part you want in a dynamic way?

      Either way good luck with it!

      Reply
  8. Dat Nguyen

    Hi John, I am using Excel 2016. The section where you create a query on the folder containing all files. You are seeing:
    Load, Edit and Cancel

    For me, I am unable to see Edit, all I am seeing are:
    Combine, Load, Transform and Cancel. There is no Edit so I am unable to filter out the unwanted data file of different type.
    I tried selected Transform and it brings up the Power Query Window but not matter what I selected in the Power Query window, nothing happens, Query window seems to freeze and I have to kill the task with Ctrl-Alt-Delete

    Do you know why?

    Reply
    • John

      Yes, they updated the UI since I wrote this post. Transform is the new Edit button. You can also click on the combine button and choose combine and edit (also new).

      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Get The Latest News

Follow Us

Follow us on social media to stay up to date with the latest tips in Excel!

Pin It on Pinterest

Share This