Perl读写Excel简单操作
使用模块
- Spreadsheet::ParseExcel
- Spreadsheet::WriteExcel
读Excel
#!/usr/bin/perl -w
use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::FmtUnicode;
my $parser = Spreadsheet::ParseExcel->new();
my $formatter = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map=>"CP936"); #修正中文乱码问题
my $workbook = $parser->parse($ARGV[0], $formatter);
if ( !defined $workbook ) {
die $parser->error(), ".
";
}
for my $worksheet ( $workbook->worksheets() ) { #遍历sheet
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)
";
print "Value = ", $cell->value(), "
"; #读取单元格中的信息
print "
";
}
}
print "
A sheet has been read.
";
}
写Excel
#!/usr/bin/perl -w
use Spreadsheet::WriteExcel;
# 创建一个新的EXCEL文件
my $workbook = Spreadsheet::WriteExcel->new('Hello.xls');
# 添加一个工作表
$worksheet = $workbook->add_worksheet();
# 新建一个样式
$format = $workbook->add_format(); # Add a format
$format->set_bold(); #设置字体为粗体
$format->set_color('red'); #设置单元格前景色为红色
$format->set_align('center'); #设置单元格居中
#使用行号及列号,向单元格写入一个格式化和末格式化的字符串
$col = $row = 0;
$worksheet->write($row, $col, 'Hi Excel!', $format);
$worksheet->write(1, $col, 'Hi Excel!');
foreach $row (10..20)
{
foreach $col (10..20)
{
$worksheet->write($row, $col, "$row+$col", $format);
}
}
# 使用单元格名称(例:A1),向单元格中写一个数字。
$worksheet->write('A3', 1.2345);
$worksheet->write('A4', '=SIN(PI()/4)');
# 添加更多工作表
$worksheet = $workbook->add_worksheet();
foreach $row (10..20)
{
foreach $col (10..20)
{
$worksheet->write($row, $col, "$row+$col", $format);
}
}
exit;
参考资料
[1]. Spreadsheet::ParseExcel
[2]. Spreadsheet::WriteExcel