Excel无法打开使用Spreadsheet :: WriteExcel创建的.xlsx文件

时间:2014-10-13 23:28:47

标签: perl

我一直在使用以下脚本将.csv文件转换为.xlsx格式,但Excel说:

  

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.

这是我的代码:

#!/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";
    }
}

2 个答案:

答案 0 :(得分:3)

使用Excel::Writer::XLSX作为替补。

这实际上是Spreadsheet::WriteExcel文档的建议,表明它已被取代:http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Migrating_to_Excel::Writer::XLSX

答案 1 :(得分:1)

模块Spreadsheet :: WriteExcel仅支持较旧的.xls格式;考虑升级到Excel :: Writer :: XLSX。

请参阅有关CPAN的说明,明确解决此问题; http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Migrating_to_Excel::Writer::XLSX