100% found this document useful (4 votes)
30 views

Download full Data Mashup with Microsoft Excel Using Power Query and M: Finding, Transforming, and Loading Data from External Sources Adam Aspin ebook all chapters

Data

Uploaded by

heisegoudyu6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
30 views

Download full Data Mashup with Microsoft Excel Using Power Query and M: Finding, Transforming, and Loading Data from External Sources Adam Aspin ebook all chapters

Data

Uploaded by

heisegoudyu6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Data Mashup with Microsoft Excel Using Power Query


and M: Finding, Transforming, and Loading Data
from External Sources Adam Aspin

https://textbookfull.com/product/data-mashup-with-microsoft-
excel-using-power-query-and-m-finding-transforming-and-
loading-data-from-external-sources-adam-aspin/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Data Visualization in Excel 2016 Adam Aspin

https://textbookfull.com/product/data-visualization-in-
excel-2016-adam-aspin/

textboxfull.com

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/

textboxfull.com

Analyzing Data with Microsoft Power BI and Power Pivot for


Excel 1st Edition Alberto Ferrari & Marco Russo

https://textbookfull.com/product/analyzing-data-with-microsoft-power-
bi-and-power-pivot-for-excel-1st-edition-alberto-ferrari-marco-russo/

textboxfull.com

Pro Power BI Desktop: Self-service Analytics and Data


Visualization for the Power User 3rd Edition Adam Aspin

https://textbookfull.com/product/pro-power-bi-desktop-self-service-
analytics-and-data-visualization-for-the-power-user-3rd-edition-adam-
aspin/
textboxfull.com
Pro Power BI Desktop Self Service Analytics and Data
Visualization for the Power User Third Edition Adam Aspin

https://textbookfull.com/product/pro-power-bi-desktop-self-service-
analytics-and-data-visualization-for-the-power-user-third-edition-
adam-aspin/
textboxfull.com

Learning Apache Drill Query and Analyze Distributed Data


Sources with SQL 1st Edition Charles Givre

https://textbookfull.com/product/learning-apache-drill-query-and-
analyze-distributed-data-sources-with-sql-1st-edition-charles-givre/

textboxfull.com

Data Analysis with Microsoft Power Bi Brian Larson

https://textbookfull.com/product/data-analysis-with-microsoft-power-
bi-brian-larson/

textboxfull.com

Targeting Using Augmented Data in Database Marketing


Decision Factors for Evaluating External Sources 1st
Edition Bettina Hüttenrauch
https://textbookfull.com/product/targeting-using-augmented-data-in-
database-marketing-decision-factors-for-evaluating-external-
sources-1st-edition-bettina-huttenrauch/
textboxfull.com

Microsoft Excel Data Analysis and Business Modeling 5th


Edition Wayne Winston

https://textbookfull.com/product/microsoft-excel-data-analysis-and-
business-modeling-5th-edition-wayne-winston/

textboxfull.com
Data Mashup
with Microsof t
Excel Using Power
Query and M
Finding, Transforming, and Loading Data
from External Sources

Adam Aspin
Data Mashup with
Microsoft Excel Using
Power Query and M
Finding, Transforming, and
Loading Data from
External Sources

Adam Aspin
Data Mashup with Microsoft Excel Using Power Query and M: Finding,
Transforming, and Loading Data from External Sources
Adam Aspin
Stafford, UK

ISBN-13 (pbk): 978-1-4842-6017-3 ISBN-13 (electronic): 978-1-4842-6018-0


https://doi.org/10.1007/978-1-4842-6018-0

Copyright © 2020 by Adam Aspin


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Jonathan Gennick
Development Editor: Laura Berendson
Coordinating Editor: Jill Balzano
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484260173. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author��������������������������������������������������������������������������������������������������� xiii

About the Technical Reviewer���������������������������������������������������������������������������������xv


Acknowledgments�������������������������������������������������������������������������������������������������xvii

Introduction������������������������������������������������������������������������������������������������������������xix

Chapter 1: Using Power Query to Discover and Load Data into Excel���������������������� 1
Power Query��������������������������������������������������������������������������������������������������������������������������������� 2
The Data Load Process����������������������������������������������������������������������������������������������������������������� 4
Why Use Power Query?����������������������������������������������������������������������������������������������������������������� 7
The Queries & Connections Pane�������������������������������������������������������������������������������������������������� 8
Displaying the Queries & Connections Pane���������������������������������������������������������������������������� 9
The Peek Window�������������������������������������������������������������������������������������������������������������������� 9
Peek Window Options������������������������������������������������������������������������������������������������������������ 10
View in Worksheet����������������������������������������������������������������������������������������������������������������� 11
Deleting a Query������������������������������������������������������������������������������������������������������������������������� 12
Understanding Data Load������������������������������������������������������������������������������������������������������������ 12
The Navigator Dialog������������������������������������������������������������������������������������������������������������� 13
Select Multiple Source Tables����������������������������������������������������������������������������������������������� 15
Searching for Datasets���������������������������������������������������������������������������������������������������������� 15
Navigator Display Options����������������������������������������������������������������������������������������������������� 17
Refresh���������������������������������������������������������������������������������������������������������������������������������� 17
The Navigator Data Preview�������������������������������������������������������������������������������������������������� 18
Modifying Data���������������������������������������������������������������������������������������������������������������������� 19
The Power Query Editor�������������������������������������������������������������������������������������������������������������� 20
Data Sources������������������������������������������������������������������������������������������������������������������������������� 20

iii
Table of Contents

Source Data Properties��������������������������������������������������������������������������������������������������������������� 22


Query Properties������������������������������������������������������������������������������������������������������������������������� 23
Load Destinations����������������������������������������������������������������������������������������������������������������������� 25
Repurposing an Existing Connection������������������������������������������������������������������������������������� 26
Load to Excel������������������������������������������������������������������������������������������������������������������������� 28
Load to the Data Model��������������������������������������������������������������������������������������������������������� 28
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 30

Chapter 2: Discovering and Loading File-Based Data with Power Query��������������� 31


File Sources�������������������������������������������������������������������������������������������������������������������������������� 31
Loading Data from Files�������������������������������������������������������������������������������������������������������������� 33
CSV Files�������������������������������������������������������������������������������������������������������������������������������� 33
Text Files������������������������������������������������������������������������������������������������������������������������������� 37
Text and CSV Options������������������������������������������������������������������������������������������������������������� 38
Fixed-Width Text Files����������������������������������������������������������������������������������������������������������� 40
Simple XML Files������������������������������������������������������������������������������������������������������������������� 41
Excel Files����������������������������������������������������������������������������������������������������������������������������� 43
Why Use Power Query to Connect to Excel��������������������������������������������������������������������������� 47
From Table/Range������������������������������������������������������������������������������������������������������������������ 48
Microsoft Access Databases������������������������������������������������������������������������������������������������� 49
JSON Files����������������������������������������������������������������������������������������������������������������������������������� 51
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 51

Chapter 3: Loading Data from Databases and Data Warehouses��������������������������� 53


Relational Databases������������������������������������������������������������������������������������������������������������������ 54
SQL Server���������������������������������������������������������������������������������������������������������������������������������� 56
Automatically Loading Related Tables����������������������������������������������������������������������������������� 60
Database Options������������������������������������������������������������������������������������������������������������������ 61
Searching for Tables�������������������������������������������������������������������������������������������������������������� 64
Oracle Databases������������������������������������������������������������������������������������������������������������������������ 71
Other Relational Databases��������������������������������������������������������������������������������������������������������� 74

iv
Table of Contents

Microsoft SQL Server Analysis Services Data Sources��������������������������������������������������������������� 76


From Analysis Services��������������������������������������������������������������������������������������������������������� 80
SSAS Tabular Data Warehouses�������������������������������������������������������������������������������������������������� 83
Types of Credentials When Connecting��������������������������������������������������������������������������������������� 87
Unable to Connect����������������������������������������������������������������������������������������������������������������������� 87
Other Database Connections������������������������������������������������������������������������������������������������������� 88
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 88

Chapter 4: Loading Data from the Web and the Cloud�������������������������������������������� 89


Web and Cloud Services������������������������������������������������������������������������������������������������������������� 89
Web Pages����������������������������������������������������������������������������������������������������������������������������� 90
Online Services���������������������������������������������������������������������������������������������������������������������� 90
Microsoft Azure��������������������������������������������������������������������������������������������������������������������� 91
Web Pages���������������������������������������������������������������������������������������������������������������������������������� 91
Advanced Web Options���������������������������������������������������������������������������������������������������������� 93
Viewing the Source Web Page����������������������������������������������������������������������������������������������� 94
Salesforce����������������������������������������������������������������������������������������������������������������������������������� 95
Loading Data from Salesforce Objects���������������������������������������������������������������������������������� 96
Salesforce Reports�������������������������������������������������������������������������������������������������������������� 102
Microsoft Dynamics 365����������������������������������������������������������������������������������������������������������� 102
Azure SQL Database������������������������������������������������������������������������������������������������������������������ 104
Azure SQL Data Warehouse (Azure Synapse Analytics)������������������������������������������������������������ 106
Connecting to SQL Server on an Azure Virtual Machine����������������������������������������������������������� 108
Azure Blob Storage������������������������������������������������������������������������������������������������������������������� 110
Azure Security��������������������������������������������������������������������������������������������������������������������������� 112
Other Source Types������������������������������������������������������������������������������������������������������������������� 113
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 114

Chapter 5: Generic Data Sources�������������������������������������������������������������������������� 115


ODBC Sources��������������������������������������������������������������������������������������������������������������������������� 116
OLE DB Data Sources���������������������������������������������������������������������������������������������������������������� 125

v
Table of Contents

OData Feeds������������������������������������������������������������������������������������������������������������������������������ 129


OData Options���������������������������������������������������������������������������������������������������������������������� 132
Refreshing Data������������������������������������������������������������������������������������������������������������������������ 132
Refreshing the Entire Data in the Excel In-Memory Model�������������������������������������������������� 133
Refreshing an Individual Query������������������������������������������������������������������������������������������� 133
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 134

Chapter 6: Structuring Imported Data������������������������������������������������������������������ 135


Extending Queries in Power Query������������������������������������������������������������������������������������������� 136
Editing Data After a Data Load��������������������������������������������������������������������������������������������� 137
Transforming Data Before Loading�������������������������������������������������������������������������������������� 141
Query or Load?�������������������������������������������������������������������������������������������������������������������������� 141
The Power Query Editor������������������������������������������������������������������������������������������������������������ 143
The Applied Steps List��������������������������������������������������������������������������������������������������������� 144
The Power Query Editor Ribbons����������������������������������������������������������������������������������������� 145
Dataset Shaping������������������������������������������������������������������������������������������������������������������������ 152
Renaming Columns������������������������������������������������������������������������������������������������������������� 153
Reordering Columns������������������������������������������������������������������������������������������������������������ 153
Removing Columns�������������������������������������������������������������������������������������������������������������� 155
Choosing Columns��������������������������������������������������������������������������������������������������������������� 156
Merging Columns���������������������������������������������������������������������������������������������������������������� 158
Moving to a Specific Column����������������������������������������������������������������������������������������������� 161
Removing Records�������������������������������������������������������������������������������������������������������������������� 162
Keeping Rows���������������������������������������������������������������������������������������������������������������������� 163
Removing Duplicate Records���������������������������������������������������������������������������������������������� 166
Sorting Data������������������������������������������������������������������������������������������������������������������������������ 167
Reversing the Row Order����������������������������������������������������������������������������������������������������� 168
Undoing a Sort Operation���������������������������������������������������������������������������������������������������� 168
Filtering Data���������������������������������������������������������������������������������������������������������������������������� 170
Selecting Specific Text Values��������������������������������������������������������������������������������������������� 170
Finding Elements in the Filter List��������������������������������������������������������������������������������������� 171

vi
Table of Contents

Filtering Text Ranges����������������������������������������������������������������������������������������������������������� 172


Filtering Numeric Ranges���������������������������������������������������������������������������������������������������� 173
Filtering Date and Time Ranges������������������������������������������������������������������������������������������� 174
Filtering Numeric Data�������������������������������������������������������������������������������������������������������� 175
Applying Advanced Filters��������������������������������������������������������������������������������������������������� 177
Grouping Records��������������������������������������������������������������������������������������������������������������������� 179
Simple Groups��������������������������������������������������������������������������������������������������������������������� 179
Complex Groups������������������������������������������������������������������������������������������������������������������ 181
Count Rows������������������������������������������������������������������������������������������������������������������������������� 184
Saving Changes in the Query Editor������������������������������������������������������������������������������������������ 184
Exiting the Query Editor������������������������������������������������������������������������������������������������������������ 184
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 185

Chapter 7: Data Transformation���������������������������������������������������������������������������� 187


Viewing a Full Record��������������������������������������������������������������������������������������������������������������� 188
Power Query Editor Context Menus������������������������������������������������������������������������������������������ 189
Using the First Row as Headers������������������������������������������������������������������������������������������������ 190
Changing Data Type������������������������������������������������������������������������������������������������������������������ 192
Detecting Data Types����������������������������������������������������������������������������������������������������������� 195
Data Type Indicators������������������������������������������������������������������������������������������������������������ 195
Switching Data Types���������������������������������������������������������������������������������������������������������� 196
Data Type Using Locale�������������������������������������������������������������������������������������������������������� 197
Replacing Values����������������������������������������������������������������������������������������������������������������������� 198
Transforming Column Contents������������������������������������������������������������������������������������������������� 201
Text Transformation������������������������������������������������������������������������������������������������������������� 201
Adding a Prefix or a Suffix��������������������������������������������������������������������������������������������������� 203
Removing Leading and Trailing Spaces������������������������������������������������������������������������������� 204
Removing Nonprinting Characters��������������������������������������������������������������������������������������� 204
Number Transformations����������������������������������������������������������������������������������������������������� 205
Filling Down Empty Cells���������������������������������������������������������������������������������������������������������� 215

vii
Table of Contents

Extracting Part of a Column’s Contents������������������������������������������������������������������������������������ 218


Advanced Extract Options���������������������������������������������������������������������������������������������������� 219
Duplicating Columns����������������������������������������������������������������������������������������������������������������� 221
Splitting Columns���������������������������������������������������������������������������������������������������������������������� 222
Splitting Column by a Delimiter������������������������������������������������������������������������������������������� 223
Advanced Options for Delimiter Split����������������������������������������������������������������������������������� 225
Splitting Columns by Number of Characters����������������������������������������������������������������������� 226
Merging Columns���������������������������������������������������������������������������������������������������������������������� 228
Creating Columns from Examples��������������������������������������������������������������������������������������������� 229
Adding Conditional Columns����������������������������������������������������������������������������������������������������� 231
Index Columns�������������������������������������������������������������������������������������������������������������������������� 234
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 236

Chapter 8: Restructuring Data������������������������������������������������������������������������������ 237


The Power Query Editor View Ribbon���������������������������������������������������������������������������������������� 238
Merging Data���������������������������������������������������������������������������������������������������������������������������� 239
Extending a Query with Merged Data���������������������������������������������������������������������������������� 240
Aggregating Data During a Merge Operation���������������������������������������������������������������������� 244
Merge as a New Query�������������������������������������������������������������������������������������������������������� 248
Types of Join������������������������������������������������������������������������������������������������������������������������ 248
Joining on Multiple Columns����������������������������������������������������������������������������������������������� 250
Preparing Datasets for Joins����������������������������������������������������������������������������������������������� 252
Correct and Incorrect Joins������������������������������������������������������������������������������������������������� 253
Examining Joined Data�������������������������������������������������������������������������������������������������������� 254
Appending Data������������������������������������������������������������������������������������������������������������������������� 256
Adding the Contents of One Query to Another��������������������������������������������������������������������� 256
Appending the Contents of Multiple Queries����������������������������������������������������������������������� 259
Changing the Data Structure����������������������������������������������������������������������������������������������������� 260
Unpivoting Tables���������������������������������������������������������������������������������������������������������������� 261
Pivoting Tables��������������������������������������������������������������������������������������������������������������������� 263
Transposing Rows and Columns������������������������������������������������������������������������������������������ 265

viii
Table of Contents

Loading Data from Inside the Query Editor Directly������������������������������������������������������������������ 266


Error Display����������������������������������������������������������������������������������������������������������������������������� 267
Removing Errors������������������������������������������������������������������������������������������������������������������ 268
Viewing Errors��������������������������������������������������������������������������������������������������������������������� 268
Data Transformation Approaches���������������������������������������������������������������������������������������������� 269
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 269

Chapter 9: Complex Data Loads���������������������������������������������������������������������������� 271


Adding Multiple Files from a Source Folder������������������������������������������������������������������������������ 272
Filtering Source Files in a Folder���������������������������������������������������������������������������������������������� 275
Displaying and Filtering File Attributes������������������������������������������������������������������������������������� 278
Removing Header Rows After Multiple File Loads�������������������������������������������������������������������� 280
Combining Identically Structured Files������������������������������������������������������������������������������������� 280
Loading and Parsing JSON Files����������������������������������������������������������������������������������������������� 281
The List Tools Transform Ribbon����������������������������������������������������������������������������������������������� 283
Parsing XML Data from a Column��������������������������������������������������������������������������������������������� 284
Parsing JSON Data from a Column������������������������������������������������������������������������������������������� 286
Complex JSON Files������������������������������������������������������������������������������������������������������������ 288
Complex XML Files�������������������������������������������������������������������������������������������������������������������� 294
Convert a Column to a List�������������������������������������������������������������������������������������������������������� 295
Reusing Data Sources��������������������������������������������������������������������������������������������������������������� 296
Pinning a Data Source��������������������������������������������������������������������������������������������������������� 297
Copying Data from Power Query Editor������������������������������������������������������������������������������������ 298
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 299

