Power BI报表获取当前文件名失败,求可行解决方案
Power BI 获取当前文件名的可行方案
已尝试的无效方案
以下DAX与M语言脚本及操作均无法获取当前PBIX文件名:
- DAX公式:
FileName = VAR FilePath = LEFT(PATH(), FIND("[", PATH(), 1) - 2) RETURN RIGHT(FilePath, LEN(FilePath) - FIND("", REVERSESTRING(FilePath), 1))
FileName = FIRSTNONBLANK(FileNameQuery[FileName], 1)
Current File Name = VALUE.NATIVEQUERYMETADATA()[Source.Name]
Current File Name Without Extension = REPLACELASTSTRING( VALUE.NATIVEQUERYMETADATA()[Source.Name], ".pbix", "" )
- M语言脚本:
let Source = #shared, CurrentWorkbook = Source{[Name="CurrentWorkbook"]}[Content], FileName = CurrentWorkbook{[Name="Name"]}[Content] in FileName
let Source = #table({"FileName"}, {{Uri.LocalFileFromPath(#shared[Content])}}) in Source
- 操作步骤:在Power Query中创建空白查询输入
=[Source.Name],生成文件名列后引用到模型,再在DAX中调用,无效。
可行解决办法
方法1:Power Query直接读取导航属性
创建新空白查询,输入以下M代码:
let GetFileName = () => let PBIXProps = #shared[PowerBI.DataSource].NavigationProperties() in PBIXProps[FileName], CurrentFileName = GetFileName() in CurrentFileName
执行后即可得到带扩展名的当前文件名。若需移除扩展名,修改代码为:
let GetFileName = () => let PBIXProps = #shared[PowerBI.DataSource].NavigationProperties(), FullName = PBIXProps[FileName], NameWithoutExt = Text.BeforeDelimiter(FullName, ".") in NameWithoutExt, CurrentFileName = GetFileName() in CurrentFileName
将该查询加载到数据模型后,可在DAX中直接引用,例如='FileNameQuery'[Value]。
方法2:通过文件夹文件属性匹配获取
若方法1失效,可通过文件修改时间匹配获取文件名:
- 创建空白查询,输入以下M代码作为自定义函数:
(GetCurrentPBIXName) => let PBIXPath = #shared[PowerBI.DataSource].NavigationProperties()[FilePath], FolderPath = Path.GetDirectoryName(PBIXPath), FolderFiles = Folder.Files(FolderPath), FilteredFiles = Table.SelectRows(FolderFiles, each [Extension] = ".pbix" and [Date modified] = #shared[PowerBI.DataSource].NavigationProperties()[LastModified]), TargetFileName = FilteredFiles{0}[Name] in TargetFileName
- 调用该函数即可获取当前文件名。注意:需确保当前文件夹中无其他同修改时间的PBIX文件,避免匹配错误。
内容的提问来源于stack exchange,提问作者Dmitri Braverman
相关产品推荐
相关产品推荐

