我想用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