You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Power Query调用date.nager.at API获取全球节假日失败求助

修复后的Power Query代码及问题说明

问题定位

你的代码主要存在两个核心问题:

  • API URL拼接错误:在Table.AddColumn的each上下文里,需用_[CountryCode]引用当前行的国家代码,原代码直接写[CountryCode]无法正确取值
  • 缺少错误处理:部分国家可能无节假日数据或请求失败,会导致整个查询中断

修复后的代码

let
    Source = Json.Document(Web.Contents("https://date.nager.at/api/v3/AvailableCountries")),
    CountryCodesTable = Table.FromList(Source, Splitter.SplitByNothing(), {"CountryCode"}),
    SetColumnType = Table.TransformColumnTypes(CountryCodesTable, {{"CountryCode", type text}}),
    // 添加错误处理,避免单个国家请求失败导致全局中断
    AddHolidays = Table.AddColumn(SetColumnType, "Holidays", each 
        try Json.Document(Web.Contents("https://date.nager.at/api/v3/NextPublicHolidays/" & _[CountryCode])) 
        otherwise null),
    // 过滤无有效数据的行
    RemoveNullHolidays = Table.SelectRows(AddHolidays, each [Holidays] <> null),
    ExpandHolidaysList = Table.ExpandListColumn(RemoveNullHolidays, "Holidays"),
    ExpandHolidaysDetails = Table.ExpandRecordColumn(ExpandHolidaysList, "Holidays", 
        {"date", "localName", "name", "countryCode"}, 
        {"HolidayDate", "LocalName", "Name", "CountryCode_FromAPI"}),
    // 统一字段类型,兼容可能的空值
    FinalTypeTransform = Table.TransformColumnTypes(ExpandHolidaysDetails, {
        {"CountryCode", type text},
        {"HolidayDate", type date},
        {"LocalName", type text},
        {"Name", type text},
        {"CountryCode_FromAPI", type text}
    })
in
    FinalTypeTransform

关键调整说明

  • 修正URL拼接逻辑:用_[CountryCode]正确获取当前行的国家代码,实现动态API请求
  • 增加错误捕获:通过try otherwise null处理单个国家的请求失败,保证查询整体可用性
  • 过滤无效数据:移除无节假日数据的行,减少冗余内容
  • 补充API返回的countryCode字段,与原列做交叉验证
  • 删除无意义的重复重命名步骤

内容的提问来源于stack exchange,提问作者milenjao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 07:02:44