简体   繁体   中英

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."

#!/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 .

Also from docs

Note about the requirement for binmode(). An Excel file is comprised of binary data. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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