有沒有辦法將多個文本檔案中的值自動化到同一個 Excel 檔案中的多個作業表?(例如:Textfile1 值到 Sheet1,Textfile2 值到 Sheet2 等等)因為現在我每次從不同的文本檔案中提取值時都必須更改文本檔案和 Excel 作業表的名稱,以便我需要一個自動化來簡化作業。下面是我最近使用的 Perl 腳本。
use strict;
use warnings;
use Excel::Writer::XLSX;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
{
my $output_fn = 'result.xlsx';
my $input_fn = 'accuracy_final_copy.txt.gz';
my $workbook = Excel::Writer::XLSX->new( $output_fn );
my $worksheet = $workbook->add_worksheet();
my $zip = IO::Uncompress::Gunzip->new( $input_fn )
or die "gunzip failed: $GunzipError\n";
$worksheet->write( 0, 0, "Accuracy value" );
my $col = 0;
my $row = 1;
while (!$zip->eof()) {
my $line = $zip->getline();
chomp($line);
next if $line !~ /\S/; # skip empty lines
my $value = $line;
$worksheet->write( $row, $col, $value );
$row ;
}
$workbook->close();
}
uj5u.com熱心網友回復:
你所擁有的大部分都很好,只需添加一個合適的回圈
use warnings;
use strict;
use feature 'say';
use Excel::Writer::XLSX;
my @files = @ARGV ? @ARGV : die "Usage: $0 filenames\n";
my $workbook = Excel::Writer::XLSX->new( 'perl.xlsx' );
for my $file (@files) {
say "Processing $file";
my $worksheet = $workbook->add_worksheet();
my ($fname) = $file =~ m{(?:.*/)?(.*)}; # extract basename
$worksheet->write( 0, 0, $fname );
open my $fh, '<', $file or do {
warn "Can't open $file: $!";
next
};
my ($col, $row) = (0, 1);
while (<$fh>) {
chomp;
my $value = $_;
$worksheet->write( $row, $col, $value );
$row;
}
}
$workbook->close;
這會在第一列中為每個檔案寫入一個新作業表,每行一行。
uj5u.com熱心網友回復:
這是一個示例,它將當前目錄中以.gzas Sheet1、Sheet2、 ... 等結尾的所有檔案添加到result.xlsx檔案中:
use feature qw(say);
use strict;
use warnings;
use Excel::Writer::XLSX;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
{
my $output_fn = 'result.xlsx';
my @input_files = <*.gz>;
my $workbook = Excel::Writer::XLSX->new( $output_fn );
for my $input_fn (@input_files) {
say "Adding file $input_fn ..";
add_sheet($input_fn, $workbook);
}
$workbook->close();
}
sub add_sheet {
my ($input_fn, $workbook) = @_;
my $worksheet = $workbook->add_worksheet();
my $zip = IO::Uncompress::Gunzip->new( $input_fn )
or die "gunzip failed: $GunzipError\n";
$worksheet->write( 0, 0, "Accuracy value" );
my $col = 0;
my $row = 1;
while (!$zip->eof()) {
my $line = $zip->getline();
chomp($line);
next if $line !~ /\S/; # skip empty lines
my $value = $line;
$worksheet->write( $row, $col, $value );
$row ;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/316796.html
