如何从perl中的xlsx读取数据

时间:2013-11-05 04:47:22

标签: perl xlsx

需要一些好人帮我阅读扩展名为“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";
}

3 个答案:

答案 0 :(得分:11)

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

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

而不是使用ParseExcel。

答案 1 :(得分:2)

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

来自文档:

use Spreadsheet::ParseXLSX;

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

请参阅Spreadsheet::ParseExcel了解更多文档。

答案 2 :(得分:1)

假设您已经安装了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");