1

我想将数组数组中的一系列值添加到 Excel 电子表格中的一系列单元格中;我写了以下内容,但失败了:

use Win32::OLE;
use Cwd;

eval {$excel = Win32::OLE->GetActiveObject('Excel.Application')};
die "Excel not installed" if $@;
unless (defined $excel) 
{
    $excel = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
    or die "Oops, cannot start Excel";
}

$workbook = $excel->Workbooks->Open(getcwd() . "/test.xlsx");
$worksheet = $workbook->Worksheets(1);
@matrix = ( [0, 1], [2, 3] );

$worksheet->Range("B5:C6")->{Value} = @matrix;

$worksheet->Save;

上面的代码用 (2, 2, 2, 2) 而不是 (0, 1, 2, 3) 更新单元格 B5:C6,我无法弄清楚原因......我做错了什么?

4

2 回答 2

4

文档示例传递了一个数组引用

$sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ],
                                   [ 42,    'Perl',  3.1415  ]];

更改您的代码以执行相同的操作:

$worksheet->Range("B5:C6")->{Value} = \@matrix;

数字 2 可能来自@matrix.

于 2013-11-05T13:29:33.330 回答
0

查看我从将一系列单元格设置为一组值与将每个单元格设置为一个值(一次 1 个单元格)相比所获得的速度改进:

处理时间:

start 29:29 to stop 31:41    = 2 min, 12 sec    (The SLOW WAY)  
start 19:55 to stop 20:33    = 0 min, 38 sec    (The SPEEDY WAY) 

那是 132 秒对 38 秒

代码:

use Win32::OLE; 
$EXCEL = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit; print "MS-Excel is shutting 
down.\n"; sleep 2;}); 
$EXCEL->{SheetsInNewWorkbook} = 1; 
$BOOK       = $EXCEL->Workbooks->Add(); 
$SHEET      = $BOOK->Worksheets(1);

$SHEET->Range( "A1" )->{Value} = "Book"; 
$SHEET->Range( "B1" )->{Value} = "Chapter";
$SHEET->Range( "C1" )->{Value} = "Verse";
$SHEET->Range( "D1" )->{Value} = "Text"; 

$start=1; $stop=66; 
$row=1;   $cnt=0;

@worksheet_array=();

#-- Process the MS-Access database (ODBC connection), SQL Query Result Set, 
#-- which selected all Bible verses from Books 1-66 (i.e. Genesis thru Revelation).

while ($db->FetchRow()) {  
   $row++;   $cnt++;  
    if (($cnt % 1000) == 0) { 
       print "Processed ($cnt Verses from the Bible Database: Books ($start-$stop) of 66\n";
    } 

   $worksheet_array[$row-2][0] = $book        = $db->Data("book");   
   $worksheet_array[$row-2][1] = $chapter     = $db->Data("chapter");
   $worksheet_array[$row-2][2] = $verse       = $db->Data("verse"); 
   $worksheet_array[$row-2][3] = $verse_text  = $db->Data("verse_text"); 

   print OUT "$book|$chapter|$verse|$verse_text\n";  #-- This output goes to a text (*.txt) file

   #-- The Too Slow Way!  Write data 1 cell at a time.
   #  $SHEET->Range( "A$row" )->{Value} = $book; 
   #  $SHEET->Range( "B$row" )->{Value} = $chapter; 
   #  $SHEET->Range( "C$row" )->{Value} = $verse;
   #  $SHEET->Range( "D$row" )->{Value} = $verse_text; 
}

而是一次写入所有数据......快速方式!

$SHEET->Range( "A2:D$row" )->{Value} = \@worksheet_array;   #-- $row = 31102 (total nbr verses)
$SHEET->Columns("A")->AutoFilter; 
$SHEET->Columns( "A:D" )->AutoFit(); 
$EXCEL->Windows(1)->{SplitRow}    = 1;
$EXCEL->Windows(1)->{FreezePanes} = 1;
$BOOK->SaveAs($excel97outputfile_dot_xls);
$BOOK->Close();       sleep 1;   
$EXCEL->Quit;         sleep 1;
undef $BOOK;  undef $EXCEL;
于 2014-12-19T16:24:18.077 回答