简体   繁体   English

将CSV转换为Excel会导致文件损坏错误

[英]Convert CSV to Excel gives file corrupted error

I converted multiple csv files into a excel spreadsheet using the perl script below which is basically a modified version of the code in the link , but i cannot open the output excel file, it gives a pop up message "The file is corrupted." 我使用下面的perl脚本将多个csv文件转换为excel电子表格,该脚本基本上是链接中代码的修改版本,但是我无法打开输出excel文件,它会弹出消息“文件已损坏”。

#!/usr/intel/bin/perl -W

use strict;
use Spreadsheet::WriteExcel::Big;
use Text::CSV_XS;

# Check for valid number of arguments
if (($#ARGV < 1) || ($#ARGV > 2)) {
   die("Usage: csv2xls csvfile_dir xlsfile\n");
};

my $csvdir  = $ARGV[0];
my $outfile = $ARGV[1];


# Create a new Excel workbook
my $workbook  = Spreadsheet::WriteExcel::Big->new($outfile);
my $csvfile   = "";
my $tab_title = "";

foreach $csvfile (glob("$csvdir/*.csv")) {
    print "$csvfile\n";
    # Open the Comma Separated Variable file
    open (CSVFILE, $csvfile) or die "$csvfile: $!";
    $csvfile =~ s/.*\///;
    $tab_title = (split(/\./,$csvfile))[0];
    print "-D- $tab_title\n";

    # Create a new Excel worksheet
    my $worksheet = $workbook->add_worksheet($tab_title);

    # Create a new CSV parsing object
    my $csv = Text::CSV_XS->new;

    # Row and column are zero indexed
    my $row = 0;

    while (<CSVFILE>) {
        if ($csv->parse($_)) {
            my @Fld = $csv->fields;
            print "-D- @Fld\n";
            my $col = 0;
            foreach my $token (@Fld) {
                $worksheet->write($row, $col, $token);
                $col++;
            }
            $row++;
        } else {
            my $err = $csv->error_input;
            print "Text::CSV_XS parse() failed on argument: ", $err, "\n";
        }
    }
}

How can i fix it? 我该如何解决?

You need to close your workbook. 您需要关闭工作簿。

$workbook->close();

Also upgrade your Excel module to the latest version, I also faced the similar issue of corrupted excel files which was solved on updating Spreadsheet::WriteExcel . 还要将您的Excel模块升级到最新版本,我还遇到了类似的Excel文件损坏问题,该问题已通过更新Spreadsheet::WriteExcel解决。

Also from docs 也是从文档

Note about the requirement for binmode(). 注意有关binmode()的要求。 An Excel file is comprised of binary data. Excel文件由二进制数据组成。 Therefore, if you are using a filehandle you should ensure that you binmode() it prior to passing it to new().You should do this regardless of whether you are on a Windows platform or not. 因此,如果您使用的是文件句柄,则应确保在将其传递给new()之前先对其进行binmode()处理,无论您是否在Windows平台上都应这样做。 This applies especially to users of perl 5.8 on systems where UTF-8 is likely to be in operation such as RedHat Linux 9. If your program, either intentionally or not, writes UTF-8 data to a filehandle that is passed to new() it will corrupt the Excel file that is created. 这尤其适用于可能运行UTF-8的系统(例如RedHat Linux 9)上的perl 5.8的用户。如果您的程序有意或无意地将UTF-8数据写入传递给new()的文件句柄中它将损坏创建的Excel文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM