james.f.williamson has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I'm trying to insert a 4x4 array into an excel document. I've got as far as opening it, creating two sheets (for later) and inserting single cells. However... when I try to insert an array to a range it doesn't work. Would some kind soul be able to tell me where I'm going wrong?

My other question is, if I wanted to loop through this array from @array[0][0] to @array44 is there a way to reference the Excel cells by X and Y numerically rather than X alphabetically and Y numerically?

Would be much appreciated.
#!/usr/bin/perl -w use strict; use Win32::OLE qw(in with); use Win32::OLE::Const 'Microsoft Excel'; $Win32::OLE::Warn = 3; # die on errors... # get already active Excel application or open new my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit'); my $excel_file = 'C:/work/james_test.xls'; # -e checks to see if the file exists if (-e "$excel_file") { # open Excel file my $Book = $Excel->Workbooks->Open("$excel_file"); } else{ $Excel->{Visible} = 0; $Excel->{DisplayAlerts}=0; #0 is hide alerts $Excel->{SheetsInNewWorkBook} = 1; my $Workbook = $Excel->Workbooks->Add(); my $sheet1 = $Workbook->Worksheets(1); $sheet1->{Name} = "WorkSheet1"; my $sheet2 = $Workbook->Worksheets->Add(); $sheet2->{Name} = "WorkSheet 2"; my @average_values_table = ( [ "1", "2", "3", "4" ], [ "5", "8", "7", "8"], [ "1", "2", "3", "4" ], [ "5", "8", "7", "8"], ); $sheet1 -> Range("A1:D4") -> {Value} = @average_values_table; $Workbook->SaveAs($excel_file); $Workbook->Close(); $Excel->Quit(); }

Replies are listed 'Best First'.
Re: inserting a perl array into an Excel doc with OLE
by Andrew Coolman (Hermit) on Oct 10, 2008 at 17:37 UTC
    Change this to anonymous array and it will work fine:
    $sheet1 -> Range("A1:D4") -> {Value} = [@average_values_table];

    Regards,
    s++ą  ł˝ ął. Ş ş şą Żľ ľą˛ş ą ŻĽąş.}++y~-~?-{~/s**$_*ee
      ahhhhh. brilliant! thanks. Would you care to explain why an anonymous array is used please?
        I used the above as well, and it worked great.

      I think the right code is:

      $sheet1 -> Range("A1:D4") -> {Value} = \@average_values_table;

      (In other words, referring to the array's address).

      If you use an anonymous array, you're needlessly creating a new array.