Chapter 10: Organizing and Managing Queries���������������������������������������������������� 301


Managing the Transformation Process������������������������������������������������������������������������������������� 301
Modifying a Step����������������������������������������������������������������������������������������������������������������� 302
Renaming a Step����������������������������������������������������������������������������������������������������������������� 303
Deleting a Step or a Series of Steps������������������������������������������������������������������������������������ 304

ix
Table of Contents

Discarding Changes������������������������������������������������������������������������������������������������������������������ 305


Modifying an Existing Step�������������������������������������������������������������������������������������������������� 306
Adding a Step���������������������������������������������������������������������������������������������������������������������� 308
Altering Process Step Sequencing�������������������������������������������������������������������������������������� 309
An Approach to Sequencing������������������������������������������������������������������������������������������������ 309
Error Records����������������������������������������������������������������������������������������������������������������������� 310
Managing Queries��������������������������������������������������������������������������������������������������������������������� 310
Organizing Queries�������������������������������������������������������������������������������������������������������������� 311
Grouping Queries����������������������������������������������������������������������������������������������������������������� 312
Duplicating Queries������������������������������������������������������������������������������������������������������������� 314
Referencing Queries������������������������������������������������������������������������������������������������������������ 315
Documenting Queries���������������������������������������������������������������������������������������������������������� 316
Adding a Column as a New Query��������������������������������������������������������������������������������������� 318
Managing Queries from the Queries & Connections Pane�������������������������������������������������������� 319
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 320

Chapter 11: Parameterizing Queries��������������������������������������������������������������������� 321


Parameterizing Queries������������������������������������������������������������������������������������������������������������� 321
Creating a Simple Parameter���������������������������������������������������������������������������������������������� 322
Creating a Set of Parameter Values������������������������������������������������������������������������������������� 324
Creating a Query-Based Parameter������������������������������������������������������������������������������������� 326
Modifying a Parameter�������������������������������������������������������������������������������������������������������� 328
Applying a Parameter When Filtering Records�������������������������������������������������������������������� 329
Modifying the Current Value of a Parameter������������������������������������������������������������������������ 331
Applying a Parameter to a Data Source������������������������������������������������������������������������������� 332
Other Uses for Parameters�������������������������������������������������������������������������������������������������� 334
Using Parameters in the Data Source Step������������������������������������������������������������������������� 334
Applying a Parameter to a SQL Query��������������������������������������������������������������������������������� 335
Query Icons�������������������������������������������������������������������������������������������������������������������������� 337
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 337

x
Table of Contents

Chapter 12: The M Language�������������������������������������������������������������������������������� 339


What Is the M Language?��������������������������������������������������������������������������������������������������������� 340
M and the Power Query Editor�������������������������������������������������������������������������������������������������� 341
Modifying the Code for a Step��������������������������������������������������������������������������������������������� 342
M Expressions��������������������������������������������������������������������������������������������������������������������� 344
Writing M by Adding Custom Columns�������������������������������������������������������������������������������������� 345
The Advanced Editor����������������������������������������������������������������������������������������������������������������� 348
Expressions in the Advanced Editor������������������������������������������������������������������������������������ 348
The Let Statement��������������������������������������������������������������������������������������������������������������� 350
Modifying M in the Advanced Editor������������������������������������������������������������������������������������ 350
Syntax Checking������������������������������������������������������������������������������������������������������������������ 352
Basic M Functions��������������������������������������������������������������������������������������������������������������������� 352
Text Functions��������������������������������������������������������������������������������������������������������������������������� 354
Number Functions��������������������������������������������������������������������������������������������������������������������� 355
Date Functions�������������������������������������������������������������������������������������������������������������������������� 357
Time Functions�������������������������������������������������������������������������������������������������������������������������� 359
Duration Functions�������������������������������������������������������������������������������������������������������������������� 359
M Concepts������������������������������������������������������������������������������������������������������������������������������� 360
M Data Types����������������������������������������������������������������������������������������������������������������������������� 361
M Values������������������������������������������������������������������������������������������������������������������������������������ 362
Defining Your Own Variables in M���������������������������������������������������������������������������������������� 363
Writing M Queries��������������������������������������������������������������������������������������������������������������������� 364
Lists������������������������������������������������������������������������������������������������������������������������������������� 365
Creating Lists Manually������������������������������������������������������������������������������������������������������� 365
Generating Sequences Using Lists�������������������������������������������������������������������������������������� 367
Accessing Values from a List����������������������������������������������������������������������������������������������� 367
List Functions���������������������������������������������������������������������������������������������������������������������� 368
Records������������������������������������������������������������������������������������������������������������������������������� 368
Tables���������������������������������������������������������������������������������������������������������������������������������� 370
Other Function Areas���������������������������������������������������������������������������������������������������������������� 372

xi
Table of Contents

Custom Functions in M������������������������������������������������������������������������������������������������������������� 372


Adding Comments to M Code���������������������������������������������������������������������������������������������������� 374
Single-Line Comments�������������������������������������������������������������������������������������������������������� 374
Multiline Comments������������������������������������������������������������������������������������������������������������ 374
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 375

Appendix A: Sample Data������������������������������������������������������������������������������������� 377


Downloading the Sample Data�������������������������������������������������������������������������������������������������� 377

Index��������������������������������������������������������������������������������������������������������������������� 379

xii
About the Author
Adam Aspin is an independent business intelligence consultant based in the United
Kingdom. He has worked with SQL Server for over 25 years. During this time, he has
developed several dozen reporting and analytical systems based on the Microsoft
Analytics Stack.
Business intelligence has been Adam’s principal focus for the last 20 years. He has
applied his skills for a variety of clients in a range of industry sectors. He is the author
of Apress books: SQL Server 2012 Data Integration Recipes, Pro Power BI Desktop (now
in its third edition), Business Intelligence with SQL Server Reporting Services, and High
Impact Data Visualization in Excel with Power View, 3D Maps, Get & Transform and
Power BI.
A graduate of Oxford University, Adam began his career in publishing before moving
into IT. Databases soon became a passion, and his experience in this arena ranges from
dBase to Oracle, and Access to MySQL, with occasional sorties into the world of DB2.
He is, however, most at home in the Microsoft universe when using SQL Server Analysis
Services, SQL Server Reporting Services, SQL Server Integration Services, and Power
BI—both on-premises and in Azure.
A fluent French speaker, Adam has worked in France and Switzerland for many years.

xiii
About the Technical Reviewer
Karine Aspin is a principal consultant with Calidra Ltd., a UK-based data and analytics
consultancy. A mathematics graduate of the Swiss Federal Institute of Technology,
Karine has worked at a range of IT companies including IBM Global Services.

xv
Acknowledgments
Writing a technical book can be a lonely occupation. So I am all the more grateful for
all the help and encouragement that I have received from so many fabulous friends and
colleagues.
First, my considerable thanks go to Jonathan Gennick, the commissioning editor
of this book. Throughout the publication process, Jonathan has been both a tower
of strength and an exemplary mentor. He has always been available to share his vast
experience selflessly and courteously.
Heartfelt thanks go to Jill Balzano, the Apress coordinating editor, for calmly
managing this book through the production process. She succeeded—once again—in
the well-nigh impossible task of making a potentially stress-filled trek into a pleasant
journey filled with light and humor. Her team also deserves much praise for their
efficiency under pressure.
I also owe a debt of gratitude to my wife, Karine, for her time and effort spent
reviewing this book. Being a technical reviewer is a thankless task, but I want to say a
heartfelt “thank you” to her for the range and depth of her comments and for picking up
so much that otherwise would have gone unnoticed. The book is a better one thanks to
her efforts.
My thanks also go to Ann Gemer Tuballa for her tireless and subtle work editing and
polishing the prose and to the team at SPi Global for the hours spent preparing the book
for publishing.

xvii
Introduction
Analytics has become one of the buzzwords that define an age. Managers want their staff
to deliver meaningful insight in seconds; users just want to do their jobs quickly and
well. Everyone wants to produce clear, telling, and accurate analysis with tools that are
intuitive and easy to use.
Microsoft recognized these trends and needs a few short years ago when they
extended Excel with an add-in called Power Query. Once a mere optional extension to
the world’s leading spreadsheet, Power Query is now a fundamental pillar of the Excel
toolkit. It allows a user to take data from a wide range of sources and transform them into
the base data that they can build on to add metrics, instant analyses, and KPIs to project
their insights.
With Power Query, the era of self-service data access and transformation has finally
arrived.

