在单个单元格中将存储的字符串打印到 xls 中

Print stored string into xls in a single cell

我有一个数组,其中存储了我从文本文件中提取的字符串,并希望在单个单元格中打印在 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 函数更改为 return 数组 标量。

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);