LibreOffice Calc C# SDK插入图片至单元格遇XGraphic相关问题
在LibreOffice Calc中通过SDK添加图片的问题与解决障碍
背景
我正在编写程序将图片添加到LibreOffice Calc的单元格中,但LibreOffice近期修改了实现方式,网上现有示例都是已失效的旧方法。
注:技术上无法将图片“插入”单元格,这类图片是位于电子表格上方DrawPage上的叠加层,用于“装饰”表格。
采用新方式的核心步骤之一是创建包含图片的XGraphic对象:需要先创建XGraphicProvider,再传入指定图片文件URL的MediaProperties。
第一个问题:XGraphic为空(已排查出原因)
最初实现时生成的XGraphic为空,LibreOffice SDK报错信息极少。相关代码如下:
// addpic // add picture to spreadsheet - debug version class OpenOfficeApp { [STAThread] static void Main(string[] args) { bool lreadonly; string pqfile; string pqURL; string pqpic; pqfile = "file:///D:/Documents/NSexeye/ODS%20File%20Access/"+ "addpix/addpic.ods"; pqpic = "addpic2"; pqURL = pqpic+".jpg"; lreadonly = false; Console.WriteLine("Using: "+pqfile); // get the desktop XComponentContext XCC = uno.util.Bootstrap.bootstrap(); XMultiComponentFactory XMCF = (XMultiComponentFactory)XCC.getServiceManager(); XMultiServiceFactory XMSF = (XMultiServiceFactory)XCC.getServiceManager(); XComponentLoader XCL = (XComponentLoader)XMSF.createInstance("com.sun.star.frame.Desktop"); // open the spreadsheet PropertyValue[] pPV = new PropertyValue[2]; pPV[0] = new PropertyValue(); pPV[0].Name = "Hidden"; pPV[0].Value = new uno.Any(true); pPV[1] = new PropertyValue(); pPV[1].Name = "ReadOnly"; if (lreadonly) pPV[1].Value = new uno.Any(true); else pPV[1].Value = new uno.Any(false); XComponent XCo = XCL.loadComponentFromURL(pqfile,"_blank",0,pPV); // create graphic object containing image object oGP = XMCF.createInstanceWithContext( "com.sun.star.graphic.GraphicProvider",XCC); if (oGP == null) { Console.WriteLine("oGP is null. Aborting."); return; } XGraphicProvider XGP = (XGraphicProvider)oGP; if (XGP == null) { Console.WriteLine("XGP is null. Aborting."); return; } pPV = new PropertyValue[1]; pPV[0] = new PropertyValue(); pPV[0].Name = "URL"; pPV[0].Value = new uno.Any(pqURL); Console.WriteLine("Creating XGraphic containing "+pqURL); XGraphic XG = XGP.queryGraphic(pPV); // *** XG is null here if (XG == null) { Console.WriteLine("XG is null. Aborting."); return; } // ... lots of stuff to be added here // save and close the spreadsheet XModifiable XM = (XModifiable)XCo; XM.setModified(true); XStorable XSt = (XStorable)XCo; XSt.store(); XCloseable XCl = (XCloseable)XCo; XCl.close(true); // terminate LibreOffice // *** I want this to not terminate it if something else is open XDesktop XD = (XDesktop)XCL; if (XD != null) XD.terminate(); } }
排查后发现问题:向XGraphicProvider的URL属性传入了裸文件名,需要使用与电子表格文件名一致的file:///格式。
当前问题:XGraphic转uno.Any的编译错误
现在需要将XGraphic指定为GraphicObjectShape的Graphic属性,但setPropertyValue()要求参数为uno.Any类型,尝试直接传入XG或者new uno.Any(XG)都编译失败,相关代码如下:
// set image XGraphic XPropertySet XPS = (XPropertySet)XS; XPS.setPropertyValue("Graphic",XG); XPS.setPropertyValue("Name",new uno.Any(pqpic));
我的目标是编写一个可运行的、向Calc单元格添加及操作图片的示例程序,这类需求较多但目前没有可用的最新示例,寻求LibreOffice SDK开发者的帮助。
内容的提问来源于stack exchange,提问作者user7505909
相关产品推荐
相关产品推荐