What Is Power Query?


Power Query is a tool that is used to carry out ETL. This acronym stands for Extract,
Transform, Load. This is the sequential process that covers

• Connecting to source data outside the current Excel workbook (or


file if you prefer) and accessing all or part of the data that you need to
bring into Excel. This is the extract phase of ETL.

• Reshaping the data (the “data mashup” process) so that the resulting
data is in a form that can be used by Excel. Essentially, this means
ensuring that the data is in a coherent, structured, and complete
tabular format. This is the transform phase of ETL.

• Returning the data into Excel as a table in a worksheet or into the


Excel/Power Pivot data model. This is the load phase of ETL.

These three phases make up the data ingestion process. So it is worth taking a short
look at what makes up each one of them.

xix
Introduction

Connecting to Source Data


Gone are the days when you manually entered all the data you needed into a
spreadsheet. Today’s data are available in a multitude of locations and formats—and are
too voluminous to rekey.
This is where Power Query’s ability to connect instantly to 40-odd standard data
sources is simply invaluable. Is your accounting data in MS Dynamics? Just connect. Is
your CRM data in Salesforce? Just connect. Is your organization using a Data Lake?...you
can guess the reply.
Yet this is only a small part of what Power Query can do to help simplify your
analyses. For not only can it connect to a multitude of data sources (many of which
are outlined in Chapters 1 through 5), it does this via a unified interface that makes
connecting to data sources brilliantly simple. On top of this, you can use Power Query to
preview the source data and ensure that you are loading exactly what you need. Finally,
to top it all, the same interface is used for just about all of the available source data
connections. This means that once you have learned to set up one connection, you have
learned how to connect to virtually all of the available data sources.
In essence, part of Power Query is just another connection to external data. However,
its unified data access interface, range of available data sources, and sheer simplicity will
probably induce you to replace any data connections made using older technologies
pretty quickly.

D
 ata Transformation
Once you have established a connection to a data source, you may need to tweak the
data in some way. Indeed, you may even need to reshape it entirely. This is the data
mashup process—and it is the area where Power Query shines.
Power Query can carry out the simplest data transformation tasks to the most
complex data restructuring challenges in a few clicks. You can

• Filter source data so that you only load exactly the rows and columns
you need

• Extend the source data with calculations or data extracted from


existing columns of data

xx
Introduction

• Cleanse and rationalize the data easily and quickly in


a multitude of ways

• Join or split source tables to prepare a logical set of data tables for
each specific analytical requirement

• Group and aggregate source data to reduce the quantity of data


loaded into Excel

• Prepare source data tables to become a usable data model

This list merely scratches the surface of all that Power Query can do to mash up your
data. It is, without hyperbole, unbelievably powerful at transforming source data. Indeed,
it can carry out data ingestion and transformation tasks that used to be the preserve of
expensive products that required complex programming skills and powerful servers.
All of this can now be done using a code-free interface that assists you in taking the
messiest source data and delivering it to Excel as limpid tables of information ready to
work with. If you wish to become a Power Query super-user, then you can extend its
possibilities using the built-in M language.

Loading into a Worksheet or the Data Model


This final phase is the easiest by far. It is simply a question of telling Power Query where
to land the data. This can be one—or both—of

• A worksheet: Power Query can place the data from each source
query into a separate worksheet. Once in a worksheet, it is perfectly
“normal” Excel data. From here on you can do what you want to
the data in Excel just as you normally would using all the Excel
techniques that you have learned over the years.

• The data model: Also referred to, often, as the Power Pivot data
model (which is the term that I prefer to use), this is an in-memory
data store. It can handle many more rows of data than Excel—tens
of millions in some cases—and is normally the basis for pivot table
output in Excel. When dealing with large source datasets, it is often
the ideal destination for data that you have accessed using Power
Query, as it is compressed in memory (and consequently takes up
less space when saved to disk) and can easily exceed the 1,048,576
row limit of Excel worksheets.
xxi
Introduction

The data model and Power Pivot are extensive subjects in their own right, and this
book will not be looking at either of them in detail.

Integrating Power Query into Daily Workflows


Power Query is completely integrated into the latest versions of Excel. This means that
you can use it seamlessly as part of your daily routines when ingesting and analyzing
data. Put simply:

• Data source connections, transformation routines, and data loading


into Excel are created once and can be reused whenever suits you.

• You can trigger manual data refreshes at any time—and these can be
total refreshes of every source connection in a workbook or refreshes
of a single source if you prefer.

• Data sources can be reused across different Excel workbooks.

• Power Query processes can be copied between different Excel files.

• Power Query processes (called queries) can be managed and


extended with interactive parameters to create immensely powerful
ETL processes.

• Power Query–based data flows can be customized and extended


using the built-in M language.

So, as is the case for nearly all your Excel-based work, you are likely to build once
and use often.

The Evolution of Power Query


Power Query has evolved considerably over the years since it was first made available as a
downloadable add-in for Excel 2010. It was still optional for Excel 2013 and only attained
the status of being completely integrated into Excel by the 2016 version. Indeed, it suffered
a name change at that point and was accessed under the heading “Get & Transform.”
Since around 2017—and since the Excel 2019 version—it has reverted to being
Power Query once again. This is the version that is the subject of this book. This does not
mean that you cannot use the techniques described in these pages with earlier versions

xxii
Introduction

of the product. However, it will mean that certain aspects of the Excel interface that you
use to launch Power Query will be slightly different from those described in Chapters 1
through 5. These differences are essentially minor and should not present any
difficulties to experienced Excel users.
This is made possible due to the fact that Power Query is accessed using a separate
interface. It is called from inside Excel, but exists in its own parallel universe. This
ensures a consistent look and feel whatever the version of Excel that you are using. The
entry point into Power Query may change with Excel versions—but the product itself
remains the same. Just remember that the range of available data sources will depend on
the version of Excel that you are using. Some of the “enterprise-level” data sources are
only available in Pro and Enterprise subscriptions to Excel.

How to Use This Book


If you wish, you can read this book from start to finish as it is designed to be a progressive
tutorial that will help you to learn Power Query. However, as Power Query is composed
of four main areas, this book is broken down into four sets of chapters that focus on the
various key areas of the product. It follows that you can, if you prefer, focus on individual
topics in Power Query without having to take a linear approach to reading this book.

• Chapters 1 through 5 show you how to connect to a range of varied


data sources and bring this data into Excel using Power Query.
Depending on the source data that you need to use, you may only
need to dip into parts of these chapters to find guidance on how to
use a specific source data type.

• Chapters 6 through 9 explain how to transform and clean data so that


you can use it for analysis. These data transformations range from
the extremely simple to the potentially complex. Indeed, they are as
potentially vast as data itself. You may never need to apply all of the
extensive range of data modification and cleansing techniques that
Power Query can deliver—but just about everything that it can do is
explained in detail in these chapters.

xxiii
Introduction

• Chapters 10 and 11 explain how to tame the real world of data


loading and transformation. Here you will learn how to organize and
manage your queries, as well as how to add parameters to make them
more interactive and resilient.

• Chapter 12 introduces you to M—the language that Power Query uses


to transform your data. Using M you can push your data ingestion
and transformation routines to new heights that are simply not
possible using just the Power Query interface.

On to Learning Power Query


This book comes with a small set of sample data that are used to create the examples
that are used throughout the book. I realize that it may seem paradoxical to use a tiny
dataset for a product that can handle tens of millions of rows of data, but I prefer to use
a comprehensible set of source data so that the reader can concentrate on what is being
learned, rather than the data itself.
It is inevitable that not every question can be anticipated and answered in one book.
Nonetheless, I hope that I have answered many of the data ingestion and transformation
questions that you might encounter and—more importantly—have given you the
approaches and the confidence to resolve most of the Power Query challenges that you
might meet when applying this product to solve real-world problems.
As a final point, the information on “pure” Power Query in Chapters 6–12 is
independent of Excel. So if you are learning Power Query in Power BI, SQL Server
Integration Services, or the Power BI Service, you can find a wealth of relevant
information to assist you in your data transformation projects.
I wish you good luck in using Power Query, and I sincerely hope that you have as
much fun using it as I did in writing this book.

xxiv
CHAPTER 1

Using Power Query


to Discover and Load
Data into Excel
If you are reading this book, it is most likely because you need to use data. More
specifically, it may be that you need to take a journey from data to insight in which
you have to take quantities of facts and figures, shape them into comprehensible
information, and add the analysis that delivers clear meaning. More to the point, you
want to do all this using the spreadsheet that you know and trust—Microsoft Excel.
This book is all about that journey. It covers the many ways that you, an Excel user,
can transform external raw data into the information structures that enable you to
deliver high-impact analyses. This fresh approach presumes that you are not dependent
on central IT to help you to load data from external sources, nor do you need their
help on a regular basis. It is based on enabling the user to handle industrial-strength
quantities of source data using the world’s most popular spreadsheet in the shortest
possible time frame.
The keywords in this universe are

