【问题标题】:Perl - Dropping delimited text files into one Excel file with tabsPerl - 将分隔的文本文件放入一个带有标签的 Excel 文件中
【发布时间】:2014-04-23 14:44:16
【问题描述】:

休息一段时间后回到 Perl,我一直在寻找一种方法,将一些制表符分隔的文本文件放入数组,然后放入 Excel 文件;基本上是为目录中的每个文本文件生成的 Excel 选项卡。通常,文本文件是类似的格式。

下面的代码是从示例中拼凑而成的,通常会产生我所追求的。但是,输出会忽略任何选项卡并在一个字符串中打印所有文本(每行)。我正在努力解决如何在代码中实现制表符分隔符。我知道我需要在将文本文件推入数组时对其进行拆分。我一直在玩散列,但我认为我对这个问题的研究太远了,这很可能是我缺少的一个明显的答案。

use warnings;
use strict;
use Cwd qw(abs_path);
use Spreadsheet::WriteExcel;

die "Log path ARG required " unless defined $ARGV[0];

my $path = abs_path( $ARGV[0] );

my $workbook = Spreadsheet::WriteExcel->new("resultsbook.xls");

chdir $path or die "no such directory: $!";
if ( -d $path ) {    ## test if $path given is a directory
    opendir my $dir, $path or die "can't open the directory: $!";
    while ( defined( my $file = readdir($dir) ) ) {
        chomp $file;
        next if $file eq '.' or $file eq '..';

        (my $sheetname = $file) =~s/\.\w+?//; 
        my $wrksheet = $workbook->add_worksheet($sheetname);
        $wrksheet->write_col( 0, 0, [ @{ readfile($file) } ] );
    }
}

sub readfile {
    my $textfilecontent = [];
    open my $fh, '<', shift() or die "can't open file:$!";
    while (<$fh>) {
        chomp;
        push @{$textfilecontent}, $_, $/;
    }
    return $textfilecontent;
}

【问题讨论】:

    标签: excel perl


    【解决方案1】:

    在将行推入@textfilecontent 变量之前,您需要使用制表符(或任何分隔符)拆分行。这里还有一些其他小的更正:

    use warnings;
    use strict;
    use Cwd qw(abs_path);
    use Spreadsheet::WriteExcel;
    
    die "Log path ARG required " unless defined $ARGV[0];
    
    my $path = abs_path( $ARGV[0] );
    
    my $workbook = Spreadsheet::WriteExcel->new("resultsbook.xls");
    
    chdir $path or die "no such directory: $!";
    if ( -d $path ) {    ## test if $path given is a directory
        opendir my $dir, $path or die "can't open the directory: $!";
        while ( defined( my $file = readdir($dir) ) ) {
            chomp $file;
            next if $file eq '.' or $file eq '..';
    
            (my $sheetname = $file) =~s/\.\w+//; 
            my $wrksheet = $workbook->add_worksheet($sheetname);
            $wrksheet->write_col( 0, 0, readfile($file));
        }
    }
    
    sub readfile {
        my @textfilecontent = ();
        open my $fh, '<', shift() or die "can't open file:$!";
        while (<$fh>) {
          chomp;
          push @textfilecontent, [split(/\t/)];
        }
        return \@textfilecontent;
    }
    

    【讨论】:

    • 非常感谢 Imran,这正是我想要的!顶级人物。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多