【发布时间】:2014-12-24 15:26:46
【问题描述】:
我使用下面的 perl 脚本将多个 csv 文件转换为 excel 电子表格,该脚本基本上是 link 中代码的修改版本,但我无法打开输出的 excel 文件,它会弹出消息“文件已损坏。”
#!/usr/intel/bin/perl -W
use strict;
use Spreadsheet::WriteExcel::Big;
use Text::CSV_XS;
# Check for valid number of arguments
if (($#ARGV < 1) || ($#ARGV > 2)) {
die("Usage: csv2xls csvfile_dir xlsfile\n");
};
my $csvdir = $ARGV[0];
my $outfile = $ARGV[1];
# Create a new Excel workbook
my $workbook = Spreadsheet::WriteExcel::Big->new($outfile);
my $csvfile = "";
my $tab_title = "";
foreach $csvfile (glob("$csvdir/*.csv")) {
print "$csvfile\n";
# Open the Comma Separated Variable file
open (CSVFILE, $csvfile) or die "$csvfile: $!";
$csvfile =~ s/.*\///;
$tab_title = (split(/\./,$csvfile))[0];
print "-D- $tab_title\n";
# Create a new Excel worksheet
my $worksheet = $workbook->add_worksheet($tab_title);
# Create a new CSV parsing object
my $csv = Text::CSV_XS->new;
# Row and column are zero indexed
my $row = 0;
while (<CSVFILE>) {
if ($csv->parse($_)) {
my @Fld = $csv->fields;
print "-D- @Fld\n";
my $col = 0;
foreach my $token (@Fld) {
$worksheet->write($row, $col, $token);
$col++;
}
$row++;
} else {
my $err = $csv->error_input;
print "Text::CSV_XS parse() failed on argument: ", $err, "\n";
}
}
}
我该如何解决?
【问题讨论】:
标签: excel perl export-to-excel