简体   繁体   中英

How to print the outputs on excel file to each columns by using perl?

How to write the output in each rows and each columns?

use Win32::OLE;
@a = (1..5);
@b = (20..30);
@c = (30..48);
@array = ("@a","@b","@c");
my $xl = Win32::OLE->new('Excel.Application');
$xl->{EnableEvents} = 0;
$xl->{Visible} = 1;
my $wb = $xl->Workbooks->Add;
my $sht = $wb->Sheets(1);
$sht->{Name} = "Occurance";
foreach $s (@array){
    @each = split(' ',$s);
    $col++;
    foreach (@each){
        $row++;
        $sht->cells($row,$col)->{Value} = "$_";
    }
}

In this script gives output, But i expect the array value of "@b" write to the column B, Row 1 to end of array. Then "@c" write to the column c, Row 1 to end of array. How can do it?

You're not initializing $row in the column loop.

What you have is:

foreach $s (@array){
    $col++;
    foreach (@$s){
        $row++;
        $sht->cells($row,$col)->{Value} = "$_";
    }
}

Add 'my $row = 0;'

foreach $s (@array){
    $col++;
    my $row = 0;
    foreach (@$s){
        $row++;
        $sht->cells($row,$col)->{Value} = "$_";
    }
}

For a little more advanced perl, you can make @array an array of arrays instead of an array of strings:

use strict;
use warnings;
use Win32::OLE;
my @a = (1..5);
my @b = (20..30);
my @c = (30..48);
my @array = (\@a,\@b,\@c);
my $xl = Win32::OLE->new('Excel.Application');
$xl->{EnableEvents} = 0;
$xl->{Visible} = 1;
my $wb = $xl->Workbooks->Add;
my $sht = $wb->Sheets(1);
$sht->{Name} = "Occurance";
my $col = 0;
foreach my $s (@array){
    $col++;
    my $row = 0;
    foreach my $item (@$s){
        $row++;
        $sht->cells($row,$col)->{Value} = $item;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM