Libreoffice basic - 关联数组

Posted

技术标签:

【中文标题】Libreoffice basic - 关联数组【英文标题】:Libreoffice basic - Associative array 【发布时间】:2016-05-11 19:07:59 【问题描述】:

我来自 php/JS/AS3/...这种语言。现在我正在学习 Libreoffice 的基础知识,并且我正在努力寻找如何获得与用于其他语言的关联数组类似的东西。

我想做的是拥有这种结构:

2016 => 十月 => 文件名.csv

2016 => 四月 => anotherfilename.csv

以年份为主键,然后是月份和一些数据。 更多我尝试查找信息,更多我感到困惑,所以如果有人能告诉我一些关于如何组织我的数据的信息,我会很高兴。

谢谢!

【问题讨论】:

【参考方案1】:

正如@Chrono Kitsune 所说,Python 和 Java 具有这些功能,但 Basic 没有。这是 LibreOffice Writer 的 Python-UNO 示例:

def dict_example():
    files_by_year = 
        2016 : 'October' : 'afilename.csv',
                'November' : 'bfilename.csv',
        2017 : 'April' : 'anotherfilename.csv',
    
    doc = XSCRIPTCONTEXT.getDocument()
    oVC = doc.getCurrentController().getViewCursor()
    for year in files_by_year:
        for month in files_by_year[year]:
            filename = files_by_year[year][month]
            oVC.getText().insertString(
                oVC, "%s %d: %s\n" % (month, year, filename), False)

g_exportedScripts = dict_example,

使用文本编辑器(如记事本或 GEdit)创建包含上述代码的文件。然后放到here。

要运行它,打开 Writer 并转到 Tools -> Macros -> Run Macro,然后在 My Macros 下找到文件。

【讨论】:

【参考方案2】:

我不熟悉 LibreOffice(或 OpenOffice.org)BASIC 或 VBA,但我没有在文档中找到任何类型的关联数组、散列或其他人称之为的任何内容。

但是,许多现代 BASIC 方言允许您 define your own type as a series of fields。那么这只是使用类似的东西的问题

Dim SomeArray(count|range) As New MyType

我认为这与您在不利用外部库的情况下所获得的一样接近。也许 Python-UNO bridge 会有所帮助,因为 Python 具有这样的功能(字典),但我不确定。我也不知道它会如何影响性能。您可能更喜欢 Java 而不是 Python 来与 UNO 交互,这也可以:有 java.util.HashMap 类型。抱歉,我帮不上忙,但要记住的重要一点是,任何 BASIC 代码在没有外部帮助的情况下,往往都符合英语中“基本”一词的含义。

【讨论】:

【参考方案3】:

这个问题很久以前就问过了,但答案只对了一半。

确实,LibreOffice Basic 没有原生关联数组类型。但是 LibreOffice API 提供服务。 com.sun.star.container.EnumerableMap 服务将满足您的需求。

这是一个例子:

' Create the map
map = com.sun.star.container.EnumerableMap.create("long", "any")

' The values
values = Array( _
    Array(2016, "October", "afilename.csv"), _
    Array(2016, "April", "anotherfilename.csv") _
)

' Fill the map
For i=LBound(values) to UBound(values)
    value = values(i)
    theYear = value(0)
    theMonth = value(1)
    theFile = value(2)
    If map.containsKey(theYear) Then
        map2 = map.get(theYear)
    Else
        map2 = com.sun.star.container.EnumerableMap.create("string","string")
        map.put(theYear, map2)
    End If
    map2.put(theMonth, theFile)
Next

' Access to an element
map.get(2016).get("April")  ' anotherfilename.csv

如您所见,这些方法与您可以在更常用的语言中找到的方法相似。

注意:如果您遇到IllegalTypeException,您可能必须使用CreateUNOValue("<type>", ...) 将值转换为声明的类型。 (例如,请参阅这个非常老的问题https://bz.apache.org/ooo/show_bug.cgi?id=121192。)

【讨论】:

以上是关于Libreoffice basic - 关联数组的主要内容,如果未能解决你的问题,请参考以下文章

LibreOffice Basic:用于拆分字符串的现有实用程序?

使用 LibreOffice Basic 迭代控件

如何在 Basic 中使用 LibreOffice 功能?

在 Basic 中计算自己的对数(LibreOffice Calc Macro)

在 LibreOffice 宏的 Basic 中获取文档路径

使用 BASIC 在 LibreOffice 中复制表格的最后一行