word2003的文档中包含了5000个人员情况登记表格,如下:能否自动地将每张表中姓名一栏的内容替换表标题处的XX内容,如:在第1张表中,将“张三”字符串替换表标题处的XX。已经试了一星期了,也解决不了。各位TX帮帮忙吧,谢谢了!

解决方案 »

  1.   


    procedure TForm1.Button1Click(Sender: TObject);
    var
      tableName:string;
      TableCount:integer;
      i:integer;
      SelectionStart,SelectionEnd:integer;
    begin
      wordApp:=CreateOleObject('word.application');
      wordapp.visible:=true;
      wordapp.documents.open('C:\Users\lenovo\Desktop\北京.doc');  TableCount:=wordapp.activeDocument.tables.count;
      //获取第一张表名
      //表1 xx记录  建议你全部以这种格式('表'+数字+空格+表名+'记录')   现在要做的是获取 tableName=xx;
      //建议用一个 循环来查找  表1..表TableCount  获取每张表的tableName  //将第一个表中  cell(rol,col) 赋值为  你想要的表格名
      for i:=1 to TableCount do
      begin
        wordapp.selection.find.clearFormatting;
        wordapp.selection.find.text:='表'+IntToStr(i);
        wordapp.selection.find.wrap:=2; //wdFindStop 到达搜索区域的开始或者结尾时,停止执行查找操作。
        wordapp.selection.find.execute;
        SelectionStart:=wordapp.selection.end+1;//中间有空格 所以+1;    //搜索'记录'
        wordapp.selection.find.clearFormatting;
        wordapp.selection.find.text:='记录';
        wordapp.selection.find.wrap:=2; //wdFindStop 到达搜索区域的开始或者结尾时,停止执行查找操作。
        wordapp.selection.find.execute;
        SelectionEnd:=wordapp.selection.start;    wordapp.selection.start:=SelectionStart;
        wordapp.selection.end:=SelectionEnd;
        tableName:=wordapp.selection.text;
        //将表i中  cell(rol,col) 赋值为  你想要的表格名
        wordapp.activeDocument.tables.item(i).cell(1,2).range.delete;
        wordapp.activeDocument.tables.item(i).cell(1,2).range.InsertAfter(tableName);
      end;
    end;应该是可解决你问题了
    主要就是word api的操作  http://download.csdn.net/detail/xsl510079027/4200269
      

  2.   

    你有看到我写循环吧   是从 表1..表n 我也亲自测试过是可以的。如果果你每次查找表1后查不到表2 原因应该是查找完表1,进入到了文档末尾。wordapp.selection.find.wrap:=2; //wdFindStop 到达搜索区域的开始或者结尾时,停止执行查找操作。按理说不会出现这种情况,可能wrap的值我记错了。。所以在循环一开始应该加上一句wordapp.selection.homeKey(wdstory);//wdstory=0回到篇首。这样只是浪费效率一点,应该是不会有问题。
      

  3.   

    呵呵,果然是这样的!调通了,就是感觉在写word时,来回倒腾,效率低些,但绝对可行。谢谢了,大侠!!!真心谢谢。