代码之家  ›  专栏  ›  技术社区  ›  Drsin

将xls转换为csv的Perl脚本

  •  0
  • Drsin  · 技术社区  · 11 年前

    此脚本将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;
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   Jens    11 年前

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

    更改:

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