歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Unix知識 >> 關於Unix >> 功能豐富的Perl:用Perl讀寫Excel文件

功能豐富的Perl:用Perl讀寫Excel文件

日期:2017/3/6 15:50:25   编辑:關於Unix
Spreadsheet::WriteExcel 和 Spreadsheet::ParseExcel 在 2000 年,Takanori Kawai 和 John McNamara 編寫出了 Spreadsheet::WriteExcel 和 Spreadsheet::ParseExcel 模塊並將它們張貼在 CPAN 上,這兩個模塊使得在任何平台上從 Excel 文件抽取數據成為可能
  Spreadsheet::WriteExcel 和 Spreadsheet::ParseExcel
  在 2000 年,Takanori Kawai 和 John McNamara 編寫出了 Spreadsheet::WriteExcel 和 Spreadsheet::ParseExcel 模塊並將它們張貼在 CPAN 上,這兩個模塊使得在任何平台上從 Excel 文件抽取數據成為可能(盡管不容易)。
  
  正如我們在稍後將看到的,如果您正在使用 Windows,Win32::OLE 仍提供一個更簡單、更可靠的解決方案,並且 Spreadsheet::WriteExcel 模塊建議使用 Win32::OLE 來進行更強大的數據和工作表操縱。Win32::OLE 帶有 ActiveState Perl 工具箱,可以用來通過 OLE 驅動許多其它 Windows 應用程序。請注意,要使用此模塊,您仍需要在機器上安裝和注冊一個 Excel 引擎(通常隨 Excel 本身安裝)。
  
  需要解析 Excel 數據的應用程序數以千計,但是這裡有幾個示例:將 Excel 導出到 CSV、與存儲在共享驅動器上的電子表格交互、將金融數據移至數據庫以便形成報告以及在不提供任何其他格式的情況下分析數據。
  
  要演示這裡給出的示例,必須在您的系統上安裝 Perl 5.6.0。您的系統最好是最近(2000 年或以後)的主流 UNIX 安裝(Linux、Solaris 和 BSD)。雖然這些示例在以前版本的 Perl 和 UNXI 以及其他操作系統中也可以使用,但是您應該考慮到您將面對那些它們無法作為練習發揮作用的情況。
  
  Windows 示例:解析
  本節僅適用於 Windows 機器。所有其它各節適用於 Linux。
  
  在進行之前,請安裝 ActiveState Perl(這裡使用版本 628)或 ActiveState Komodo IDE 以編輯和調試 Perl。Komodo 為家庭用戶提供一個免費許可證,您大概在幾分鐘之內就可以得到它。(有關下載站點,請參閱本文後面的參考資料。)
  
  使用 ActiveState PPM 軟件包管理器安裝 Spreadsheet::ParseExcel 和 Spreadsheet::WriteExcel 模塊是困難的。PPM 沒有歷史記錄,難以設置選項,幫助會滾出屏幕並且缺省方式是忽略相關性而安裝。您可以從命令行輸入“ppm”然後發出以下命令來調用 PPM:
  
  清單 1:安裝 Excel 模塊的 PPM 命令
  
  ppm> install OLE::Storage_Lite
  ppm> install Spreadsheet::ParseExcel
  ppm> install Spreadsheet::WriteExcel
  
  在這種情況下,該模塊的安裝將失敗,因為 IO::Scalar 還不可用,因此,您可能想放棄 PPM 問題的查找,而轉向內置的 Win32::OLE 模塊。然而,在您閱讀本文時,ActiveState 可能已經發布了該問題的修正。
  
  有了 ActiveState 的 Win32::OLE,您可以使用下面所列的代碼逐個單元地轉儲工作表:
  
  下載 win32excel.pl
  
  清單 2:win32excel.pl
  
  #!/usr/bin/perl -w
  
  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:/komodo projects/test.xls");
  
  # You can dynamically obtain the number of worksheets, rows, and columns
  # through the Excel OLE interface. Excel's Visual Basic Editor has more
  # information on the Excel OLE interface. Here we just use the first
  # worksheet, rows 1 through 4 and columns 1 through 3.
  
  # select worksheet number 1 (you can also select a worksheet by name)
  my $Sheet = $Book->Worksheets(1);
  
  foreach my $row (1..4)
  {
   foreach my $col (1..3)
   {
   # skip empty cells
   next unless defined $Sheet->Cells($row,$col)->{'Value'};
  
   # print out the contents of a cell 
   printf "At ($row, $col) the value is %s and the formula is %s\n",
    $Sheet->Cells($row,$col)->{'Value'},
    $Sheet->Cells($row,$col)->{'Formula'};    
   }
  }
  
  # clean up after ourselves
  $Book->Close;
  
  請注意,您可以用以下方式很輕松地為單元分配值:
  
  $sheet->Cells($row, $col)->{'Value'} = 1;
  
  Linux 示例:解析
  本節適用於 UNIX,特別適用於 Linux。沒有在 Windows 中測試它。
  
  很難給出一個比 Spreadsheet::ParseExcel 模塊文檔中所提供的示例更好的 Linux 解析示例,因此我將演示那個示例,然後解釋其工作原理。
  
  下載 parse-excel.pl
  
  清單 3:parse-excel.pl
  
  #!/usr/bin/perl -w
  
  use strict;
  use Spreadsheet::ParseExcel;
  
  my $oExcel = new Spreadsheet::ParseExcel;
  
  die "You must provide a filename to $0 to be parsed as an Excel file" unless @ARGV;
  
  my $oBook = $oExcel->Parse($ARGV[0]);
  my($iR, $iC, $oWkS, $oWkC);
  print "FILE :", $oBook->{File} , "\n";
  print "COUNT :", $oBook->{SheetCount} , "\n";
  
  print "AUTHOR:", $oBook->{Author} , "\n"
   if defined $oBook->{Author};
  
  for(my $iSheet=0; $iSheet < $oBook->{SheetCount} ; $iSheet++)
  {
   $oWkS = $oBook->{Worksheet}[$iSheet];
   print "--------- SHEET:", $oWkS->{Name}, "\n";
   for(my $iR = $oWkS->{MinRow} ;
     defined $oWkS->{MaxRow} && $iR <= $oWkS->{MaxRow} ;
     $iR++)
   {
   for(my $iC = $oWkS->{MinCol} ;
     defined $oWkS->{MaxCol} && $iC <= $oWkS->{MaxCol} ;
     $iC++)
   {
    $oWkC = $oWkS->{Cells}[$iR][$iC];
    print "( $iR , $iC ) =>", $oWkC->Value, "\n" if($oWkC);
   }
   }
  }
  
  此示例是用 Excel 97 測試的。如果它不能工作,則試著將它轉換成 Excel 97 格式。Spreadsheet::ParseExcel 的 perldoc 頁也聲稱了 Excel 95 和 2000 兼容性
  
  電子表格被解析成一個名為 $oBook 的頂級對象。$oBook 具有輔助程序的特性,例如“File”、“SheetCount”和“Author”。 Spreadsheet::ParseExcel 的 perldoc 頁的工作簿一節中記載了這些特性。
  
  該工作簿包含幾個工作表:通過使用工作簿 SheetCount 特性迭代它們。每個工作表都有一個 MinRow 和 MinCol 以及相應的 MaxRow 和 MaxCol 特性,它們可以用來確定該工作簿可以訪問的范圍。Spreadsheet::ParseExcel perldoc 頁的工作表一節中記載了這些特性。
  
  可以通過 Cell 特性從工作表獲得單元;那就是清單 3 中獲得 $oWkC 對象的方式。Spreadsheet::ParseExcel 的 perldoc 頁的 Cell 一節中記載了 Cell 特性。根據文檔,似乎沒有一種方式能夠獲得特定單元中列出的公式。
  
  Linux 示例:寫入
  本節適用於 UNIX,特別適用於 Linux。沒有在 Windows 中測試它。
  
  Spreadsheet::WriteExcel 在 Examples 目錄中帶有許多示例腳本,通常可以在 /usr/lib/perl5/site_perl/5.6.0/Spreadsheet/WriteExcel/examples 下找到這些腳本。它可能被安裝在其它各處;如果找不到那個目錄,請與您的本地 Perl 管理員聯系。
  
  壞消息是 Spreadsheet::WriteExcel 無法用於寫入現有 Excel 文件。必須自己使用 Spreadsheet::ParseExcel 從現有 Excel 文件導入數據。好消息是 Spreadsheet::WriteExcel 與 Excel 5 直至 Excel 2000 兼容。
  
  這裡有一個程序,它演示如何從一個 Excel 文件抽取、修改(所有數字都乘以 2)數據以及將數據寫入新的 Excel 文件。只保留數據,不保留格式和任何特性。公式被丟棄。
  
  下載 excel-x2.pl
  
  清單 4:excel-x2.pl
  
  #!/usr/bin/perl -w
  
  use strict;
  use Spreadsheet::ParseExcel;
  use Spreadsheet::WriteExcel;
  use Data::Dumper;
  
  # cobbled together from examples for the Spreadsheet::ParseExcel and
  # Spreadsheet::WriteExcel modules
  
  my $sourcename = shift @ARGV;
  my $destname = shift @ARGV or die "invocation: $0 ";
  
  my $source_excel = new Spreadsheet::ParseExcel;
  
  my $source_book = $source_excel->Parse($sourcename)
   or die "Could not open source Excel file $sourcename: $!";
  
  my $storage_book;
  
  foreach my $source_sheet_number (0 .. $source_book->{SheetCount}-1)
  {
   my $source_sheet = $source_book->{Worksheet}[$source_sheet_number];
  
   print "--------- SHEET:", $source_sheet->{Name}, "\n";
  
   # sanity checking on the source file: rows and columns should be sensible
   next unless defined $source_sheet->{MaxRow};
   next unless $source_sheet->{MinRow} <= $source_sheet->{MaxRow};
   next unless defined $source_sheet->{MaxCol};
   next unless $source_sheet->{MinCol} <= $source_sheet->{MaxCol};
  
   foreach my $row_index ($source_sheet->{MinRow} .. $source_sheet->{MaxRow})
   {
   foreach my $col_index ($source_sheet->{MinCol} .. $source_sheet->{MaxCol})
   {
    my $source_cell = $source_sheet->{Cells}[$row_index][$col_index];
    if ($source_cell)
    {
    print "( $row_index , $col_index ) =>", $source_cell->Value, "\n";
  
    if ($source_cell->{Type} eq 'Numeric')
    {
   $storage_book->{$source_sheet->{Name}}->{$row_index}->{$col_index} = $source_cell->Value*2;
    }
    else
    {
   $storage_book->{$source_sheet->{Name}}->{$row_index}->{$col_index} = $source_cell->Value;
    } # end of if/else
    } # end of source_cell check
   } # foreach col_index
   } # foreach row_index
  } # foreach source_sheet_number
  
  print "Perl recognized the following data (sheet/row/column order):\n";
  print Dumper $storage_book;
  
  my $dest_book = Spreadsheet::WriteExcel->new("$destname")
   or die "Could not create a new Excel file in $destname: $!";
  
  print "\n\nSaving recognized data in $destname...";
  
  foreach my $sheet (keys %$storage_book)
  {
   my $dest_sheet = $dest_book->addworksheet($sheet);
   foreach my $row (keys %{$storage_book->{$sheet}})
   {
   foreach my $col (keys %{$storage_book->{$sheet}->{$row}})
   {
    $dest_sheet->write($row, $col, $storage_book->{$sheet}->{$row}->{$col});
   } # foreach column
   } # foreach row
  } # foreach sheet
  
  $dest_book->close();
  
  print "done!\n";
  
  值得注意的是,程序的數據抽取和存儲部分必須要分開。它們本來可以同時進行,但是通過將它們分開,可以輕松地進行錯誤修復和改進。
  
  對於上述問題,一個好得多的解決方案可能是通過 XML::Excel CPAN 模塊實現,但是必須編寫將 XML 轉換回 Excel 的特殊轉換器。 如果要以那種方式導入數據,還可以通過 DBD::Excel 模塊使用 DBI 接口。最後,Spreadsheet::ParseExcel 帶有 Spreadsheet::ParseExcel::SaveParser 模塊,它聲稱可以在兩個 Excel 文件之間轉換,但是沒有文檔和示例。我的網站(請參閱參考資料)演示了一個使用 SaveParser 的示例。事先警告:那是個實驗型程序,極易出問題。
  
  結束語
  如果您正在使用 Windows 機器,請堅持使用 Win32::OLE 模塊,除非您的機器上根本沒有 Excel。雖然 Spreadsheet::WriteExcel 和 Spreadsheet::ParseExcel 模塊的功能正不斷完善,但 Win32::OLE 是目前獲得 Excel 數據的最簡便方式。
  
  在 UNIX,特別是 Linux 上,請使用 Spreadsheet::WriteExcel 和 Spreadsheet::ParseExcel 模塊對 Excel 數據進行編程訪問。但是事先警告:它們還是相當不成熟的模塊,如果您需要穩定性,則它們可能不適合您。

Copyright © Linux教程網 All Rights Reserved