Perl:将Text :: Table写入xlsx的简单方法?

时间:2014-08-15 19:13:57

标签: excel perl

我想知道Perl是否可以轻松地将Text::Table对象写入xlsx?例如。也许使用Excel::Writer?我希望有一些方法可以很容易地做到这一点,就像以某种方式将表转换或转换为哈希或数组或Excel::Writer已经识别的其他结构。

尝试直接将表格写入Excel工作表不起作用:

#!/usr/bin/perl
use strict;
use warnings;
use Text::Table;
use Excel::Writer::XLSX;


# From Perl Monks Table tutorial:
my $tb = Text::Table->new(
    "Planet", "Radius\nkm", "Density\ng/cm^3"
);
$tb->load(
    [ "Mercury", 2360, 3.7 ],
    [ "Venus", 6110, 5.1 ],
    [ "Earth", 6378, 5.52 ],
    [ "Jupiter", 71030, 1.3 ],
);
print $tb;

# From CPAN Excel::Writer tutorial
my $workbook  = Excel::Writer::XLSX->new( 'a_simple.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
$worksheet1->write( 0, 0, "Hi Excel!" ); #Works 

# Now I want to write a table to a worksheet:
my $worksheet2 = $workbook->add_worksheet();
$worksheet1->write( 0, 0, $tb ); # Does not work

我知道我可以遍历表并将每个条目写入Excel,或者我也可以编写相同的数据用于将表直接填充到Excel中,因为我正在创建表,但是因为我有已经生成一个大表的大块代码我希望我可以将结果转储到Excel中。

1 个答案:

答案 0 :(得分:0)

看起来Text::Table不允许提取插入的数据,因此您需要欺骗内部。 (您可以向Text::Table的作者建议将存储数据的访问权限添加为新功能)

您可以尝试类似

的内容
for my $col (0 .. $tb->n_cols() - 1)) {
    for my $row (0 .. $tb->height() - 1) {
        #looks like no support in module to extract data, so need to 
        #attack the internals (not good, but may cover the need....)
        my $cell_data = $tb->_cols[$col][$row];
        $worksheet->write( $row, $col, $cell_data);
    }
}

如果你能掌握原始数组(即你用过的那个 - >加载(...)

,那就更好了

然后

my @table = (
    [ "Mercury", 2360, 3.7 ],
    [ "Venus", 6110, 5.1 ],
    [ "Earth", 6378, 5.52 ],
    [ "Jupiter", 71030, 1.3 ],
);
$tb->load(@table);

for my $row (0 .. @table - 1) {
    for my $col (0  .. @{$table[$row]} - 1) {
        my $cell_data = $table[$row][$col];
        $worksheet->write( $row, $col, $cell_data);
    }
}