讀寫Excel的元件需要另外安裝,指令如下:
perl -MCPAN -e shell -> install Spreadsheet::WriteExcel
perl -MCPAN -e shell -> install Spreadsheet::ParseExcel
Python代碼
#!/usr/bin/perl
use Spreadsheet::WriteExcel; #寫入Excel資料
use Spreadsheet::ParseExcel; #讀取Excel資料
# 讀取資料
# 使用: LoadStringsFromExcel(fileName);
sub LoadStringsFromExcel
{
my $parser = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse(@_[0]); #打開傳入的檔
my $TotalCount = 0;
if(!defined $workbook) #是否打開成功
{
print "Failed to open @_[0]\n";
die $parser->error(),".\n";
}
$Sheets_Count = $workbook->worksheet_count(); #有多少個Sheet
#依次訪問所有Sheet
for ($index=1;$index<=$Sheets_Count;$index++)
{
my $worksheet = $workbook->worksheet($index-1);
my $result;
if(!defined $worksheet) #讀取Sheet失敗
{
print "Could not get the worksheet \n";
last;
}
else
{
$result = LoadWordingsFromSheet($worksheet);
$TotalCount += $result;
}
}
printf "\nTotal found $TotalCount strings\n";
print "Finished!\n";
}
# 讀取Sheet中字串,由LoadStringsFromExcel呼叫
sub LoadWordingsFromSheet
{
my $sheet = $_[0]; #取得傳入的sheet
if(!defined $sheet)
{
die "Could not get argument!\n";
}
#得到Sheet中的最小行號及最大行號
my ($minRow,$maxRow) = $sheet->row_range();
print "Now, checking ",$sheet->get_name()," \n"; #列印Sheet的名稱
$count = 1;
#依次讀取每行資料中第一列的資料
for($i=$minRow;$i<=$maxRow;$i++)
{
#取到第一列的資料, get_cell(行號,列號)
$str = ($sheet->get_cell($i,0))->value();
$str = trim($str);
print $str,"\n";
$count++;
}
return $count;
}
sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
#寫入Excel
#使用WriteDataToExcel(檔案名)
sub WriteDataToExcel
{
my $workbook = Spreadsheet::WriteExcel->new(@_[0]);#打開Excel檔
if(!defined $workbook) #是否打開成功
{
print "Failed to open @_[0]\n";
die $parser->error(),".\n";
}
my $worksheet = $workbook->add_worksheet(); #新建一個Sheet
if(!defined $sheet)
{
die "Cannot create new sheet!\n";
}
#寫入第一行標題 write(行號,列號,內容)
$worksheet->write(0,0,'ID');
$worksheet->write(0,1,'RULE');
#其它處理
}
沒有留言:
張貼留言