gpt4 book ai didi

excel - 在保持编码的同时使用 Perl 将 XLSX 转换为 CSV

转载 作者:行者123 更新时间:2023-12-01 05:49:08 34 4
gpt4 key购买 nike

我是一名 BI 开发人员,使用 perl 脚本作为我的 ETL - 我通过电子邮件接收数据,获取文件,解析它并将其推送到数据库中。大多数文件是 CSV 文件,但偶尔我有一个 XLSX 文件。

我一直在使用 Spreadsheet::XLSX 进行转换,但我注意到 CSV 输出的编码错误(需要是 UTF8,因为口音和外语)。

这就是我正在使用的子程序($input_file 是一个 Excel 文件),但我一直在获取包含错误字符的数据。

我错过了什么?

非常感谢大家!

sub convert_to_csv {
my $input_file = $_[0];
my ( $filename, $extension ) = split( '\.', $input_file );
open( format_file, ">:**encoding(utf-8)**", "$filename.csv" ) or die "could not open out file $!\n";
my $excel = Spreadsheet::XLSX->new($input_file);
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) {
my $trimcell;
$trimcell = $cell->value();
print STDERR "cell: $trimcell\n"; ## Just for the tests so I don't have to open the file to see if it's ok
$trimcell =~ s/^\s+|\s+$//g; ## Just to make sure I don't have extra spaces
$line .= "\"" . $trimcell . "\",";
}
}
chomp($line);
if ($line =~ /Grand Total/){} ##customized for the files
else {
print format_file "$line\n";
$line = '';
}
}
}
close format_file;
}

最佳答案

我的知识来自于使用 ETL::Pipeline,它使用 Spreadsheet::XLSX 来读取 .xlsx 文件。但是我知道哪些字段是UTF-8

我编写了一个本地 ETL::Pipeline 模块来处理 Excel 文件的输出

use Encode qw(decode encode);

$ra_rec->{name} = decode( 'UTF-8', $ra_rec->{name}, Encode::FB_CROAK );

关于excel - 在保持编码的同时使用 Perl 将 XLSX 转换为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60377128/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com