空白单元格不在xls中使用perl转换为csv

时间:2014-02-07 10:08:37

标签: excel perl csv

我有下面的脚本,将xls转换为csv ok,但它不会将我的xls中的空白单元转换为csv文件中的空白:

#!/usr/bin/perl
use strict;
use Spreadsheet::ParseExcel;

my $sourcename = shift @ARGV or die "invocation: $0 <source file>\n";
my $source_excel = new Spreadsheet::ParseExcel;
my $source_book = $source_excel->Parse($sourcename) 
    or die "Could not open source Excel file $sourcename: $!";
my $storage_book;

foreach my $source_sheet_number (0 .. $source_book->{SheetCount}-1) {
 my $source_sheet = $source_book->{Worksheet}[$source_sheet_number];

 print "--------- SHEET:", $source_sheet->{Name}, "\n";
 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 "( $row_index , $col_index ) =>", $source_cell->Value, "\t;";
   print  $source_cell->Value, ";";
   }
  }
  print "\n";
 }
}

示例excel

ABC BCC DCC DES
SDE     KOT FET

它转换为

ABC;BCC;DCC;DES;
SDE;KOT;FET;

而不是

ABC;BCC;DCC;DES;
SDE;;KOT;FET;

1 个答案:

答案 0 :(得分:3)

如果您要创建CSV,请使用Text :: CSV,这将为您节省很多麻烦。

'如果$ source'代码不匹配空单元格。

修复您的代码:

   if (defined $source_cell) {
     #print "( $row_index , $col_index ) =>", $source_cell->Value, "\t;";
     print  $source_cell->Value, ";";
   } else {
     print ';';
   }