Sub topic 2
Importing from an Excel table, a CSV file, and other sources
This chapter covers how to bring data into Power Query from an Excel table, a CSV file, and a few other common sources. It assumes you can work with Excel tables and know the basic data types (text, number, date). It also assumes you have seen the Power Query Editor, which later chapters cover in more detail.
The Get Data entry points
All imports start on the Data tab, in the Get & Transform Data group. Each source type has its own command. The command you pick decides which connector runs. A connector is the component that knows how to read one kind of source.
| Source | Where to find it | Connector function in M |
|---|---|---|
| Excel table or named range in this workbook | Data > From Table/Range | `Excel.CurrentWorkbook` |
| Another Excel workbook | Data > Get Data > From File > From Workbook | `Excel.Workbook` |
| CSV or text file | Data > From Text/CSV | `Csv.Document` |
| Folder of files | Data > Get Data > From File > From Folder | `Folder.Files` |
| Web page | Data > From Web | `Web.BrowserContents` or `Web.Page` |
| Database such as SQL Server | Data > Get Data > From Database | `Sql.Database` |
Each command opens a preview dialog or the Navigator. From there you can choose Load to send the data straight to a worksheet, or Transform Data to open the Power Query Editor first. For anything that needs cleaning, choose Transform Data.
Importing from an Excel table
An Excel table is a range you have turned into a table with Ctrl+T. A table has a name, such as SalesRaw, and it grows when you add rows. This makes it the most reliable source inside a workbook.
- Click any cell inside the table.
- Choose Data > From Table/Range.
- The Power Query Editor opens with the table loaded.
If your data is a plain range, Excel offers to convert it to a table first. Accept this. A plain range is fixed, so a query reading it would miss new rows.
Power Query reads the table through Excel.CurrentWorkbook. The first step it records looks like this. The second step then sets data types and the third cleans the Region text.
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"Date", type date}, {"Amount", type number}}),
Trimmed = Table.TransformColumns(Typed, {{"Region", each Text.Trim(Text.Clean(_)), type text}})
in
TrimmedThe expression {[Name="SalesRaw"]}[Content] picks the item named SalesRaw from the list of tables and ranges in the workbook, then takes its contents. The query finds the table by name. If you rename the table in Excel, the query breaks, so rename tables before you build queries on them.
Excel table gotchas
- Headers come through as headers. A table already knows its header row, so no promotion is needed.
- Types are not guessed from the table. Power Query reads the column values and may mark everything as
any. Set types yourself, as in the second step above. - Calculated columns arrive as values. The query reads results, not formulas.
- Loading back to the source table causes a loop. Do not load a query result onto the sheet that holds its own source table, and never into the source table itself.
Importing from a CSV file
A CSV file is a plain text file where each line is a row and commas separate the columns. Use Data > From Text/CSV and pick the file. A preview dialog shows three settings you should check every time.
- File Origin is the text encoding. Most modern exports use UTF-8. If you see odd characters such as
éwhereéshould be, change this setting. - Delimiter is the character between columns. It is a comma for most files, but semicolon or tab files are common in regions that use a comma as the decimal mark.
- Data Type Detection controls whether Power Query guesses types from the first 200 rows or the whole data set. The default sample can guess wrong when later rows differ from the first ones.
Choose Transform Data to continue. The recorded query looks like this:
let
Source = Csv.Document(File.Contents("C:\Data\sales.csv"), [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv]),
Promoted = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
Typed = Table.TransformColumnTypes(Promoted, {{"OrderID", Int64.Type}, {"Amount", type number}})
in
TypedEncoding=65001 is the code for UTF-8. QuoteStyle.Csv tells the reader that a quoted field may contain commas or line breaks. Table.PromoteHeaders turns the first row into column names.
CSV gotchas
- Leading zeros disappear. An ID such as
00123becomes123if Power Query types the column as a number. Set that column to text before any numeric conversion happens, or remove the automatic type step and set it yourself. - Hard-coded paths break on other computers.
C:\Data\sales.csvworks only where that path exists. The later chapter on parameters shows how to make the path easy to change. - Locale affects numbers and dates.
1.234,56is read as text in a US locale. The data types chapter covers the Using Locale option.
Importing from other sources
The same pattern applies to other sources. You choose a connector, the preview shows what is available, and you pick Transform Data.
Another Excel workbook
Use From Workbook. The Navigator lists every sheet, table, and named range in that file. Pick a table when one exists, because a table has real headers and grows with the data. A sheet is a weaker choice, since it includes blank rows and needs its header row promoted.
A web page
Use From Web and paste the URL. The Navigator lists the tables it found on the page. Web pages change layout without notice, so a web query can stop working even when your steps are correct.
A database
Choose a database connector and enter the server and database names. You are asked for credentials the first time. A database import has one major benefit. Many steps you add are translated into a query that the database runs itself. This is called query folding, and a later chapter covers it.
Credentials and privacy
The first time you connect to a source, Excel asks how to authenticate. It stores the answer per source. You can review or clear stored credentials under Data > Get Data > Data Source Settings. If a refresh later fails with an access error, this is the first place to look.
Privacy levels may also appear when you combine sources. They stop data from one source being sent to another. Leave them at their defaults unless you have a clear reason to change them.
How the pieces fit together
Choosing the right source
Common errors when importing
- "Expression.Error: The key didn't match any rows in the table." The table or sheet name in the Source step no longer exists. Open the step and correct the name.
- "DataSource.Error: Could not find file." The path is wrong or the file is moved. Edit the path in the Source step.
- Everything lands in one column. The delimiter is wrong. Reopen the Source step and change the delimiter.
- Garbled characters. The encoding is wrong. Change File Origin.
- A column shows errors after typing. Values in that column do not fit the type. Look at the offending rows before you change the type again.
Exercise
A CSV export contains an OrderID column with values such as 00457. After import, the IDs show as 457. What went wrong, and how do you keep the leading zeros?
Show answer
Power Query typed the column as a number, which drops leading zeros. Set the OrderID column to text, either by removing the automatic type-detection step and setting the type to Text yourself, or by changing the type to Text on the step that follows the header promotion. Do this before any step that converts the column to a number.
Exercise
You built a query on an Excel table named SalesRaw. A coworker renames the table to Sales_Raw. What error do you expect on refresh, and where do you fix it?
Show answer
The refresh fails because the Source step looks up a table named SalesRaw, which no longer exists, so you get an error that the key didn't match any rows. Open the Source step in the Applied Steps list and change the name in the formula to Sales_Raw.