• Fast

• Decentralized

• Intuitive

• Interactive
• Delivery

1
© Adam Aspin 2020
A. Aspin, Data Mashup with Microsoft Excel Using Power Query and M,
https://doi.org/10.1007/978-1-4842-6018-0_1
Chapter 1 Using Power Query to Discover and Load Data into Excel

Using the techniques described in this book, you can discover and load data from
a multitude of external sources. You can then, quickly and intuitively, transform and
cleanse this raw data to make it structured and usable. Once ready for use, you can load
it into either Excel worksheets or the Power Pivot data model in Excel and start using the
tool you already know so well—Excel—to provide detailed analytics.
It follows that this book is written from the perspective of the user. Essentially it is
all about empowerment—letting users define their own requirements and satisfy their
own needs simply and efficiently by building on their existing skills. The amazing thing
is that you can do all of this using Excel without needing any other tools or utilities. Your
sources could be in many places and in many formats. Nonetheless, you need to access
them, sample them, select them, and, if necessary, transform or cleanse them in order to
deliver your analyses. All of this is enabled by Power Query.

Power Query
Power Query is one of the most recent additions to the Excel toolkit. Now fully integrated
into Excel, it allows you to discover, access, and consolidate information from varied
sources. Once your data is selected, cleansed, and transformed into a coherent table, you
can then place it in an Excel worksheet for detailed analysis or load it directly into Power
Pivot (the Excel data model), which is a natural repository for data when you want to
“slice and dice” it interactively.
Power Query allows you to do many things with source data, but the four main steps
are likely to be

• Import data from a wide variety of sources. This covers corporate


databases to files and social media to big data.

• Merge data from multiple sources into a coherent structure.

• Shape data into the columns and records that suit your use cases.

• Cleanse your data to make it reliable and easy to use.

There was a time when these processes required dedicated teams of IT specialists.
Well, not any more. With Power Query, you can mash up your own data so that it is the
way you want it and is ready to use as part of your self-service solution.

2
Chapter 1 Using Power Query to Discover and Load Data into Excel

This is because discovering, loading, cleansing, restructuring, and modifying source


data are what Power Query is designed to do. It allows you to accomplish the following:

• Data discovery: Find and connect to a myriad of data sources


containing potentially useful data. This can be from both public and
private data sources. This is the subject of Chapters 1 through 5.

• Data loading: Select the data you have examined and load a subset
into Power Query for shaping.
• Data modification: Modify the structure of each dataset that you have
imported.

• Filter and clean the data itself.

Although I have outlined these three steps as if they are completely separate and
sequential, the reality is that they often blend into a single process. Indeed, there could
be many occasions when you will examine the data after it has been loaded into Excel—
or clean datasets before you load them. The core objective will, however, always remain
the same: find some data and then sample it in Power Query where you can tweak, clean,
and shape it before loading it into Excel.
This process could be described simplistically as “First, catch your data.” In the world
of data warehousing, the specialists call it ETL, which is short for Extract, Transform, and
Load. Despite the reassuring confidence that the acronym brings, this process is rarely
a smooth, logical progression through a clear-cut series of steps. The reality is often
far messier. You may often find yourself importing some data, cleaning it, importing
some more data from another source, combining the second dataset with the first one,
removing some rows and columns, and then repeating these operations, as well as many
others, several times over.
In this and the following few chapters, I will try to show you how the process can
work in practice using Power Query. I hope that this will make the various steps that
comprise an ETL process clearer. All I am asking is that you remain aware that the
range of options that Power Query includes make it a multifaceted and tremendously
capable tool. The science is to know which options to use. The art is to know when to
use them.

3
Chapter 1 Using Power Query to Discover and Load Data into Excel

The Data Load Process


Let’s begin with a rapid overview of what you need to do to get some data into Excel
(assuming that you have downloaded the sample data that accompanies this book from
the Apress website—this is explained in Appendix A). The following steps explain what
you have to do to load data from a source that you know well already—Excel itself. Yes,
I know that you can copy and paste data between workbooks, but that would be to miss
the point and miss out on all the incredible extra facets of data mashup that Power Query
can offer. In this initial case, the actual source of the data is irrelevant. It could come from
any of a few dozen available sources. Excel is simply an example of potential source data.

1. Open a new, blank workbook in Excel.

2. Click Data in the menu to switch to the Data ribbon.

3. Click Get Data. The Get Data popup menu will appear, as shown
in Figure 1-1.

Figure 1-1. The Get Data popup menu

4
Chapter 1 Using Power Query to Discover and Load Data into Excel

4. Click From File.

5. Click From Workbook. The Import Data dialog will appear.

6. Click the file C:\DataMashupWithExcelSamples\


BrilliantBritishCars.xlsx. The Import Data dialog will look like the
one in Figure 1-2.

Figure 1-2. The Import Data dialog when loading data from an Excel workbook

7. Click the Import button. The Navigator dialog will appear.

8. You will see that the BrilliantBritishCars.xlsx file appears on


the left of the Navigator dialog and that any workbooks, named
ranges, or data tables that it contains are also listed under the file.

9. Click the BaseData worksheet name that is on the left. The


contents of this workbook will appear in the data pane on the
right of the Navigator dialog. The Navigator dialog should look like
Figure 1-3.

5
Chapter 1 Using Power Query to Discover and Load Data into Excel

Figure 1-3. The Navigator dialog with data selected

10. Click Load. The data will be loaded from the external Excel
workbook into a new worksheet inside the current workbook.

You will see the Excel window, like the one shown in Figure 1-4. The external data is
now an Excel table (named BaseData, as this was the name of the source data table). You
can see that the connection to the external workbook now appears on the right of the
Excel spreadsheet data in the new Queries & Connections pane. I will explain this new
element in a couple of pages once I have explained exactly why Power Query is such a
cool solution to data ingestion challenges.

6
Chapter 1 Using Power Query to Discover and Load Data into Excel

Figure 1-4. Data available in Excel

I imagine that loading this data took a few seconds at most. Yet you now have a
complete set of external data in Excel that is ready to be used for analysis and reporting.
However, for the moment, I would like to pause and explain exactly what you have seen
so far.

Why Use Power Query?


What you have just done is to open up Excel to become the preferred analysis and MI/BI
(Management Information and Business Intelligence) tool when it comes to connecting
to the information held in dozens of external data sources. What you just saw was that
Excel can now connect to multiple sources of data and bring them into spreadsheets for
further analysis in a few clicks.
However, it is vital to understand that you have so far only scratched the surface of
Power Query and all that it can do to facilitate data ingestion. This is because viewing
and loading data are just the start. As well, you can use it to

• Import data from multiple different data sources

• Import multiple datasets from external data sources at the same time

