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

在LibreOffice Calc的VBA中提取JSON响应指定字段值

改造LibreOffice Calc的GetSun函数,支持返回指定日出日落字段值

我在Linux Mint系统的LibreOffice Calc中编写了GetSun函数,调用日出日落API获取JSON格式响应,但当前函数仅返回完整JSON内容。需要修改函数,使其支持传入指定字段参数(如sunrise、sunset),仅返回对应字段的值。例如调用=GETSUN(C12,C13,B6,sunrise)时返回“5:42:35 AM”,调用=GETSUN(C12,C13,B6,sunset)时返回“7:43:53 PM”。

原函数代码

Function GetSun(lat,lon As Double, dateinput As Date) As String
Dim url as String
url = "https://api.sunrise-sunset.org/json?lat=" & lat & "&lng=" & lon & "&date=" & dateinput

On Error GoTo ErrorHandler

Dim funtionAccess As Object
functionAccess = createUnoService("com.sun.star.sheet.FunctionAccess")

GetSun = functionAccess.callFunction("WEBSERVICE",Array(url))

Exit Function
ErrorHandler:
GetSun = "Error " & Err
End Function

修改后的函数代码

Function GetSun(lat As Double, lon As Double, dateinput As Date, Optional field As String) As String
    Dim url As String
    Dim jsonResponse As String
    Dim jsonObj As Object
    Dim functionAccess As Object
    
    ' 构建API请求URL
    url = "https://api.sunrise-sunset.org/json?lat=" & lat & "&lng=" & lon & "&date=" & dateinput
    
    On Error GoTo ErrorHandler
    
    ' 获取API响应
    functionAccess = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    jsonResponse = functionAccess.callFunction("WEBSERVICE", Array(url))
    
    ' 解析JSON响应
    jsonObj = CreateUnoService("com.sun.star.script.JSON")
    jsonObj = jsonObj.parse(jsonResponse)
    
    ' 根据参数判断返回内容
    If IsMissing(field) Then
        ' 无字段参数时返回完整JSON
        GetSun = jsonResponse
    Else
        ' 从results节点提取指定字段值
        If jsonObj.has("results") Then
            Dim resultsObj As Object
            resultsObj = jsonObj.get("results")
            If resultsObj.has(field) Then
                GetSun = resultsObj.get(field)
            Else
                GetSun = "字段不存在: " & field
            End If
        Else
            GetSun = "API响应格式错误"
        End If
    End If
    
    Exit Function
    
ErrorHandler:
    GetSun = "错误: " & Err.Description
End Function

关键修改说明

  • 新增可选参数field,用于指定要返回的目标字段(如sunrise、sunset)
  • 引入com.sun.star.script.JSON服务解析JSON,无需依赖外部工具
  • 增加多场景判断:
    • 未传入field时,保留原逻辑返回完整JSON
    • 传入field时,从API响应的results节点下提取对应值
    • 针对字段不存在、响应格式错误等情况添加提示信息
  • 优化错误处理,返回具体错误描述而非仅错误码

调用示例

  • 返回完整JSON:=GETSUN(C12,C13,B6)(C12=纬度,C13=经度,B6=日期)
  • 返回日出时间:=GETSUN(C12,C13,B6,"sunrise")
  • 返回日落时间:=GETSUN(C12,C13,B6,"sunset")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:32:41