【问题标题】:Convert CSV to Excel gives file corrupted error将 CSV 转换为 Excel 会导致文件损坏错误
【发布时间】:2014-12-24 15:26:46
【问题描述】:

我使用下面的 perl 脚本将多个 csv 文件转换为 excel 电子表格,该脚本基本上是 link 中代码的修改版本,但我无法打开输出的 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";
        }
    }
}

我该如何解决?

【问题讨论】:

    标签: excel perl export-to-excel


    【解决方案1】:

    您需要关闭工作簿。

    $workbook->close();
    

    另外将你的 Excel 模块升级到最新版本,我也遇到了类似的损坏 excel 文件的问题,在更新 Spreadsheet::WriteExcel 时得到了解决。

    同样来自docs

    注意有关 binmode() 的要求。一个Excel文件包括 二进制数据。因此,如果您使用的是文件句柄,您应该 确保在将其传递给 new() 之前对其进行 binmode()。你应该 无论您是否在 Windows 平台上,都要执行此操作。 这尤其适用于使用 UTF-8 的系统上的 perl 5.8 用户 可能正在运行如 RedHat Linux 9。如果你的程序, 有意或无意,将 UTF-8 数据写入文件句柄 传递给 new() 会损坏创建的 Excel 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多