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
相关产品推荐
相关产品推荐

