歡迎您光臨本站 註冊首頁

用perl實現從mysql資料庫里導出數據到excel

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0
此perl腳本參照博文
http://hi.baidu.com/jwxbond/blog/item/0774c566f91e7f2cab184cfe.html
修正該腳本導出UTF8字元為亂碼問題
需要安裝的模塊
Spreadsheet::WriteExcel
OLE::Storage_Lite
可從www.cpan.org上下載相關模塊,如果比較懶可以下載文章后的附件,並附一腳本安裝相關模塊,附件文件為
OLE-Storage_Lite-0.18.tar.gz
Spreadsheet-WriteExcel-2.25.tar.gz
getmysqldate.pl
腳本如下
#!/usr/bin/perl
use strict;
use DBI;
use Encode;
use Spreadsheet::WriteExcel::Big;
my $hostname="localhost"; #主機
my $username="root";#用戶名
my $password="xxx";#密碼
my $dbname=$ARGV[1];#連接的資料庫名稱
my $port=3306;#埠號
#由於連接到資料庫名需要經常變化我把資料庫名定義為一變數,如果不定義也行執行sql語句的時候可以用mysql.user;這樣的語句來定義到某個資料庫
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');
if ($#ARGV != '2') #如果接收到的ARGV值不為2則執行提示語句
{
print qq~usage: $0 FILENAME.xls DBNAME "SQL STATEMENT" n~;
exit;
}
my $script_name=$ARGV[0];
my $sql_cmd=$ARGV[2];
$sql_cmd=~ s/"//g;
my $dbh = DBI->connect("dbi:mysql:database=$dbname;host=$hostname;port=$port",$username,$password);

$dbh->do("set charset utf8;"); #mysql資料庫是utf8編碼,設置相同的編碼方式,否則中文會亂碼
my $sth = $dbh->prepare("$sql_cmd") || die $dbh->errstr;
my $rows = $sth->execute() or die $sth->errstr;
my $sql;
print "$sql cmd find $rows rows.n";
my @cols_name = @{$sth->{'NAME'}}; #從資料庫查詢結果的列名
if ($#cols_name > $#cols)
{
print "result table fields overflow!(max num. > ".($#cols 1).")n";
exit;
}
print "write to excel..n";

#創建表格文件
my $excel = Spreadsheet::WriteExcel::Big->new("$ARGV[0]") || die "文件創建失敗:$!";
#添加sheet頁
my $sheet = $excel->add_worksheet('result');
#表的格式
my $title_style = $excel->add_format();
$title_style->set_size(11);
$title_style->set_bold();
$title_style->set_align('center');
my $sheet_col = 0; #sheet列
#將結果寫入表格
for (my $i=0;$i<=$#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<=$#cols_name ;$i )
{
next if ($row[$i] eq ''); #無信息,就不寫入
Encode::_utf8_on($row[$i]); #把$row[i]當作utf8來處理
$sheet->write($sheet_col, $i,$row[$i]);
}
}
print "finish!n";
#腳本使用方法perl getmysqldate.pl fuck.xls information_schema "select * from tables;"
分號可有可無,但作為mysqlsql語法習慣了


[火星人 ] 用perl實現從mysql資料庫里導出數據到excel已經有702次圍觀

http://coctec.com/docs/linux/show-post-53168.html