2013-11-22 31 views
1

我希望能夠解析zip文件中的excel。我已經能夠解析壓縮文件來返回壓縮文件中的文件,如果正則表達式匹配產生了一個excel文件,我想解析文件。如何解析zip文件中的excel文件?

下面是解析爲Excel電子表格的名稱的ZIP文件中的腳本...

#!/usr/bin/perl 
use strict; 
use warnings; 
use Archive::Zip; 
use Spreadsheet::ParseExcel; 

my $zipFile = Archive::Zip->new(); 
my $xl_file = ""; 
#open zipfile 
$zipFile->read('/home/user/Desktop/test.zip') == 0 || die "cannot read zip file\n"; 

#find all files within zipfile 
my @files = $zipFile->memberNames('/home/user/Desktop/test.zip'); 
foreach my $file (sort @files) { 
    #find all excel files 
    if($file =~ m/(.*xls)/){ 
     $xl_file = $1; 
      print "excel file found.\n"; 
    } 
} 

這是一個分析在細胞中的值的腳本。

#!/usr/bin/perl 
use strict; 
use warnings; 

my $filename = "/home/user/worksheet.xls"; 
use Spreadsheet::ParseExcel; 

my $parser = Spreadsheet::ParseExcel->new(); 
my $workbook = $parser->parse("$filename"); 

if (!defined $workbook) { 
    die $parser->error(), ".\n"; 
} 
open(FILE, '>', "parse.txt")||die "cannot open parse.txt!\n"; 

for my $worksheet ($workbook->worksheets()) { 
    my ($row_min, $row_max) = $worksheet->row_range(); 
    my ($col_min, $col_max) = $worksheet->col_range();  
    my $s = $worksheet -> get_cell(2,2); 
    my $p = $worksheet-> get_cell(2,3); 
    print FILE $s->value()."\n"; 
    print FILE $p->value()."\n"; 
} 
close FILE; 

如何將這些結合在一起?

+0

一種方法是在命令行中使用管道,並僅在您提取了一個excel文件時才從第一個腳本輸出文件名。然後第二個腳本獲取該文件名並解析它。像'parseZip.pl myzip.zip | parseExcel.pl'。第一個腳本中的缺失部分是提取實際文件而不是文件名。第二個腳本需要修改以接受'STDIN'上的文件名。 – abiessu

回答

1

Archive::Zip的文件,有可能得到一個壓縮文件件的內容作爲字符串:

​​

並根據Spreadsheet::ParseExcel的文件,有可能解析字符串方含內容傳遞字符串作爲參考的Excel文件:

my $workbook = $parser->parse(\$xls_content); 

因此,您應該能夠將兩者結合在一起。

另一種可能性是將zip文件成員解壓縮到臨時文件中。

+0

謝謝。這是最好的/最簡單的工作。 – Stephen