7
Another Random Scribd Document
with Unrelated Content
and procedure, with all our well-known safeguards of the rights of the
subject and the dignity and sanctity of law, must be a great
improvement on the old haphazard Burmese system, and must
afford far greater protection to the innocent, and a greater probability
of detecting and punishing the guilty. In point of impartiality and
freedom from corruption, too, there must be a great change for the
better. Since the country has begun to thoroughly settle down, and
the necessity for a speedy and summary decision in criminal cases
is no longer felt, a Judicial Commissioner has been appointed for
Upper Burma, a trained civilian of high position and experience,
whose duty it is to revise the proceedings of the subordinate courts,
and, if necessary, alter the findings. This precaution Government
takes to ensure that the cases shall have full and mature
consideration, and that in the name of justice, justice shall be done.
An illustration of the improved methods of legal procedure, after
Western models, introduced under the British administration, is the
compulsory registration of deeds relating to immovable property.
This measure operates to prevent fraud and secure and simplify
titles. The deed being registered, and a copy of it being kept in
Government records, forgery and other methods of cheating are
made far more difficult. Under the Burman rule deeds were not used,
the theory being that all property belonged to the king. It can readily
be imagined what confusion of title resulted from that primitive
method, and how necessary it was to make enactments that should
minimise the risk of fraud, dispute and litigation.
The survey of the whole country has made good progress. Year by
year, despite the disturbed state of the country, and the consequent
danger of travelling, survey parties have been diligently employed in
that important business. Triangulation has been carried over 84,000
square miles, and the whole country has been mapped on a scale of
four miles to the inch.
Experimental farming is, in Upper Burma, a new undertaking
which necessarily falls to the lot of Government, in the absence of
the requisite knowledge and enterprise on the part of the people.
With a view to increasing the products of the country, and bettering
the position of the people, an experimental farm has been
established in the Shan States. Various products, new to Burma, are
receiving a trial; for instance, English fruit trees on some of the hill
stations, and at various other places potatoes, American maize,
wheat, barley, and English garden vegetables. The successful
introduction of some of these new products may mean a great deal
for the prosperity of the country. Attention has also been paid to the
rearing of cattle, sheep and horses, and veterinary assistants are
employed, at the expense of Government, in combating cattle
disease, and their work has given satisfaction to the people.
There is no branch of the public service for which there is more
need in a new country than that of the Department of Public Works.
A country recently come under British rule presents a wide field for
the talents and energies of the civil engineer. The principal public
works of the Burmans consisted of the construction of reservoirs for
that great necessity of life, water, both for drinking purposes and for
irrigation, and the formation of channels for conducting the water to
the fields. These works were found only in a few favoured places,
and though not finished in first-rate engineering style, exhibited no
small amount of ingenuity and skill. Beyond this their engineering
manifested itself rather in religious edifices than in works of general
public utility.
There was therefore great need to supplement what the Burmans
had left lacking. The country was without a single good road. Even in
Mandalay itself there was not a road worthy of the name. Now some
hundreds of miles of good road have been constructed, the streams
bridged, and communications opened up on the principal lines of
travel. An extensive system of new irrigation works is under
construction or in contemplation. In every principal station barracks
for the soldiers and the police, and jails have been built, and in every
town, market houses, court houses, public offices and hospitals
provided; so that already there is not a town of any considerable size
which does not show abundant outward signs of the change which
has come over the country.
Railways were of course unknown in Upper Burma before the
advent of British rule; and they are likely to prove a powerful stimulus
to the development of the country. There was a line of railway
already finished in Lower Burma from Rangoon to Toungoo, 166
miles, and the extension of this line to Mandalay, 220 miles farther,
was one of the first great public works projected. It was sanctioned in
November 1886; the survey was pushed on and completed by the
summer of 1887; the work was begun on each section as soon as
the estimates were sanctioned; and so rapidly was the work carried
on that an engine ran through from Toungoo to Mandalay by May
1st, 1888. The line was finally completed and opened for traffic in
March 1889. The cost was a little over twenty millions of rupees.
At the beginning the work practically lay through an enemy’s
country, but survey parties and working parties were carefully
guarded, and no successful attacks were made upon the many
thousands of labourers on the work. The construction gave
employment and wages to a large number of Burmans, at a time
when the labouring classes would have been otherwise in great
straits. The finding of honest remunerative work for so many people
was, in itself, a great check on dacoity. Since the railway was
opened the districts through which it runs have been the quietest in
Upper Burma, although previously so greatly disturbed.
From every point of view this first introduction of railways into
Upper Burma must be pronounced a great success. From the very
first this line paid its working expenses, and in conjunction with the
rest of the state railways in Burma, 4 per cent. on the capital
invested. If it could do that at the outset it will do much more when
other railway extensions are carried out, and roads are made as
feeders to the traffic. To all this must be added the great
convenience it affords to the public and to Government, and the
impulse it gives to commerce, besides its strategic importance from
a military point of view.
Encouraged by this result, another line, called the Mu Valley
extension, is already well on towards completion. It starts from
Sagaing, on the opposite side of the Irrawaddy to Mandalay,
proceeds in a northerly direction, and will ultimately go as far as
Mogaung in the far north of the country, some 300 miles from
Sagaing. The laying of this line through the territory of the semi-
independent little state of Wuntho was the last straw that broke the
back of the loyalty of the sawbwa. From the first he had been
awkward, and had given trouble, but the prospect of having a railway
through his dominions was too much for him, and he broke out into
open rebellion. There was nothing for it but to put down the
insurrection, annex his petty state, and administer it. Civilisation and
the general welfare cannot be expected to come to a standstill at the
bidding of an ignorant little chieftain like Wuntho.
Another extension of the Mandalay line, from Meiktila to Myingyan
on the Irrawaddy, is about to be taken in hand; and a second and
more detailed survey is shortly to be made for that very important
extension from Mandalay up to the hills, and across the Shan
plateau in a north-easterly direction, to open up the rich Shan
country, and eventually, in all probability, to connect Upper Burma
with Yunan, the great westerly province of China, with eleven
millions of inhabitants.
Railways bring new life to a country like Burma, and arouse men
from the sleep of centuries. They pay well; they civilise the people by
bringing together, in an amicable way and for their mutual benefit,
races and tribes that formerly were enemies; they render it easier to
get an honest living than to live by robbery; they not only stimulate
trade, they create it; they help to solve the difficulties of demand and
supply in the labour question, by making it cheap and easy for the
people to get to and fro; and when times of scarcity and famine
come round, they enable the Government to cope with them, and
prevent or mitigate their horrors.
The post, the telegraph and the telephone, which are now
amongst the necessities of civilised life, have all been established in
Upper Burma, and are now in thorough working order. In fact, so
civilised has Upper Burma become, that a movement is on foot for a
private company to lay down several miles of tramway in the streets
of Mandalay, and start a service of trams; and another scheme has
been submitted for lighting the principal streets with electricity.
A government in an Oriental country, to be successful, must,
before everything else, be strong, and nothing contributes more to
this than an efficient police. At the outset, the establishment of order
was largely a military work, and the brunt of it rested on our British
and Sepoy troops. But gradually as the country settled down, the
troops were reduced, and the police took over the work of keeping
order. Here was considerable scope for organisation. In most of the
countries where English rule has been established, we have
managed to organise a police out of the materials the country
supplied. But the Burmans do not prove very tractable for this, so
that whilst there has been special need for a strong police to keep
matters in order, it so happens that we have a people specially
wanting in the qualities necessary for this work. The police officers
complain that the Burmans in the force “cannot be trusted to oppose
a larger force of dacoits, or to do sentry work.” The Burman finds
great difficulty in submitting to discipline or carrying out any regular
routine whatever in a reliable manner. He loves to have his own way,
to feel free to come and go just when he likes, and generally to go on
in a careless and casual manner.
After the annexation of Pegu in 1853, an attempt was made to
raise a military battalion of Burmese. By an unintentional irony it was
called “The Pegu Light Infantry.” It was found that they were
altogether too light and lacking in the spirit of discipline ever to make
good soldiers, and the Pegu Light Infantry was accordingly
disbanded.
For this reason Government has had to look elsewhere for its
police, and they have been recruited chiefly from amongst the
warlike races of Northern India, with a sprinkling of Burmans, who
are necessary for the detection of crime, and for such work as their
knowledge of their own people and language the better fits them.
During the troublous times of 1886-89 there has been a force of
twenty thousand civil and military police, about two-thirds of whom
were natives of India. But as the number of crimes of violence
decreases, it becomes possible greatly to reduce this number.
Of all the numerous innovations on Oriental methods of
government which we have introduced, that of local self-government,
as applied to municipalities, is perhaps the most noteworthy, not for
what it does at present, but for what it leads up to. This little seedling
of representative government we are sedulously planting everywhere
throughout our Indian Empire, and nurturing it with patient and
sympathetic care; and he would indeed be worthy of the name of
prophet who could say whereunto it will grow. Never under any
Indian or Burmese rule was there a vestige of representative
government, but we think it well to train them up to it.
The schoolboy in India has the History of England put into his
hands, and there he learns what Englishmen think of liberty and self-
government; and he finds that the ruling power has broadened down
in the course of ages from the one to the few, from the few to the
many, and from the many to the whole population, who now really
govern themselves. Our British policy is to organise municipalities in
every considerable town. We, the governing power, call together a
native municipal committee, as representative as we can make it by
nomination, and then we say in effect, “Now we have called you in to
consult with us, the leading English representatives of government,
and by your votes to show your opinions on such questions as the
cleaning, the lighting, the paving, and the sanitation of the town, its
water supply, the regulation of its markets, and a number of other
local matters, and we ask you to vote supplies of money for these
things, and to levy taxes and rates accordingly.”
All these things are matters of course to the Englishman in his own
country, and if any of them were conducted without consulting him
through his elected representatives, he would soon want to know the
reason why. But not so with the Oriental; they are to him innovations
of an unheard-of character. Neither he nor any of his forefathers
were ever asked to do such a thing as vote before. It is no wonder,
therefore, if our worthy native citizen takes his seat as he is bidden in
the municipal council-chamber of his town, bewildered at first with
this unwonted experience, voting to the best of his ability as he
thinks the worthy president, the English Deputy Commissioner of the
district, would desire him to vote. But in course of time he comes to
see what it all means, for the Oriental is by no means deficient in
perception. He sees that the measures proposed and carried affect
him and his kindred and his neighbours, and he begins to see that a
voice and a vote mean power, and that these are questions which
touch his pocket and circumstances.
By-and-by the people find that the municipal ordinance provides
for the expression of their opinions in a more direct and effective
way. The rule is, that “as soon as any town desires to elect its
members it is permitted to do so.” In many towns in India they are
now elected. We have in Upper Burma seventeen municipalities, but
in no case yet is there any election of members; they are all
appointed by nomination. The change from the full-blown doctrine of
the divine right of kings, in its completest form, to representative
government, is too sudden for them to realise where they are as yet.
But it will come. All the teaching we give them, both by precept and
example, is in effect this: that the true ideal of government is
government by the people, and that all other forms of government
are only temporary expedients leading up to it.
We cannot wonder if in time they follow the path where it logically
leads them to a wider outlook than merely municipal affairs. “If in
municipal why not in national affairs?” they will naturally ask. The
National Congress in India is the natural sequence of all this. It is the
feeling after some arrangement or institution that shall give effect to
the will of the people, on many more matters than they are at present
consulted upon. It may be silly sometimes, and selfish, and
reactionary, and stupidly conservative, and childish, but whatever its
faults, its follies, and its weaknesses, it is at all events our own
bantling, the child of our own careful nurture and instruction. It is no
use our attempting to frown it out of countenance; what we have to
do is to take it by the hand, and guide it until it reaches years of
discretion.
BURMESE WOMAN ON HER WAY TO THE WELL TO DRAW WATER.
CHAPTER VIII.
INTOXICANTS IN BURMA—THE LIQUOR
QUESTION.

