perl中调用ole 处理excel文件

来源:互联网 发布:黑色沙漠巫师捏脸数据 编辑:程序博客网 时间:2024/05/01 14:32

perl中提供了win32::ole模块来操作excel表格,具体的操作函数和方法可以查阅excel的帮助文档,打开excel文件,从菜单栏"工具"->"宏”->”visual basic 脚本编译器, 选择对象浏览器中excel,就可以查看excel提供的函数和方法。

函数的使用方法也可以参考excel vba,baidu搜索一下,就可以找到使用方法。

以上方法对任何脚本操作excel都适用。同样还可以查看word的函数。

例子:perl+win32::ole+excel

use strict;
use Win32::OLE qw(in with);
use Win32::OLE::Const 'Microsoft Excel';

$Win32::OLE::Warn = 3;           # die on errors...

# get already active Excel application or open new
my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
      || Win32::OLE->new('Excel.Application', 'Quit'); 

# open Excel file
my $Book = $Excel->Workbooks->Open("c:/test.xls");

#write the excel content to txt file;
open(FH, ">e:/test.txt");
 
# select worksheet number 1 (you can also select a worksheet by name)
my $Sheet = $Book->Worksheets(1);
my$row_counts= $Sheet->{UsedRange}->{Rows}->{Count};      #得到行数
my$column_counts = $Sheet->{UsedRange}->{Columns}->{Count};    #得到列数

#set rows 2 's font is bold.
$Sheet->Rows(2)->{Font}->{Bold}=true;


my $row;
my $col;
for( $row=1;$row<$row_counts+1;$row++)
{
for( $col=1;$col<$column_counts+1;$col++)
{
    # skip empty cells
    #next unless defined $Sheet->Cells($row,$col)->{'Value'};

# print out the contents of a cell 
#    printf " %s ",
#     $Sheet->Cells($row,$col)->{'Value'},
  print FH $Sheet->Cells($row,$col)->{'Value'};
  print FH "/n";

}
#print "/n";
}
print $Sheet->Cells(2,1)->{'Value'};

# clean up after ourselves

#$Book->Save;


$Book->Close;
close FH;