如何在 word 中查找 table 并使用 delphi 更新 table 中的值

How to find a table in word and update values in the table using delphi

我是使用 Delphi 进行 Ole 单词自动化的新手。我有一个示例文档,里面有很多 table。我可以通过在 word 中找到一个形状并在其中插入值来插入图像。但是我无法找到特定的 table 并使用 delphi 将一些值更新到其中。有办法吗?谢谢 !

可能是这样的:

Word.ActiveDocument.Tables.Item( 1 ).Cell( 1, 1 ).Range.Text := 'some text';

我假设您主要是问如何找到 table,而不是之后如何更改 table 的内容。如何执行此操作取决于您要用于查找感兴趣的 table 的条件。

从表面上看,您应该能够使用 MS Word 的 Selection 对象的 Goto 方法导航到给定的 table。但是,由于 Goto 没有找到正确的 table.

,在检测操作何时失败时存在问题(请参阅此答案的末尾)

如果文档中感兴趣的 table 前面有一个识别文本标签,您可以简单地搜索该标签,如果找到,则从该标签向前导航,就像这个找到 table标签后'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 ..." 块仅将光标放在 table 的第一个单元格的第一个字符上。进入 table 后,您可以随意更改其内容。

如果您想了解如何在 table 单元格中插入图像,请转到 Word 功能区上的“开发人员”选项卡,录制一个执行所需操作的宏,然后使用 EditMacros 弹出窗口中查看 - 通常很容易将其剪切并粘贴到 Delphi 中并进行编辑进入等效的 Delphi 代码。查找所需 table 的其他方法也是如此 - 录制宏然后翻译它。

要在文档中找到第 N 个 table 并将光标放在其左上角的单元格中,您可以这样做:

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);  

它的问题是如何检查代码是否成功。与 Find returns 一个 WordBool 不同,Goto returns 一个 Range 对象。如果您尝试使用它转到仅包含 2 个 table 的文档中的第 10 个 table,则不会引发错误,但返回的范围是最后一个 table文档。我还没有找到一种方法来检查返回的 Range Goto 是否成功,而不检查与 table 关联的一些文本,这些文本本来可以首先使用 Find 找到的。当然,如果文档保证包含您要查找的 table,Goto 的这个问题可能不需要您担心。