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

C#中使用LibreOffice XSheetAnnotationShapeSupplier调整批注大小遇类型转换异常

C#中使用LibreOffice XSheetAnnotationShapeSupplier调整批注大小遇类型转换异常

嘿,我来帮你搞定这个问题!你碰到的System.InvalidCastException,核心原因很明确:XSheetAnnotationShapeSupplier接口根本不是由XSpreadsheet对象实现的——这个接口是属于单个单元格批注(SheetAnnotation)的,不是整个工作表对象,直接转工作表肯定会报错。

下面是修正后的完整思路和代码,适配你的sAnnotation函数需求:

正确操作步骤

  • 先定位到目标单元格,获取对应的XCell对象
  • 检查该单元格是否已有批注,没有则创建新批注
  • 把批注对象转换成XSheetAnnotationShapeSupplier(这才是正确的转换对象)
  • 通过接口获取批注的形状对象,再设置它的位置和大小

修正后的代码示例

using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.table;
using unoidl.com.sun.star.drawing;
using unoidl.com.sun.star.uno;

public bool sAnnotation(string strCell, string strAnnotation, int x, int y, int nWidth, int nHeight)
{
    try
    {
        // 1. 解析单元格地址,获取目标单元格对象(假设你已持有XSpreadsheet实例xSpreadsheet)
        XCellRange xCellRange = xSpreadsheet.getCellRangeByName(strCell);
        XCell xCell = xCellRange.getCellByPosition(0, 0);

        // 2. 获取或创建单元格批注
        XSheetAnnotation xAnnotation = null;
        XSheetAnnotationAnchor xAnchor = (XSheetAnnotationAnchor)xCell;
        xAnnotation = xAnchor.getAnnotation();
        
        if (xAnnotation == null)
        {
            // 无批注则创建新的
            XSheetAnnotations xAnnotations = xSpreadsheet.getAnnotations();
            xAnnotations.insertNew(xCell.getCellAddress(), strAnnotation);
            xAnnotation = xAnchor.getAnnotation();
        }
        else
        {
            // 已有批注则更新内容
            xAnnotation.setAnnotationText(strAnnotation);
        }

        // 3. 正确转换为XSheetAnnotationShapeSupplier(注意是批注对象,不是工作表)
        XSheetAnnotationShapeSupplier xShapeSupplier = (XSheetAnnotationShapeSupplier)xAnnotation;
        if (xShapeSupplier != null)
        {
            // 4. 调整批注的位置和大小
            XShape xShape = xShapeSupplier.getAnnotationShape();
            xShape.setPosition(new Point(x, y));
            xShape.setSize(new Size(nWidth, nHeight));
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"操作批注出错:{ex.Message}");
    }
    return false;
}

关键提醒

一定要记牢:XSheetAnnotationShapeSupplier是批注专属的接口,只能从单元格批注对象(XSheetAnnotation)转换而来,和工作表对象没有直接关系,这就是你之前转换报错的核心原因。

备注:内容来源于stack exchange,提问作者Jump6024

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 16:38:19