【问题标题】:How can I navigate Word tables using WIN32::OLE perl package?如何使用 WIN32::OLE perl 包导航 Word 表?
【发布时间】:2017-05-07 03:38:21
【问题描述】:

我有一个包含数百个单词文档的目录,每个文档都包含一组标准化的表格。我需要解析这些表并提取其中的数据。我开发了吐出整个表格的脚本。

#!/usr/bin/perl;
use strict;
use warnings;

use Carp qw( croak );
use Cwd qw( abs_path );
use Path::Class;
use Win32::OLE qw(in);
use Win32::OLE::Const 'Microsoft Word';
$Win32::OLE::Warn = 3;
=d
my $datasheet_dir = "./path/to/worddocs";
my @files = glob "$datasheet_dir/*.doc";
print "scalar: ".scalar(@files)."\n";
foreach my $f (@files){
    print $f."\n";
}
=cut
#my $file = $files[0];
my $file = "word.doc";
print "file: $file\n";

run(\@files);

sub run {
    my $argv = shift;
    my $word = get_word();

    $word->{DisplayAlerts} = wdAlertsNone;
    $word->{Visible}       = 1;

    for my $word_file ( @$argv ) {
        print_tables($word, $word_file);
    }

    return;
}

sub print_tables {
    my $word = shift;
    my $word_file = file(abs_path(shift));

    my $doc = $word->{Documents}->Open("$word_file");
    my $tables = $word->ActiveDocument->{Tables};

    for my $table (in $tables) {
        my $text = $table->ConvertToText(wdSeparateByTabs)->Text;
        $text =~ s/\r/\n/g;
        print $text, "\n";
    }

    $doc->Close(0);
    return;
}

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

有没有办法导航单元格?我只想返回在第一列中具有特定值的行?

例如,对于下表,我只想 grep 第一列有水果的行。

apple       pl
banana      xml
California  csv
pickle      txt
Illinois    gov
pear        doc

【问题讨论】:

    标签: perl cpan


    【解决方案1】:

    在首先使用Columns 对象和Rows 集合获取维度之后,您可以使用 OLE 访问表格的各个单元格。

    或者您可以将文本后处理为 Perl 数组,然后对其进行迭代。 而不是

    my $text = $table->ConvertToText(wdSeparateByTabs)->Text;
    $text =~ s/\r/\n/g;
    print $text, "\n";
    

    类似

    my %fruit; # population of look-up table of fruit omitted
    
    my $text = $table->ConvertToText(wdSeparateByTabs)->Text;
    my @lines = split /\r/, $text;
    for my $line ( @lines ) {
        my @fields = split /\t/, $lines;
    
        next unless exists $fruit{$fields[0]};
    
        print "$line\n";
    }
    

    可以根据需要添加区分大小写等的改进。

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      相关资源
      最近更新 更多