将 xls 转换为 csv 的 Perl 脚本

Perl script to convert xls to csv

此脚本可以将 xls 转换为 csv。 挑战在于它不会将 xls 中的空白单元格转换为 csv 文件中的空白。 感谢您的帮助:UPDATED SCRIPT

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

my $sourcename = shift @ARGV or die "invocation: [=10=] <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 && $source_cell->Value) {
   #print "( $row_index , $col_index ) =>", $source_cell->Value, "\t;";
   print  $source_cell->Value, ";";
   }
 else
  {
  print ";"
   }
  }
 }
}

样本excel

EFG KDD ABS JME
FGO     POP JET

转换为:

EFG;KDD;ABS;JME;
FGO;POP;JET;

但应该是:

EFG;KDD;ABS;JME;
FGO;;POP;JET;

您必须检查单元格的值是否已初始化,而不是单元格本身。

变化:

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

收件人:

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

应该可以。

更新:

 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 && $source_cell->Value) {
      print  $source_cell->Value.";";
   } else {
      print ";";
   }
  }
  print "\n";
 }
}