user3360439
user3360439

Reputation: 389

Excel cannot open .xlsx file created with Spreadsheet::WriteExcel

I have been using the following script to convert a .csv file to .xlsx format, but Excel says:

Cannot open the file because the file format or file extension is not valid, verify that the file has not been corrupted and that the extension matches the format file.

Here is my code:

#!/usr/bin/perl

use strict;
use Spreadsheet::WriteExcel;
use Text::CSV_XS;
open( CSVFILE,">", "C:\\Book1.csv") or die "$!";
my $workbook  = Spreadsheet::WriteExcel->new("C:\\Book1.xlsx");
my $worksheet = $workbook->add_worksheet();

my $csv = Text::CSV_XS->new;

my $row = 0;
while (<CSVFILE>) {
    if ( $csv->parse($_) ) {
        my @Fld = $csv->fields;

        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";
    }
}

Upvotes: 2

Views: 1349

Answers (2)

harvey
harvey

Reputation: 2953

The module Spreadsheet::WriteExcel only supports the older .xls format; consider upgrading to Excel::Writer::XLSX.

See the notes on CPAN that address this explicitly; http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Migrating_to_Excel::Writer::XLSX

Upvotes: 1

itsmejodie
itsmejodie

Reputation: 4228

Use Excel::Writer::XLSX as a drop-in replacement.

This is actually the suggestion of the Spreadsheet::WriteExcel documentation which indicates that it has been superseded: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Migrating_to_Excel::Writer::XLSX

Upvotes: 3

Related Questions