6

需要一些好人帮助我阅读扩展名为“xlsx”的excel文件我的脚本适用于“xls”但不是“xlsx”,这是我得到错误的代码:Can't call method "worksheet" on an undefined value如果文件是“xlsx”,这是我做有:

#!/usr/bin/perl -w

use warnings;
use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::XLSX;
use Date::Format;

my $filename = "../test.xlsx";
#Parse excel file
my $parser = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse("$filename");

#Get cell value from excel sheet1 row 1 column 2
my $worksheet = $workbook->worksheet('Sheet1');
my $cell = $worksheet->get_cell(0,1);

# Print the cell value when not blank
if ( defined $cell and $cell->value() ne "") {
    my $value = $cell->value();
    print "cell value is $value \n";
}
4

3 回答 3

12

Spreadsheet::XLSX 与 .xlsx 文件的 Spreadsheet::ParseExcel 非常相似;你需要说:

my $parser = Spreadsheet::XLSX->new();

而不是使用 ParseExcel。

于 2013-11-05T05:55:58.303 回答
3

您还可以使用 CPAN 模块Spreadsheet::ParseXLSX来解析xlsx文件。

来自文档:

use Spreadsheet::ParseXLSX;

my $parser = Spreadsheet::ParseXLSX->new;
my $workbook = $parser->parse("file.xlsx");

有关更多文档,请参阅Spreadsheet::ParseExcel

于 2015-04-15T11:59:47.653 回答
2

假设您已经安装了可以确定用于读取文件的实际解析器模块的 Spreadsheet::Read perl 模块,下面的代码片段读取并打印输入工作簿的第一个工作表的单元格。您可以检查 $workbook 对象以查看所有可配置的选项。该模块也可用于读取“csv”、“xls”等其他格式的文件。这是我发现有用的教程链接:

http://search.cpan.org/~hmbrand/Spreadsheet-Read/Read.pm

use Spreadsheet::Read;
############################################################################
# function input  : file in xlsx format with absolute path 
# function output : prints 1st worksheet content if exist
############################################################################
sub print_xlsx_file{

    my $file_path = shift;
    my $workbook = ReadData($file_path,cells => 0 );
    if(defined $workbook->[0]{'error'}){
        print "Error occurred while processing $file_path:".
              $workbook->[0]{'error'}."\n";
        exit(-1);
    }
    my $worksheet = $workbook->[1];
    my $max_rows = $worksheet->{'maxrow'};
    my $max_cols = $worksheet->{'maxcol'};

    for my $row_num (1..($max_rows))
    {
        for my $col_num (1..($max_cols)){
            print $worksheet->{'cell'}[$col_num][$row_num]."\n";
        }
    }
}
# call above function
# print_xlsx_file("/home/chammu/mybook.xlsx");
于 2014-08-31T15:29:32.447 回答