我想用Perl將excel文件轉換爲csv文件。爲了方便,我喜歡使用模塊File :: Slurp進行讀/寫操作。我需要它在一個子功能。Perl - 從Excel寫入CSV時的空行
雖然打印出到屏幕上,該程序生成期望的輸出,生成CSV-文件不幸只是包含一排以分號,字段是空的。
下面是代碼:
#!/usr/bin/perl
use File::Copy;
use v5.14;
use Cwd;
use File::Slurp;
use Spreadsheet::ParseExcel;
sub xls2csv {
my $currentPath = getcwd();
my @files = <$currentPath/stage0/*.xls>;
for my $sourcename (@files) {
print "Now working on $sourcename\n";
my $outFile = $sourcename;
$outFile =~ s/xls/csv/g;
print "Output CSV-File: ".$outFile."\n";
my $source_excel = new Spreadsheet::ParseExcel;
my $source_book = $source_excel->Parse($sourcename)
or die "Could not open source Excel file $sourcename: $!";
foreach my $source_sheet_number (0 .. $source_book->{SheetCount} - 1)
{
my $source_sheet = $source_book->{Worksheet}[$source_sheet_number];
next unless defined $source_sheet->{MaxRow};
next unless $source_sheet->{MinRow} <= $source_sheet->{MaxRow};
next unless defined $source_sheet->{MaxCol};
next unless $source_sheet->{MinCol} <= $source_sheet->{MaxCol};
foreach my $row_index (
$source_sheet->{MinRow} .. $source_sheet->{MaxRow})
{
foreach my $col_index (
$source_sheet->{MinCol} .. $source_sheet->{MaxCol})
{
my $source_cell =
$source_sheet->{Cells}[$row_index][$col_index];
if ($source_cell) {
print $source_cell->Value, ";"; # correct output!
write_file($outFile, { binmode => ':utf8' }, $source_cell->Value, ";"); # only one row of semicolons with empty fields!
}
}
print "\n";
}
}
}
}
xls2csv();
我知道它是與傳入WRITE_FILE功能參數,但不能設法解決它。
有沒有人有想法?
非常感謝您提前。除非append => 1
給出選項
加上'use strict;使用警告;'並報告你得到的錯誤/警告。我認爲'使用v5.14'激活嚴格,但不警告..但使用它們都是確定的。 – TLP
您應該知道,您可能會冒險用'$ outFile =〜s/xls/csv/g'這行來覆蓋原始文件。在Windows中,'<*.xls>'會匹配類似'foo.XLS'的東西,但是你的正則表達式區分大小寫,並且不會執行替換,所以你的輸入和輸出文件名是相同的。使用'/ i'來忽略大小寫。 – TLP
感謝提示區分大小寫。我加了使用嚴格;使用警告; 我得到的唯一警告是「寬字符打印在etl.pl行45.」。但那是因爲我的文件中有「ö」等字符。 – royskatt