標籤:excel 資料庫 office database
本指令碼功能:
從資料庫擷取資料並且寫入excel檔案;(據官網顯示已經廢棄此模組)
改用 Spreadsheet::ParseExcel及Spreadsheet::WriteExcel最好。前者是讀Excel檔案用的,後者用於寫Excel檔案。Spreadsheet::ParseExcel只能讀95-2003格式的Excel文檔,對於office 2007 Excel則要安裝Spreadsheet::XLSX。
#!/usr/bin/env perluse strict;use DBI;use Encode;use OLE::Storage_Lite;use Spreadsheet::WriteExcel::Big;#資料庫資訊my $host = { user => ‘root‘, pass => ‘123456‘, host => ‘127.0.0.1‘, database => ‘aries_host_info‘, port => 3306, table=>‘host‘,};#輸出檔案格式my ($sec,$min,$hour,$mday,$mon,$year) = (localtime)[0..5];($sec,$min,$hour,$mday,$mon,$year) = (sprintf("%02d", $sec),sprintf("%02d", $min),sprintf("%02d", $hour),sprintf("%02d", $mday),sprintf("%02d", $mon + 1),$year + 1900);my $date="$year$mon$mday$hour$min";#輸出excel名字 郵件實體附件my $excel_file="${date}.xls";my @cols=(‘A:A‘,‘B:B‘,‘C:C‘,‘D:D‘,‘E:E‘,‘F:F‘,‘G:G‘,‘H:H‘,‘I:I‘,‘J:J‘,‘K:K‘,‘L:L‘,‘M:M‘,‘N:N‘,‘O:O‘,‘P:P‘,‘Q:Q‘,‘R:R‘,‘S:S‘,‘T:T‘,‘U:U‘,‘V:V‘,‘W:W‘,‘X:X‘,‘Y:Y‘,‘Z:Z‘,‘AA:A‘,‘BB:B‘,‘CC:C‘,‘DD:D‘,‘EE:E‘,‘FF:F‘,‘GG:G‘,‘HH:H‘,‘II:I‘,‘JJ:J‘,‘KK:K‘,‘LL:L‘,‘MM:M‘,‘NN:N‘,‘OO:O‘,‘PP:P‘,‘QQ:Q‘,‘RR:R‘,‘SS:S‘,‘TT:T‘,‘UU:U‘,‘VV:V‘,‘WW:W‘,‘XX:X‘,‘YY:Y‘,‘ZZ:Z‘);#串連資料庫my $dbh=DBI->connect("DBI:mysql:$host->{database};host=$host->{host};port=$host->{port}",$host->{user},$host->{pass},{RaiseError=>1});#設定字元集$dbh->do ("set character_set_client = ‘utf8‘");$dbh->do ("set character_set_connection = ‘utf8‘");$dbh->do ("set character_set_results = ‘utf8‘");#sql 語句my $sql=qq(select * from $host->{table};);my $sth=$dbh->prepare($sql) or die ‘Unable to perpare our query:‘.$dbh->errstr."\n";my $results=$sth->execute() or die ‘Unable to execute our query:‘.$dbh->errstr."\n";#列印出sql的select行數到案頭、if ($results == 0){ print "查詢結果 : N/A";}else{#print "$sql cmd find $results rows.\n"; print "查詢結果:$results 行.\n"; }#從資料庫查詢結果的列名my @cols_name = @{$sth->{‘NAME‘}};if ($#cols_name > $#cols){print "result table fields overflow!(max num. > ".($#cols+1).")\n";exit;}print "正在寫入excel...\n";#建立excel檔案my $excel = Spreadsheet::WriteExcel::Big->new($excel_file) || die "excel 檔案建立失敗: $!";#建立 excel sheetmy $sheet = $excel->add_worksheet(‘anbound‘);#excel檔案格式my $title_style = $excel->add_format();$title_style->set_size(11);$title_style->set_bold();$title_style->set_align(‘center‘);my $sheet_col = 0; #列資訊#將結果輸出到excel 檔案for (my $i=0; $i<scalar @cols_name ;$i++) #列資訊{$sheet->set_column($cols[$i], length($cols_name[$i])+20);$sheet->write($sheet_col,$i,$cols_name[$i],$title_style);}#凍結表首行$sheet->freeze_panes(1, 0);while (my @row = $sth->fetchrow_array){ $sheet_col++; for (my $i=0; $i< scalar @cols_name ;$i++) { next if ($row[$i] eq ‘‘); #無資訊,就不寫入 Encode::_utf8_on($row[$i]); #把$row[i]當作utf8來處理 $sheet->write($sheet_col, $i,$row[$i]); }}print "excel寫入完成!\n";
本文出自 “大風” 部落格,請務必保留此出處http://lansgg.blog.51cto.com/5675165/1648322
perl寫入excel