We have seen how much there is to admire and to be proud of in


the capacity and skill of our nation as the great ruling power in India.
One cannot have dwelt in Upper Burma during the last few years
without observing how sincerely our rulers have sought the welfare
of the people, and how ably they have secured it. The liberty of the
people, their freedom from oppression, the greater security for life
and property all over the country, their general comfort and well-
being, the introduction of a far better system of law and justice than
ever they knew before, the development of the resources of the
country, and the general prosperity that has ensued, are results well
worth securing.
But the countenance given to the sale and consumption of
intoxicants, and the growth of these vices under our rule, when we
ought to be so well able to discourage and check them, are very
grave defects; and it is this matter I propose in this and the following
chapters to discuss. This is just now a question which is receiving
much attention. It is not a case for heated controversy, or for calling
ill names, but for calmly and dispassionately looking the facts in the
face, and asking ourselves in the sight of God whether we are doing
right, or whether there is not a more excellent way.
A special and peculiar interest surrounds this question, owing
partly to the fact that the new province was so recently annexed, and
our policy is not as yet finally fixed; partly to the delicate and
anomalous position in which we, as a non-abstaining race, find
ourselves, in governing a race whose religion definitely enjoins total
abstinence from everything intoxicating, and who earnestly desire
that prohibition be continued as the law of the land; and partly from
the very disastrous effects which have been found to result from the
policy we have been pursuing during the many years we have been
ruling Lower Burma.
On our annexing Upper Burma in 1886, we found the fifth
commandment of the Buddhist religion, “Thou shalt not take anything
that intoxicates,” was the law of the land, the only law on the subject
the Burmans had ever known. On this point I quote no less an
authority than a despatch from the Government of India to the
Secretary of State, dated October 1886, in which are certain
“Instructions to Civil Officers,” and it is there stated that—
“Burmans of all classes, monks and laity, very strongly wish that
drinking shops and the habit of drinking should be discouraged in
Upper Burma. In the time of the late king traffic in liquor was
altogether forbidden. No doubt there is some making and drinking of
toddy, of rice beer, and even of spirits in Burman villages. But the
sense of the better classes is against the practice. No revenue was
ever raised by the late king from liquor, lest he should seem to be
encouraging evil. And under the circumstances, it seems expedient
to meet the wishes of the people by declining for the present to
license drinking shops.”
It certainly did seem expedient, with the nation on its knees
begging us not to inflict drinking shops upon them, to license no
shops whatever; and that not only “for the present,” but to resolve
never to allow any. If ever there was a case in this world for local
option, which was overwhelmingly in favour of entire prohibition,
surely it was there; and under such circumstances the introduction of
licensed liquor shops, on any plea whatever, was entirely
unjustifiable and uncalled for. But the document proceeds:—
“Where a real demand exists for liquor to be consumed by
Europeans, Indians or Chinese, shops for the sale of spirits and of
fermented liquors may be licensed.”
So it unfortunately comes to this, that because there are certain
foreigners in the country with “a real demand” for liquor, the whole
policy of the country is to be changed for their sakes, and an
excitable, volatile people such as the Burmans, peculiarly liable to
fall away through drink, are to be exposed to temptations in their
streets, in the shape of licensed liquor shops, such as they never
had before, and such as it is well known multitudes of them will be
quite unable to resist. It is true there is a clause in the law making it a
punishable offence for the holder of the licence to sell liquor to
Burmans. But what avails such a clause? The shops are there with
the liquor for sale; that is the one all-important and damaging fact;
and as for that clause, it is in theory a glaring anomaly, and in
practice simply a farce. Any Burman can get as much liquor as he
wishes.
A recent Government report fully admits this, and shows the futility
of such a lame attempt to shield the Burmans from the effects of the
temptations furnished by the drinking taverns established in their
midst.
“The licences for the sale of liquor and opium are intended for the
convenience of the non-Burman population of Upper Burma, and the
sale of either liquor (except tari) or opium to Burmans is prohibited
by law. But there can be no doubt that the prohibition is in practice
inoperative.”
Now observe how we have progressed with this business during
the first few years of our rule. In Upper Burma, where, before we
assumed the government, there never had been such a thing as a
licensed liquor shop, and where drunkenness, when it did occur, was
severely punished, there are now 175 licensed liquor shops, and
Burmans are constantly under temptation to indulge. In Upper
Burma, where there had always been every discouragement to the
manufacture of liquor, there are now central distilleries established,
under Government patronage and licence, for the wholesale
manufacture of spirits, and one of these turns out, as the proprietor
informed a friend of mine, 500 gallons a day.
Bad as Burmese rule was, corrupt, weak and worn out, and badly
in want of funds, it never sunk so low as to derive any revenue by
the sale of licences, but now the excise revenue from liquor and
opium licences is advancing by leaps and bounds.
For the year 1887-88 it was 210,480 rupees
” 1888-89 ” 433,430 ”
” 1889-90 ” 541,700 ”

It looks as though liquor and opium under the British Government


were rapidly tightening their hold of the country, and it is quite time
England made up her mind what she is really going to do in the
matter, and whether she can reconcile this state of things with her
notions of duty to a subject race.
It is urged by the advocates of the present system that there was
drinking before, even under Burmese rule. No doubt there was. With
the materials all around in abundance in the products of the country,
both for fermenting and distilling liquors, it is not to be supposed that
alcohol was unknown. It was, however, a very uncommon thing
amongst Burmans to drink, and it can afford no possible justification
for licensing and thereby increasing the evil.
It is also urged that it is impossible to do away with drinking
entirely. “Prohibit it altogether,” say they, “and it will still go on
secretly.” There scarcely could be a poorer plea than this. How many
evils and crimes and vices there are in every country that cannot be
entirely done away with, and yet no one in his senses would propose
to license and regulate them on that ground. Our reply to this is that
a Government can only do its best, and if, after we had done our
best to discourage the drinking it still existed, despite all we could do,
it would not be our fault. But if King Theebaw could do as much as
he evidently did, with his worn-out methods of government, to keep
his people sober, what might not we accomplish with the splendid
machine of government we possess?
The last resort of the apologists for licensing intoxicants usually is
that, good or bad, we are committed to the system, and cannot get
rid of it without causing greater evils than what we now have. This is
one of the arguments used with respect to India, but it fails
altogether when applied to Burma, and has not a leg to stand on. We
had every opportunity to have continued the law of prohibition just as
we found it, and the people earnestly requested us to do so, and we
ought to have done it. Even now it is not too late to retrace our steps
in that direction, for the present state of things is felt to be
unsatisfactory, and the law cannot be carried out.
Why cannot we end it by prohibiting the manufacture and sale of
liquor throughout the country? If it be said that this would bear hardly
upon the foreign residents, it may well be replied that the rights and
liberties of foreigners ought not to prejudice those of the vast
majority, the natives of the country; and if that were the law, and
foreigners did not choose to put up with it, they would have their
remedy. No one is compelled to live in Burma.
The pity is, that England should so lag behind in the matter of
temperance reform. The Empire is inevitably increasing, yet
England, by continuing to cling to liquor as she does, fails in this
respect to fit herself for properly carrying out her duty amongst the
abstaining races that come within the sphere of our influence.
The day is coming, as every one can see, when England’s own
liquor question must be effectually dealt with, for the mind of the
majority of the English people is rapidly ripening for it. But in the
meantime, the very painful, anomalous and inconsistent position we
occupy in Upper Burma—a Christian nation establishing liquor shops
in every centre of population, against the strongly expressed wishes
of “all classes of Burmans, monks and laity”—is a humiliating proof
of the need there is for this reform to be hastened at home, so that it
may be faithfully carried out abroad, and that too before it is too late.
CHAPTER IX.
INTOXICANTS IN BURMA—THE OPIUM
QUESTION.

