How can I merge two Excel (xls) files in Perl or batch?

后端 未结 3 2114
后悔当初
后悔当初 2021-01-14 18:13

I have two files lets say a.xls and b.xls. The first one contains 2 sheets and the second one 3 of them. Can someone let me know if I can merge the

3条回答
  •  孤独总比滥情好
    2021-01-14 18:55

    If you are running on Windows, have Excel installed and can use Win32::OLE (e.g. the script will not be invoked by a web server etc), the following should work:

    #!/usr/bin/perl
    
    use warnings;
    use strict;
    
    use FindBin qw($Bin);
    use File::Spec::Functions qw( catfile );
    
    use Win32::OLE qw(in);
    use Win32::OLE::Const 'Microsoft Excel';
    $Win32::OLE::Warn = 3;
    
    my $excel = get_excel();
    $excel->{Visible} = 1; # for illustration only
    
    my @src = map $excel->Workbooks->Open($_),
              map catfile($Bin, $_),
              qw(one.xls two.xls)
              ;
    
    my $target = $excel->Workbooks->Add(xlWBATWorksheet);
    my $before = $target->Worksheets->Item(1);
    
    for my $book ( @src ) {
        my $sheets = $book->Worksheets;
        my $it = Win32::OLE::Enum->new($sheets);
    
        while (defined(my $sheet = $it->Next)) {
            $sheet->Copy($before);
        }
    }
    
    $before->Delete;
    
    $_->Close for @src;
    $target->SaveAs(catfile($Bin, 'test.xls'));
    $target->Close;
    
    sub get_excel {
        my $excel = Win32::OLE->GetActiveObject('Excel.Application');
        unless(defined $excel) {
            $excel = Win32::OLE->new('Excel.Application', sub { $_[0]->Quit })
                or die "Oops, cannot start Excel: ",
                       Win32::OLE->LastError, "\n";
        }
        return $excel;
    }
    

提交回复
热议问题