perl - 使用 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";
}
解决方案
检查单元格值是否包含“,”字符。如果 ',' 字符存在于 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"
推荐阅读
- react-native-firebase - 不存在捆绑 URL
- recursion - 尝试取 n 个数字的乘积的 n 次方根很困难
- c# - 从 AbpZeroModule 覆盖 NotificationStore
- apache-kafka - bin/kafka-topics.sh --zookeeper localhost:2181 --describe: 50 主题:__consumer_offsets 列出。这些是默认的吗?
- mysql - MySQL 立即返回新插入的行以供 GraphQL 使用的正确方法?
- android - Buildozer 错误:无法使用 GradleUserHomeScopeServices.createCachingFileHasher() 创建 FileHasher 类型的服务
- python-2.7 - Matplotlib:如何仅更改边缘的 alpha
- c# - languageext 或 asyn 与聚合绑定与验证
- flutter - 如何在 Flutter 中基于 Firebase AuthState 向作为路由器工作的 StreamBuilder 添加动画?
- laravel - 使用 laravel 向存储在数据库中的所有号码发送 nexmo 短信