I want to use the Power Query M function Csv.Document()
to get data from a named sheet within the same file. How would I do this?
This is how I can get the data from another file on the disc:
= Csv.Document(File.Contents("C:\Users\foo\OneDrive\Desktop\test.csv"),[Delimiter=",", Columns=1, Encoding=65001])
But I prefer to paste the CSV content into a sheet in the same file, and then use Power Query to get its data to put it into the Data Model. The reason is the file is shared over OneDrive, so any paths will not be the same for different users opening the file.
In effect I want to replace File.Contents("C:\Users\foo\OneDrive\Desktop\test.csv")
with a function to get the data from a sheet in the same file.
Example of CSV content I want to paste in a sheet (updated to proper format):
"created","currency","gross","fee","net","reporting_category","customer_facing_amount","customer_facing_currency","shipping_address_country","payment_metadata[order_id]"
"2024-01-01 23:56:03","sek","4262.52","65.74","4196.78","charge","390.83","eur","ES","2955"
"2024-01-02 12:49:26","sek","926.66","24.97","901.69","charge","85.00","eur","GB","2958"
This can be solved by putting the raw CSV data in a new sheet, pasting the content into column A, then naming column A. The reason for this is that Excel.CurrentWorkbook()
returns a table listing all named tables, named ranges, and Power Query output tables (those loaded to "Table" in the workbook) that are currently part of the workbook. It does not list worksheets, only these named data objects within the workbook.
After pasting the CSV content, select column A with the mouse and give it a name. In this example it was named "Stripe":
Now the data can be parsed as:
let
// Load the named range "Stripe" from the current workbook
SheetData = Excel.CurrentWorkbook(){[Name = "Stripe"]}[Content],
// Combine the values from the "Column1" column into a single text string with line breaks
CsvText = Text.Combine(Table.Column(SheetData, "Column1"), "#(lf)"),
// Parse the combined text as a CSV document
Source = Csv.Document(Text.ToBinary(CsvText), [
Delimiter = ",",
Encoding = 65001,
QuoteStyle = QuoteStyle.Csv
]),
#"Promote headers" = Table.PromoteHeaders(Source, [PromoteAllScalars = true])
in
#"Promote headers"