将CSV转换为Excel会导致文件损坏

我使用下面的perl脚本将多个csv文件转换为excel电子表格,其中基本上是链接中代码的修改版本,但是我无法打开输出excel文件,它会popup消息“The file is corrupted”。

#!/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"; } } } 

我该如何解决它?

您需要closures您的工作簿。

 $workbook->close(); 

同时升级您的Excel模块到最新版本,我也遇到了更新Spreadsheet::WriteExcel已解决的损坏的Excel文件类似的问题。

也从文档

请注意关于binmode()的要求。 Excel文件由二进制数据组成。 因此,如果你正在使用一个文件句柄,你应该确保你在将它传递给new()之前先binmode(),不pipe你是否在Windows平台上,都应该这样做。 如果你的程序有意或无意地将UTF-8数据写入一个传递给new()的文件句柄,它会破坏所创build的Excel文件。