首页 > 解决方案 > 将存储的字符串打印到单个单元格中的 xls

问题描述

我有一个存储有字符串的数组,我从文本文件中提取该数组并希望在单个单元格中的 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;
}

标签: perlxls

解决方案


如果您提供的数组中包含多个元素,则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);

推荐阅读