如何使用userDefinedProperties在LibreOffice中存储会话持久对象变量?
LibreOffice 会话持久变量存储解决方案
能否存储复杂对象?
不行。LibreOffice的用户定义文档属性(UserDefinedProperties)仅支持基础数据类型(字符串、整数、浮点数、日期、布尔值等),无法直接存储ScCellObj这类复杂对象。原因是文档属性属于可序列化的元数据,复杂对象无法被序列化保存到文档中。
如果需要关联复杂对象,只能存储其唯一标识(比如单元格的地址字符串),后续通过标识重新获取对象。
你的代码问题排查与修正
核心错误点
- 尝试直接存储
ScCellObj对象:违反了属性存储的类型限制。 - 误用
setPropertyValues方法:该方法需要传入数组参数,单个值应使用setPropertyValue(单数形式)。 - 对
addProperty参数理解模糊:下面详细解释参数含义。
addProperty 参数详解
addProperty(Name As String, Attributes As Long, DefaultValue As Any):
- 第一个参数:属性名称(如你的
nom = "test")。 - 第二个参数(Attributes):属性行为掩码,是
com.sun.star.beans.PropertyAttribute常量的数值组合,常用值:2(READWRITE):允许读写属性值128(MAYBEVOID):允许属性值为空- 通常组合使用
2 + 128,满足基础读写需求。
- 第三个参数(DefaultValue):属性的默认值,必须与后续存储的数据类型一致(如存字符串就传空字符串,存数字传
0),不能传入对象。
修正后的代码示例
下面的代码将单元格地址转换为字符串存储,后续可通过地址重新获取单元格对象:
dim docprops as object dim userprops as object dim usersetinf as object dim cell as object dim nom as string dim cellAddrStr as string nom = "test" cell = thiscomponent.sheets.getbyname("Ingrédients").getcellbyposition(0,0) ' 将单元格转换为可存储的地址字符串(格式:工作表名.单元格引用) cellAddrStr = cell.Sheet.Name & "." & cell.AbsoluteName.Split(".")(1) on error goto err_handler docprops = thiscomponent.getdocumentproperties() userprops = docprops.userdefinedproperties usersetinf = userprops.getpropertysetinfo() ' 移除已存在的同名属性 if usersetinf.haspropertybyname(nom) then userprops.removeproperty(nom) end if ' 添加属性:读写权限+允许为空,默认值为空字符串 userprops.addProperty(nom, 2 + 128, "") ' 设置属性值为单元格地址字符串 userprops.setPropertyValue(nom, cellAddrStr) ' --- 后续读取存储的单元格示例 --- dim storedAddrStr as string dim storedCell as object dim parts() as string storedAddrStr = userprops.getPropertyValue(nom) parts = Split(storedAddrStr, ".") ' 根据地址字符串重新获取单元格对象 storedCell = thiscomponent.Sheets.getByName(parts(0)).getCellRangeByName(parts(1)) msgbox "存储的单元格内容:" & storedCell.String err_handler: if err.Number <> 0 then msgbox "错误信息:" & err.Description end if
代码说明
- 存储阶段:将单元格的工作表名称和单元格引用(如
Ingrédients.A1)拼接成字符串保存,规避了对象存储的限制。 - 读取阶段:拆分存储的字符串,通过工作表名和单元格引用重新定位到目标单元格。
内容的提问来源于stack exchange,提问作者Denis M
相关产品推荐
相关产品推荐

