简体   繁体   English

具有动态单元格值的 Excel 查询

[英]Excel query with dynamic cell value

I need some help organizing what needs to be done.我需要一些帮助来组织需要做的事情。 I have a list of stock ticker symbols and need to download data for each one of them to be displayed in a query table.我有一个股票代码列表,需要下载每个代码的数据以显示在查询表中。 Here's what it would look like even though it is a shorten version :即使它是缩短版本,它也会看起来像这样:

在此处输入图片说明

I have built a url for a web query, but since my ticker changes for each request, I don't know how to have the query look into the ticker cell (C2, G2, etc...) I can do it if I name these cells, but do I have to name each one of them ?我已经为 Web 查询构建了一个 url,但是由于我的股票代码随每个请求而变化,我不知道如何让查询查看股票代码单元格(C2、G2 等...),如果我可以做到的话命名这些单元格,但我必须为每个单元格命名吗? Is there a way to look at the cell value based on cell reference ?有没有办法根据单元格引用查看单元格值? In the example below, it would have to be at Source = Json.Document(Web.Contents(meurl1 )), where I would ad meurl1&C2 or something like that.在下面的示例中,它必须位于 Source = Json.Document(Web.Contents(meurl1)) 处,我将在其中添加 meurl1&C2 或类似内容。 Any idea ?任何的想法 ?

let
meurl1 = Excel.CurrentWorkbook(){[Name="meurl1"]}[Content]{0}[Column1],
Source = Json.Document(Web.Contents(meurl1 )),
#"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
#"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", {"date", "close", "high", "low", "open"}, {"Column1.date", "Column1.close", "Column1.high", "Column1.low", "Column1.open"}),
#"Changed Type" = Table.TransformColumnTypes(#"Expanded Column1",{{"Column1.date", type datetime}}),
#"Renamed Columns" = Table.RenameColumns(#"Changed Type",{{"Column1.date", "Date"}, {"Column1.close", "Close"}, {"Column1.high", "High"}, {"Column1.low", "Low"}, {"Column1.open", "Open"}}),
#"Reordered Columns" = Table.ReorderColumns(#"Renamed Columns",{"Date", "Open", "High", "Low", "Close"}),
#"Sorted Rows" = Table.Sort(#"Reordered Columns",{{"Date", Order.Descending}})

in

The example below will load data for all tickers in a single table -- and not a separate table per ticker.下面的示例将在单个表中加载所有股票代码的数据——而不是每个股票代码的单独表格。

  1. Create a named range called tickers in your Excel file, which contains all tickers ( that you need to get data for) in a single column.在您的 Excel 文件中创建一个名为tickers的命名范围,该文件包含单个列中的所有股票代码(您需要为其获取数据)。

  2. Copy-paste the code below into the Advanced Editor in Power Query -- and then see if it gives you expected output.将下面的代码复制粘贴到 Power Query 的高级编辑器中,然后查看它是否提供了预期的输出。

I've included three examples ( verticalTable , horizontalTable and anotherHorizontalTable ).我已经包含了三个示例( verticalTablehorizontalTableanotherHorizontalTable )。 See which one of the three works best for you and your data.查看三者中的哪一个最适合您和您的数据。

I'm not sure what the value of meurl1 is in your file, so I've just copy-pasted it from your question.我不确定您的文件中meurl1的值是什么,所以我只是从您的问题中复制粘贴了它。


let
    tickers = Excel.CurrentWorkbook(){[Name="tickers"]}[Content][Column1],
    url = Excel.CurrentWorkbook(){[Name="meurl1"]}[Content]{0}[Column1],
    getTickerData = (someTicker as text) as table => 
        let
            response = Web.Contents(url & someTicker),
            parsed = Json.Document(response),
            toTable = Table.FromRecords(parsed, type table [
                date = datetime, open = number, high = number, low = number, close = number
            ])
        in toTable,
    // This approach should stack your ticker data vertically.
    // It's not what you asked for, but it might be a bit quicker than the approaches below.
    verticalTable = 
        let
            looped = List.Transform(tickers, each [ticker = _, data = getTickerData(ticker)]),
            toTable = Table.FromRecords(looped, type table [ticker = text, data = record]),
            expanded = Table.ExpandTableColumn(toTable, "data", {"date", "open", "high", "low", "close"}, {"Date", "Open", "High", "Low", "Close"})
        in expanded,
    // This approach will stack your ticker data horizontally, but with all tickers sharing a single
    // Date column.
    horizontalTable = 
        let
            allData = List.Transform(tickers, each [ticker = _, data = getTickerData(ticker)]),
            uniqueDates = List.Distinct(List.Combine(List.Transform(allData, each [data][date]))),
            looped = List.Accumulate(
                allData,
                Table.FromColumns({uniqueDates}, type table [Date = datetime]),
                (tableState as table, tickerData as record) as table =>
                    let
                        columnsToExpand = List.RemoveItems(Table.ColumnNames(tickerData[data]), {"date"}),
                        joined = Table.NestedJoin(tableState, "Date", tickerData[data], "date", "_toExpand"),
                        expanded = Table.ExpandTableColumn(joined, "_toExpand", columnsToExpand, List.Transform(columnsToExpand, each tickerData[ticker] & " (" & Text.Proper(_) & ")"))
                    in expanded
            )
        in looped,
    // This approach will stack your ticker data horizontally, but the difference here is each ticker
    // will have its own Date column.
    anotherHorizontalTable = 
        let
            looped = List.Accumulate(
                tickers,
                {},
                (tableColumns as list, ticker as text) as list =>
                    let
                        tickerTable = getTickerData(ticker),
                        renamed = Table.TransformColumnNames(tickerTable, each ticker & " (" & Text.Proper(_) & ")"),
                        columnNames = Table.ColumnNames(renamed),
                        columns = Table.ToColumns(renamed),
                        columnsWithMeta = List.Transform(List.Positions(columns), each columns{_} meta [columnName = columnNames{_}]),
                        combined = tableColumns & columnsWithMeta
                    in combined
            ),
            toTable = Table.FromColumns(looped, List.Transform(looped, each Value.Metadata(_)[columnName]))
        in toTable
in
    anotherHorizontalTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM