首页 > 解决方案 > 使用 perl 将多个 XLSX 文件转换为多个 CSV 文件

问题描述

我有下面的脚本,它将 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";
      }

标签: perl

解决方案


检查单元格值是否包含“,”字符。如果 ',' 字符存在于 sting 中,则为字符串添加双引号。编写一个方法并通过 $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"

推荐阅读