使用perl将多个XLSX文件转换为多个CSV文件

时间:2020-06-18 19:25:21

标签: perl

我有下面的脚本,它将xlsx转换为csv,但如果单元格值之间有逗号(,),则它将移至csv中的下一列,这是错误的。 Colud,请您更正吗?另外,如何一次性将多个xlsx文件转换为多个csv文件?

#!/usr/bin/perl

use strict;
use warnings;
use Spreadsheet::XLSX;
use Text::CSV qw(csv);

my $excel = Spreadsheet::XLSX -> new ('/path/file.xlsx');
my $csv = '/path/File.csv';
open(my $FH ,'>',"$csv") or die "failed to open";

my $line;
foreach my $sheet (@{$excel -> {Worksheet}}) {
    printf("Sheet: %s\n", $sheet->{Name});
    $sheet -> {MaxRow} ||= $sheet -> {MinRow};
    foreach my $row ($sheet -> {MinRow} .. $sheet -> {MaxRow}) {
        $sheet -> {MaxCol} ||= $sheet -> {MinCol};
        foreach my $col ($sheet -> {MinCol} ..  $sheet -> {MaxCol}) {
            my $cell = $sheet -> {Cells} [$row] [$col];
            #if ($cell) {
            #    $line .= "\"".$cell -> {Val}."\",";
                        #       $line .= $cell -> {Val};
                        #       if ($col != $sheet -> {MaxCol}) #appends the comma only if the column being processed is not the last
                        #       {
                        #               $line .= ",";
                        #       }
            #}
                        if (defined $cell && defined $cell->Value) {
               if ($col != $sheet -> {MaxCol})
               {
               print $FH $cell->Value.",";
              }
            else
             {
            print $FH $cell->Value ;
             }
          } else {
            if ($col != $sheet -> {MaxCol})
               { print $FH ",";
               }
             }

        }
$FH =~ s/,$//; # replace comma at the end of the string with empt
       print $FH "\n";
      }

2 个答案:

答案 0 :(得分:3)

检查单元格值是否包含','char。如果','char存在 字符串添加双引号。编写方法并通过 $ cell-> value以检查字符串是否包含char','。

例如

sub check_cell_string {     
    my ($string) = @_;     
    my $substr = ',';     
    if (index($string, $substr) != -1) { 
        $string = '"'.$string.'"';
    }     
    return $string; 
} 

然后调用文件写语句。

my $str = check_cell_string($cell->value);
print $FH $str;

例如,在csv文件条目中,如下所示

1, 1928,44,Emil Jannings,"The Last Command, The Way of All Flesh"

答案 1 :(得分:1)

关于多个文件的问题,您应该可以执行以下操作:

my @csv = ('/path/File.csv', 'secondfile', 'thirdfile');

foreach (@csv)
{
    my $excel = Spreadsheet::XLSX -> new ($_.".xslx");
    ...
}