Perl将数据从哈希转储到电子表格

时间:2016-04-12 21:12:11

标签: excel perl spreadsheet

我有一个带键和值(数组)的哈希。我想将它们转储到电子表格

%hash
   key1 -> foo bar 
   key2-> john adam gill
   key3-> apple banana mango orange

代码:

use strict;
use warnings;
use Excel::Writer::XLSX;

my $workbook = Excel::Writer::XLSX->new( 'c:\TEMP\filename.xlsx' ); 
my $worksheet = $workbook->add_worksheet();

my $row = 1;
my $col = 1;

foreach my $k (keys %hash)
{
    $worksheet->write($row, $col)->{Value} =  $k;                # title
    $worksheet->write($row, $col++,)->{Value} =  $hash{$k};     # value
    $row++;
}

当前输出
无法调用方法" add_worksheet"在未定义的值上

期望输出

enter image description here

1 个答案:

答案 0 :(得分:2)

似乎Excel::Writer::XLSX->new失败了。在致电new后添加此代码,看看出了什么问题:

if (not defined $workbook)
{
    die "Failed to create spreadsheet: $!";
}