Perl中讀寫Excel很方便,貼段代碼為以後參考。
讀寫Excel的組件需要另外安裝,指令如下:
perl -MCPAN -e shell -> install Spreadsheet::WriteExcel
perl -MCPAN -e shell -> install Spreadsheet::ParseExcel
#!/usr/bin/perluse 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#依次訪問所有Sheetfor ($index=1;$index<=$Sheets_Count;$index++) {my $worksheet = $workbook->worksheet(@Sheets[$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;}#寫入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(); #建立一個Sheetif(!defined $sheet) { die "Cannot create new sheet!\n"; }#寫入第一列名 write(行號,列號,內容)$worksheet->write(0,0,'ID');$worksheet->write(0,1,'RULE');#其它處理}