perl - 使用 Spreadsheet::WriteExcel 读取文件并将段写入 Excel

标签 perl xls

作为我上一个问题的扩展,我需要将输入文件从第一行提取到空行,然后按顺序将输出粘贴到 xls 的单个单元格中。例如,“E: sda E: qwe E: ass”将打印在 A1 单元格中,NA 将打印在 A3 单元格中,“E: sda E: qwe E: ass”将打印在单元格 A5 中。输入文件的模式会改变,但每个段由一个空行分隔。下面的代码片段只能将整个文件内容打印到一个单元格中。
输入文件:

E: sda
E: qwe
E: sss

NA

E: sda
E: qwe
E: sss

NA

NA

E: xx
E: xxxs

NA
代码:
use strict;
use warnings;
use Spreadsheet::WriteExcel;
my $filename = 'all_in_one.txt';
my $workbook = Spreadsheet::WriteExcel->new("sad.xls");
my $wrksheet = $workbook->add_worksheet("summary");


    for (my $i = 9) {
            my $result1 = read_out_your_file_misc($filename,"\n");
            $wrksheet->write($i, 1, [$result1]);
            $i = $i + 2;
        
    }

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

最佳答案

您正在将输入文件的每一行读入数组中的一个单独元素。但是,您不想这样做。
如果您更改 input record separator变量 ( $/ ) 使用段落模式,您可以将每组行放入每隔一行的单独单元格中:

use strict;
use warnings;
use Spreadsheet::WriteExcel;

my $filename = 'all_in_one.txt';
local $/ = ""; # paragraph mode
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

my $workbook = Spreadsheet::WriteExcel->new("sad.xls");
my $wrksheet = $workbook->add_worksheet("summary");
for my $i (0 .. $#content_of_file) {
    $wrksheet->write(2*$i, 1, $content_of_file[$i]);
}

您在一个单元格中获取整个文件的原因是您 join将所有行重新组合成一个标量变量 ( $result1 ),然后将该单个值写入一个单元格。另外,for loop 有点奇怪,它只循环一次。

关于perl - 使用 Spreadsheet::WriteExcel 读取文件并将段写入 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65963980/

相关文章:

perl - 将 perl 的排序函数包装在一个对象中

c++ - 将具有多个键的 perl 映射转换为 C++

regex - Perl - 无法去除空行

Perl 继承 - 子程序覆盖

python - 在 python 中从 xls 读取 unicode

perl - 在 Perl 中打印时非常奇怪的错误

asp.net - c# 从 html 到 pdf、xls 的转换器

Excel 2007 - 条件格式 - 根据单元格区域中的值设置单元格格式

excel - 从 xls 文件中读取值但未正确读取数值

Ruby 在电子表格 gem 中跳过标题