If the case of Burma in respect of liquor is serious, that of opium is


more so. It presents in a vivid manner some of the most frightful evils
of the traffic in this drug, and it shows clearly the gross inconsistency
of any Christian nation, especially when it is the ruling power,
deliberately introducing and maintaining such an evil and profiting
largely in the revenue by it, when it is eating the very vitals of the
subject nation that has implored us again and again to remove it.
The whole question of the opium policy of our Indian Government
in the East is now prominently under the view of the nation.
Parliament has already declared in the abstract that our opium policy
is indefensible, and the conscience of the British public, never quite
easy on the subject, is at present feeling keenly about it. It seems
not unlikely that the consideration of Burma, our latest, and in some
respects our worst development of the policy, may greatly aid in
shaping the views of the public on this question, and may decide us,
at the earliest possible moment, to wash our hands of the whole sad
business.
It ought, in the first place, to be understood that the opium
business is not like liquor in England, a matter of private enterprise.
It is one big monopoly of the Indian Government from first to last,
and no one else is allowed to manufacture it. Government assumes
the entire responsibility for the growth, manufacture, sale and export
of opium, and sells licences for the permission to retail it in British
India. Government is the proprietor of the whole concern. The
greater part of the Indian opium is exported to China, and there, as
everybody knows, we added to our delinquencies by compelling the
Chinese, at the point of the sword, to allow us to import opium into
China, to the lasting detriment and ruin of untold multitudes of that
people. Some of the opium, a constantly increasing quantity, is
disposed of in the different provinces of India, this part of the
business also being under Government management and licence.
As regards Upper Burma, the law we found on annexing the
country was, and had ever been, the law of prohibition. Government
knew and fully admitted this. From the despatch already quoted of
October 1886, it would appear at first sight that on taking over the
country they had fully resolved to continue that policy.
“No shops whatever will be licensed for the sale of opium,
inasmuch as all respectable classes of Burmans are against
legalising the consumption of opium in the new province.... As the
traffic in opium was prohibited under the Burmese Government,
there will be no hardship in thus proscribing opium dealings.”
But the very next sentence goes on to make an exception in
favour of Chinamen, to whom, and to whom only, it shall be lawful to
sell opium, and this clause at once lets in the mischief.
I know a small town in Upper Burma where a Chinaman obtained
a licence to sell opium to his countrymen under this regulation, on
his representing that there were two hundred of them in the town,
when, as a matter of fact, there were not more than half a dozen. He
meant, of course, to sell to the Burmans. I had this from the township
officer, who knew all the circumstances; not, however, the officer who
had helped him to get his licence. It is well known that the restriction
is merely nominal and ineffectual, and the Government officers freely
admit the fact. A recent Government officer of standing reports that—
“The consumption of liquors and opium is theoretically confined to
the non-Burman population. But there can be no doubt that a
considerable amount of both finds its way into the hands of
Burmans.”
Of course it does. The temptations are there in the shape of
licensed shops, and the tempters in the shape of cunning Chinamen
with an eye to the main chance; and so long as this is the case the
Burmans will fall into the snare in ever-increasing numbers, for they
are, like the Chinese, peculiarly liable to yield to the opium habit. The
following is the testimony of Mr. Gregory, a gentleman who travelled
through Burma to see for himself what the facts of the case were;
and whatever may be said by the apologists for opium against
alleged exaggerations, I think we may, at any rate, receive the
testimony of a Christian man concerning what he saw himself. I
quote what he says of Upper Burma. It fully proves how ineffectual
the restrictive legislation is, and how powerful the temptation:—
“At Pyinmana I saw Burmans buying opium, and at the same place
the abbot of the Buddhist monasteries and one of the chief monks
both told me that large numbers of the Burmans smoked. One of
them bitterly complained that, whereas in the late king’s time he had
power to stop these things, now he had none. At Yamethin, a
prominent Burman official told me that there were numbers of purely
Burmese villages in the neighbourhood supplied with opium from the
Yamethin centre. I myself saw Burmans purchase opium there. At
Kyaukse I saw Burmans served with opium. At all three of the opium
centres at Mandalay I saw opium served to Burmans. One of the
Chinese managers told me that the prohibition was only nominal,
and he expected that it would be shortly removed ‘now that the
Opium Act was getting into proper working order.’ At one of the
Mandalay shops I saw three Burmans being taught to smoke by one
of the Chinese assistants. A fourth was lying insensible. At Katha I
saw a number of Burmans smoking opium in their houses in rooms
quite open and visible, close by the court-house. At Bhamo, in the far
north, I saw Burmans in crowds buying opium at the Government
centre.”
Thus this legislative expedient we pretend to have adopted for
keeping the Burman from opium completely breaks down, and is a
mere dead letter. Nominally we are carrying out prohibition as we
undertook to do, but really we are tempting the Burmans to their ruin
by means of the licensed shops. Time was when Chinese opium
vendors in Upper Burma, when caught, were disgraced in every
possible way, and even flogged and imprisoned. Recently Mr. Justice
Grantham, at the Durham assizes, was trying the case of one miner
who had caused the death of another, while the two were drunk
together in the Colliery Tavern. The prisoner was found guilty. Upon
this his lordship directed the landlord of the Colliery Tavern to take
his place beside the prisoner in the dock, and the landlord having
done so, the judge proceeded to tell him in plain terms that he (the
judge) would have felt more satisfied if the jury, instead of finding the
prisoner guilty, had found the publican guilty of causing the death of
the deceased. He had served the deceased with liquor when he was
drunk already, and had undoubtedly thus caused the man’s death.
The Burman king’s way of looking upon opium vendors was the
right way, and the judge’s rebuke of the publican was well merited;
the misfortune is that so few can see it yet. The Chinese wealthy
opium vendors in Burma now ride in first-class railway carriages, and
are put forward into the honorary rank of municipal commissioners;
whilst in England we go further than this, and admit to the peerage
the heads of the great brewing firms!
We have carried the exceptional, “grandmotherly” method of
legislation to a very absurd length in Burma, prompted on the one
hand by our usual policy of regulating by licensing these vicious
indulgences, and yet restrained by a natural horror for the mischief
they do to the Burmese race, and by a well-grounded fear, founded
on painful experience, that if we do not somehow keep the nation
from liquor and opium, these vices will destroy multitudes of them.
Liquor can be lawfully sold in Upper Burma to Europeans,
Eurasians, natives of India and Chinese, but not to Burmans.
Opium to Chinese only.
Both liquor and opium may be sold to Burmans in Lower Burma.
Gunja, a product of hemp, very intoxicating, and used largely by
natives of India in their own country, is absolutely forbidden to
everybody in Burma.
The absurd and illogical in legislation could hardly go further than
the British have gone in these complicated enactments. In view of all
this one naturally inquires, If it be right to prohibit gunja, why should
it not be proper to forbid opium? If opium ought to be kept from every
race in Upper Burma but one, and they immigrants from a foreign
country and a very small minority, why not go further and shut it out
altogether? If liquor and opium are denied to Upper Burmans, why
should they be allowed to the same race in Lower Burma, where
they have done so much mischief? If liquor is bad for Burmans in
Upper Burma, how can it be good for Europeans, Chinese and
natives of India?
We should have entire prohibition of the opium curse in Upper
Burma if it were not for the Chinese; that lets in all the mischief. Why
is this? Why indeed, unless it is that having forced opium upon them
in China at the point of the bayonet, we cannot for very shame
withhold it from them in Burma, but must grant them the indulgence,
at any cost to the inhabitants, lest we become a byword and a
laughing-stock among the nations. There is no consistent standing
place between total prohibition on the one hand, and the cynical tone
adopted by the advocates of licensing on the other: “It comes to this,
that if the Burmans cannot learn to use these indulgences in
moderation they must take the consequences.”
If we persist in driving the Burmans to “take the consequences”
God will surely require it at our hands.
The further we go into the question the more does it demonstrate
the utter futility of a vacillating, partial, halting policy like this our
latest in Burma. There is nothing for it but to make that clean sweep
of it which the Burmans have always requested we would, and to
repent and do our first works, however late in the day it is for us to
begin. A brief review of the history of the opium difficulty in our older
province of Lower Burma gives emphasis to this view.
There is no wonder our rulers should in the new province show
some signs of compunction, and some feeble attempt to prohibit
opium to the Burmans, with the dreadful experience of Lower Burma
before their eyes. But they should have gone further, and made
prohibition complete. Lower Burma is in the unenviable position of
having the largest consumption of opium, per head of the population,
of any of our Indian provinces. The quantity supplied by Government
for the year 1890-91 was 54,205 seers for a population of 4,658,000.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like