无法使用Spreadsheet :: Read解析xlsx

时间:2015-08-17 06:55:32

标签: perl file spreadsheet cpan

我正在尝试使用 Spreadsheet::Read 解析 .xlsx 文件,相同的代码适用于 .xls 文件,但会引发错误下面是 .xlsx 程序:

  1. 我们正在 .cgi 文件中创建名称为“csv_path”的文件上传(浏览)按钮。
  2. 当用户提交表单时(当然是 multipart / form-data
  3. 下一页的代码

    use CGI;
    use Spreadsheet::Read;
    use Spreadsheet::ParseExcel;
    use Data::Dumper qw(Dumper);
    
    #will catch uploaded file.
    my $fname = $query->param("csv_path");
    
    print Dumper($fname); 
    #just for confirmation we printed variable $fname
    #when .xls is uploaded $fname contains:
    #$VAR1 = bless( \*{'Fh::fh00001308_4_template.xls'}, 'Fh' );
    #when .xlsx is uploaded $fname contains:
    #$VAR1 = bless( \*{'Fh::fh00001308_4_template.xlsx'}, 'Fh' );
    
    #now read the file with "Spreadsheet::Read"
    my $data_xls  = ReadData ( $fname, "strip"=>3, "dtfmt" => "mm/dd/yyyy");#here if we pass .xlsx file name(stored on server) to ReadData() it works properly.
    
    
    #print out of Spreadsheet::Read
    print "<pre>";
    print Dumper($data_xls);
    
    #when .xls is uploaded $data_xls comes up with all required data
    
    #when .xlsx is uploaded below error occurs
    #   XLSX parser cannot parse data: Undefined subroutine Fh::opened
    
  4. 如果需要进行任何更改或遗漏任何内容,请提供建议。

1 个答案:

答案 0 :(得分:1)

这里不是直接传递流数据,而是假设将文件存储在临时位置,然后将带有位置的文件名传递给ReadData()函数。
请参考下面的代码:
< / p>

use CGI;
use Spreadsheet::Read;
use Spreadsheet::ParseExcel;
use Data::Dumper qw(Dumper);

my $corrected_filename = $query->param('csv_path');
$corrected_filename =~ s/ /_/g;
# $corrected_filename .= "$username";
#store file locally
local $| = 1;
my ($bytesread,$buffer,$file);
my $fh = $query->upload('csv_path');
open(OUTF, '>' . "/tmp/upload-".$corrected_filename);
while ($bytesread = read($fh, $buffer, 1024)) {
    print(OUTF $buffer);
}
close(OUTF);
my $data_xls  = ReadData ("/tmp/upload-".$corrected_filename, "strip"=>3, "dtfmt" => "mm/dd/yyyy");#here if we pass .xlsx file name(stored on server) to ReadData() it works properly.


#print out of Spreadsheet::Read
print "<pre>";
print Dumper($data_xls);

当代码读完时,我们可以取消链接文件。