perl解析excel文件的例子,使用到了如下的两个模块:
use Spreadsheet::ParseExcel;
use Spreadsheet::WriteExcel;
一,解析excel
#!/usr/bin/perl
use strict;
use Spreadsheet::ParseExcel;
my $parser = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse('Book.xls');
if ( !defined $workbook ) {
die $parser->error(), ".n";
}
for my $worksheet ( $workbook->worksheets() )
{
my ( $row_min, $row_max ) = $worksheet->row_range();
my ( $col_min, $col_max ) = $worksheet->col_range();
for my $row ( $row_min .. $row_max ) {
for my $col ( $col_min .. $col_max ) {
my $cell = $worksheet->get_cell( $row, $col );
next unless $cell;
print "Row, Col = ($row, $col)n";
print "Value = ", $cell->value(), "n";
print "n";
}
}
}
二,写入excel文件
#!/usr/bin/perl
use strict;
use Spreadsheet::WriteExcel;
my $result = new Spreadsheet::WriteExcel("Book.xls");
my $fmt = $result->add_format();
$fmt->set_align('center');
$fmt->set_color('black');
my $sheet = "1";
my $dest_sheet1 = $result->addworksheet($sheet);
$dest_sheet1->write( 0, 0, T("book_id"), $fmt->{HEADER} );
$dest_sheet1->write( 0, 1, T("book_name"), $fmt->{HEADER} );
$dest_sheet1->write( 0, 2, T("book_type"), $fmt->{HEADER} );
$dest_sheet1->write( 0, 3, T("book_price"), $fmt->{HEADER} );
my $Num = 1;
foreach ( sort { $a <=> $b } keys %{$res_get_result} ) {
$dest_sheet1->write( $Num, 0, T( $res_get_result->{$_}->{book_id} ), $fmt );
$dest_sheet1->write( $Num, 1, T( $res_get_result->{$_}->{book_name} ), $fmt );
$dest_sheet1->write( $Num, 2, T( $res_get_result->{$_}->{book_type} ), $fmt );
$dest_sheet1->write( $Num, 3, $res_get_result->{$_}->{book_price}, $fmt );
$Num++;
}