在Perl中讀寫Excel表

來源:互聯網
上載者:User

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');#其它處理}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.