我有一个数组,其中包含从文本文件中提取的字符串,并希望在单个单元格中以xls打印。下面的命令能够在同一列中打印,但分隔行。寻找在单个单元格中打印的方法。
#!/usr/bin/perl
use strict;
use warnings;
use Spreadsheet::WriteExcel;
my $workbook = Spreadsheet::WriteExcel->new("result.xls");
my $wrksheet = $workbook->add_worksheet("summary");
$wrksheet->write_col(1,0,[@{read_out_your_file_misc("temp_stage.txt")}]);
$workbook->close() or die "Error closing file: $!";
sub read_out_your_file_misc {
my $content_of_file = [];
open my $fhh, '<', shift() or die "can't open file:$!";
while (<$fhh>) {
chomp;
#push @{$content_of_file}, $_, $/;
push @{$content_of_file}, $_;
}
return $content_of_file;
}
如果您提供一个包含多个元素的数组,则0
(A
)列中的多个行将由write_col
填充。您可以join
数组中的元素来解决这个问题。如果这是您经常使用的模式,您甚至可以更改read_out_your_file_misc
函数,根据您的需要返回数组或标量。
sub read_out_your_file_misc {
my $filename = shift or die "ERROR: read_out_your_file_misc needs a filename";
my $delim = shift || ','; # make the default delimiter a comma
open my $fhh, '<', $filename or die "ERROR: $filename: $!";
my @content_of_file = <$fhh>; # read the whole file at once
close $fhh;
chomp @content_of_file; # chomp the complete array
if(wantarray) { # return an array if that's wanted
@content_of_file;
} else { # else return it as a scalar with $delim between elements
join($delim, @content_of_file);
}
}
现在,根据接收变量的类型,函数的行为不同。
以标量形式获取文件内容并仅填充A2:
my $result = read_out_your_file_misc('temp_stage.txt');
$wrksheet->write_col(1, 0, [$result]);
以数组形式获取文件内容,并从A4开始向下填充:
my @result = read_out_your_file_misc('temp_stage.txt');
$wrksheet->write_col(3, 0, @result);