使用win32:ole perl以行方式读取MS Word表数据

Apa*_*ant 6 perl ms-word perl-module win32ole

我是perl中win32:ole模块的新手.我试图在命令提示符下逐行打印MS word表数据.但我只能打印表格的最后一行.你能帮我解决这个问题吗?提前致谢.

以下是我的代码:

#!/usr/bin/perl 
use strict;
use warnings; 
use File::Spec::Functions qw( catfile );
use Win32::OLE qw(in); 
use Win32::OLE::Const 'Microsoft Word'; 
$Win32::OLE::Warn = 3; 

my $word = get_word(); 
$word->{DisplayAlerts} = wdAlertsNone; 
$word->{Visible} = 1;
my $doc = $word->{Documents}->Open('C:\\PerlScripts\\myTest.docx');
my $tables = $word->ActiveDocument->{'Tables'};

for my $table (in $tables)
{
   my $tableText = $table->ConvertToText({ Separator => wdSeparateByTabs });
   print "Table: ". $tableText->Text(). "\n";
}

$doc->Close(0); 

sub get_word 
{ 
    my $word; 
    eval { $word = Win32::OLE->GetActiveObject('Word.Application');}; 
    die "$@\n" if $@;
    unless(defined $word) 
    { 
       $word = Win32::OLE->new('Word.Application', sub { $_[0]->Quit }) 
       or die "Oops, cannot start Word: ", Win32::OLE->LastError, "\n"; 
    } 
  return $word; 
} 
Run Code Online (Sandbox Code Playgroud)

Rob*_*lty 2

无论如何,这都不是一个完美的解决方案,但这是该问题的一个进展。

我使用了字符串分隔符“\n\n”,它产生以下输出......

需要进一步的黑客攻击:(

C:\StackOverflow>perl  word.pl meTest.docx
Table: Header1
Header2
Header3
Header4
Row1-Cell1
Row1-Cell2
Row1-Cell3
Row1-Cell4
Row2-Cell1
Row2-Cell2
Row2-Cell3
Row2-Cell4
Row2-Cell5
Run Code Online (Sandbox Code Playgroud)

这是代码。我已经注释掉了表循环中的一些其他代码,这些代码是我用来破解 $tableRange->{Text} 返回的数据的。取消注释以进一步实验。

#!/usr/bin/perl 
use strict;
use warnings; 
use File::Spec::Functions qw( catfile );
use Win32::OLE qw(in); 
use Win32::OLE::Const 'Microsoft Word'; 
$Win32::OLE::Warn = 3; 

my $word = get_word(); 
$word->{DisplayAlerts} = wdAlertsNone; 
$word->{Visible} = 1;
my $doc = $word->{Documents}->Open('meTest.docx');
my $tables = $word->ActiveDocument->{'Tables'};

for my $table (in $tables)
{
   my $tableRange = $table->ConvertToText({ Separator => "\n\n" });
   print "Table: \n" . $tableRange->{Text}. "\n";
   # foreach $word (split/\n/, $tableRange->{Text}) {
   #  print $word . "\n" ;
   #  # $userinput =  <STDIN>;
   # }
}

$doc->Close(0); 

sub get_word 
{ 
    my $word; 
    eval { $word = Win32::OLE->GetActiveObject('Word.Application');}; 
    die "$@\n" if $@;
    unless(defined $word) 
    { 
       $word = Win32::OLE->new('Word.Application', sub { $_[0]->Quit }) 
       or die "Oops, cannot start Word: ", Win32::OLE->LastError, "\n"; 
    } 
  return $word; 
} 
Run Code Online (Sandbox Code Playgroud)

抱歉我无法提供更多帮助。