【问题标题】:Perl script to convert xls to csv将 xls 转换为 csv 的 Perl 脚本
【发布时间】:2015-02-03 20:35:48
【问题描述】:

此脚本将 xls 转换为 csv ok。 挑战在于它不会将 xls 中的空白单元格转换为 csv 文件中的空白。 任何帮助表示赞赏:更新脚本

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

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 && $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;

【问题讨论】:

    标签: perl csv xls


    【解决方案1】:

    你必须检查单元格的值是否被初始化,而不是它自己的单元格。

    变化:

       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";
     }
    }
    

    【讨论】:

    • 但出现以下错误:Can't call method "Value" on an undefined value at line 23
    • 如果$source_cell 是未定义的,那么Value 会出错。您可能会发现:if ( defined $source_cell and defined $source_cell -&gt; Value ) { 做得更好。
    • @Jens。谢谢。我刚刚用你的新答案更新了脚本,但结果仍然忽略了 csv 文件中的空白。
    • @Jens。这似乎有效。包括空白。但它不会在 csv 中逐行打印结果(xls 中的行)。
    • @Jens。我正在使用 AIX。如果我使用print "\n";,它会在存在空白列的位置断开每一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    相关资源
    最近更新 更多