天天看點

Spreadsheet::WriteExcel 和 Spreadsheet::Read 對 excel 檔案的讀寫

Spreadsheet::WriteExcel 和 Spreadsheet::Read 對 excel 檔案的讀寫 2010-05-08 16:49 轉自 http://hi.baidu.com/%C2%ED%B3%A4%D5%F72008/blog/item/16cc0f4eedb7553aafc3ab9a.html

因為工作需要,給一些内容的結果需要轉換成excel給上面看,是以用perl來實作這個事件,發現perl來寫excel實在是太容易了。。我真想學老羅的講"太容易了,實在是太容易了".

在 2000 年,Takanori Kawai 和 John McNamara 編寫出了 Spreadsheet::WriteExcel 和 Spreadsheet::ParseExcel 子產品并将它們張貼在 CPAN 上,這兩個子產品使得在任何平台上從 Excel 檔案抽取資料成為可能。

perl寫excel這個子產品的内容

#!/usr/bin/perl
use strict;
use warnings;
 
use Encode;
use Spreadsheet::WriteExcel;
 
# 設定new一個對象出來,并寫上需要存成什麼名字的xls
my $xls = Spreadsheet::WriteExcel->new( "fukaiss.xls" );
 
# xml的内容名字
my $xlsContent = $xls->add_worksheet( 'report' );
 
# 這是對格式的設定,我們可以設定一個标題的,一個内容的,
# 我現在隻設定一個内容
my $contentStyle = $xls->add_format();
    $contentStyle->set_size( 8 );
    $contentStyle->set_bold();           #設定字型為粗體
    $contentStyle->set_align( 'center' );#設定單元格居中
    $contentStyle->set_text_wrap();      #是否回車換行
    $contentStyle->set_color('red');     #設定單元格前景色為紅色
 
# 寫表内容(格式是使用上面添加的表格式)
# 這個中的A,B,C是設定的excel中上面行的字母
# 這個地方中的文字我用了decode這樣中文才能正常顯示
# 最後面的contentStyle是我上面設定的行風格
 
$xlsContent->write( "A1", decode( 'utf8', "名字" ), $contentStyle );
$xlsContent->write( "B1", decode( 'utf8', "時間" ), $contentStyle );
$xlsContent->write( "C2", decode( 'utf8', "語言" ), $contentStyle );
#$xlsContent->write($row, $col, 'Hi Excel!', $format); #行,列,内容,格式
 
#這是關閉,上面的内容設定成循環就能生成很多行了
$xls->close();      

其它一些有用的設定

# #設定列的寬度

set_column($first_col, $last_col, $width, $format, $hidden, $level, $collapsed)

下面perl是讀excel檔案内容

我用的Spreadsheet::Read 子產品可以讀取xls,csv和sxc等格式的檔案,這是那本Perl Hacks上非常推薦的讀這些的子產品.
#!/usr/bin/perl
use Spreadsheet::Read;
use Data::Dumper;
use Smart::Comments;
 
my $file = '2808861.xls';
my $spreadsheet = ReadData( $file) or die "Cannot read file ";#指定讀的檔案名
my $sheet_count = $spreadsheet->[0]{sheets} or die "No sheets in $file\n"; #這個是查有幾個sheet
for my $sheet_index (1 .. $sheet_count){
    my $sheet = $spreadsheet->[$sheet_index] or next;
    printf("%s - %2d: [%-s] %3d Cols, %5d Rows\n",
                     $file,$sheet_index,$sheet->{label},$sheet->{maxcol},$sheet->{maxrow});#label是sheet名
    for my $row (1 .. $sheet->{maxrow}) {
        print join "\t" => map {
                                my $data = $sheet->{cell}[$_][$row] ;
                                defined $data ? $data : "-";
                }1 .. $sheet->{maxcol};
        print "\n";
    };
}      
# 傳一個輸出的檔案和一個數組和數組就能輸入 execl 啦,記的第一行做标題
sub excelWrite(
    my ( $filename, $file ) = @_;
    my $xls = Spreadsheet::WriteExcel::Big->new( "$filename" );
    $xls->compatibility_mode();
    my $xlsContent= $xls->add_worksheet( "$filename" );
 
    # 标題風格
    my $titleStyle  = $xls->add_format( 
                                        size    => 10,
                                        bold    => 1,
                                        border  => 2,
                                        align   => 'center',
                                    );
    # 内容風格
    my $rowStyle    = $xls->add_format( 
                                        align   => 'left',
                                        border  => 1,
                                    );
    # 設定行的寬,先查出全部有資料的一行,來做為寬度的基準
    my @tmp = ();
    foreach my $line ( 2 .. $#{$file} ){
        foreach my $contentNu ( 0 .. $#{$file->[$line]} ){
           next if $tmp[$contentNu];
           $tmp[$contentNu] = $file->[$line][$contentNu];
        }
    }
 
    foreach ( 0 .. $#tmp ){
        $xlsContent->set_column( $_ , $_+1, 4 + length $tmp[$_]);
    }
 
    # 列
    my $row = 0;
    foreach my $line ( @{$file} ){
 
        # 對風格的處理,第一行不一樣
        my $Style = $rowStyle;
        if ($row == 0 ){
            $Style = $titleStyle; 
        }
 
        # 行處理
        my $col = 0;
        foreach my $content ( @{$line} ){
            chomp $content;
            $xlsContent->set_row($row, 23);
            $xlsContent->write( $row, $col, decode("gbk",$content) ,$Style );     
            $col ++;
        }
 
        $row ++;
    }
    $xls->close();
}      

*********将現有的excel檔案導入到新的excel檔案中執行個體*********

import.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 <source file> <destination file>";
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";      
#import.pl source.xls des.xls