从Delphi修改Excel形状
如何从Delphi中修改现有的 Excel形状的文本?
我可以创build一个新的形状,并设置其文本
procedure TForm1.Button1Click(Sender: TObject); var excel, xlShape : variant; begin olecontainer1.CreateObject('Excel.Application',false); excel := olecontainer1.OleObject; excel.workbooks.open('C:\test.xls'); XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200); XlShape.textframe.characters.text:='new shape created from Delphi';
但是,如果形状已经存在,我怎样才能select它来改变它的文本属性? 就像是:
excel.application.worksheets[1].Shapes('shape1').textframe.characters.text := 'This gives error';
试试这个代码
procedure TForm1.ButtonClick(Sender: TObject); var excel, xlShape : variant; begin olecontainer1.CreateObject('Excel.Application',false); excel := olecontainer1.OleObject; excel.workbooks.open('C:\test.xls'); XlShape:=excel.ActiveSheet.Shapes.Item(1);// or like this .Item('Rectangle 1'); if VarIsEmpty(xlShape) then begin XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200); XlShape.textframe.characters.text:='new shape created from Delphi'; end else ShowMessage(XlShape.textframe.characters.text); excel.activeworkbook.close; xlShape:=Unassigned; excel:=Unassigned; OleContainer1.DestroyObject; end;
XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200); XlShape.Name := "mycustomshape";
所以,当你知道形状的名字时,可以用名字来引用它
excel.application.worksheets[1].Shapes('mycustomshape').textframe.characters.text := 'This doesnt gives error';
或者,您可以使用索引(基于0)来引用它。 我假设它是工作表中的第一个形状对象。
excel.application.worksheets[1].Shapes(0).textframe.characters.text := 'This doesnt gives error';
编辑:我不知道delphi在语法方面是如何不同。
看看是否使用方括号 (而不是常规括号)的作品
excel.application.worksheets[1].Shapes['mycustomshape'].textframe.characters.text := 'This doesnt gives error';
要么
excel.application.worksheets[1].Shapes[0].textframe.characters.text := 'This doesnt gives error';