[英]How to find a table in word and update values in the table using delphi
我假设您主要是在问如何找到表,而不是随后如何更改表的内容。 如何执行此操作取决于您要用来查找关注表的条件。
从表面上看,您应该能够使用MS Word的Selection对象的Goto方法导航到给定的表。 但是,存在一个问题(请参见此答案的结尾),以检测由于Goto找不到正确的表而导致操作何时失败。
如果感兴趣的表在文档中带有可识别的文本标签,则可以简单地搜索该标签,如果找到该标签,则可以从中向前导航,例如本示例,该示例在标签“ Table3”之后找到该表:
procedure TForm1.Button4Click(Sender: TObject);
var
AFileName : String;
MSWord,
Document : OleVariant;
Found : WordBool;
begin
AFileName := 'd:\aaad7\officeauto\Tables.Docx';
MSWord := CreateOleObject('Word.Application');
MSWord.Visible := True;
Document := MSWord.Documents.Open(AFileName);
MSWord.Selection.Find.Text :='Table3';
Found := MSWord.Selection.Find.Execute;
if Found then begin
MSWord.Selection.MoveDown( Unit:=wdLine, Count:=1);
end;
end;
如所写,“ if Found ...”块仅将光标置于表的第一个单元格的第一个字符上。 进入表格后,您可以随意更改其内容。
如果要查找如何在表格单元格中插入图像之类的方法,请转到Word功能区上的“开发人员”选项卡,记录一个可以执行所需操作的宏,然后使用“ 宏”弹出窗口中的“ 编辑 ”来查看它-通常很容易,然后将其剪切并粘贴到Delphi中,然后将其编辑为等效的Delphi代码。 查找所需表的其他方法也是如此-记录宏然后对其进行翻译。
要在文档中找到第N个表格并将光标放在其左上角的单元格中,可以执行以下操作:
procedure TForm1.Button2Click(Sender: TObject);
var
AFileName : String;
MSWord,
Document,
Tables,
Table : OleVariant;
TableNo : Integer;
begin
AFileName := 'd:\aaad7\officeauto\Tables.Docx';
MSWord := CreateOleObject('Word.Application');
MSWord.Visible := True;
Document := MSWord.Documents.Open(AFileName);
TableNo := 3;
Tables := Document.Tables;
if TableNo <= Tables.Count then begin
Table := Tables.Item(TableNo);
Table.Select;
MSWord.Selection.MoveLeft( Unit:=wdCharacter, Count:=1);
end;
end;
顺便说一句,在Word的“查找”对话框的“ Goto
选项卡上,“ Go to what
列表框中有“ Table
条目。 您可以使用类似的代码在代码中调用它
MSWord.Selection.GoTo(What:= wdGoToTable, Which:=wdGoToFirst, Count:=3);
它的问题是如何检入代码是否成功。 与查找返回WordBool
查找不同,Goto返回一个Range对象。 如果尝试使用它转到仅包含2个表的文档中的第10个表,则不会引发错误,但是返回的范围是文档中的最后一个表。 我还没有找到一种方法来从返回的Range中检查Goto是否成功,而不检查与表相关联的某些文本,而这些文本最初可能是使用Find找到的。 当然,如果保证文档包含您要查找的表,则Goto的此问题可能与您无关。
也许像:
Word.ActiveDocument.Tables.Item(1).Cell(1,1).Range.Text:='某些文本';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.