#===============================
# mysql to excel
# lastmodify at 2005-1-5
# copyright by hoowa
#=============================
use strict; #严格语法检测
use dbi; #数据库引擎
use unicode::map; #unicode引擎
#use spreadsheet::writeexcel; #excel报表引擎
use spreadsheet::writeexcel::big; #大文件excel报表引擎
my $hostname='192.168.1.133';
my $username='user';
my $password='pass';
my $dbname='db';
my $trans_compress=1; #任何非一的数关闭数据库到程序间传输压缩
$|=1;
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 != '1') {
print qq~syntax: my2excel.pl <writefilename> "[where expression]"
~;
exit;
}
$argv[1]=~ s//"//g;
warn qq~
mysql to excel
by hoowa.sun
=====================
sql: $argv[1]
~;
my $dbh =
dbi->connect("dbi:mysql:mysql_compression=$trans_compress;
database=$dbname;host=$hostname",$username,$password);
my $sth = $dbh->prepare("$argv[1]") || die $dbh->errstr;
my $rows = $sth->execute() or die $sth->errstr;
warn "rows: $rows found./n";
my @cols_name = @{$sth->{'name'}};
if ($#cols_name > $#cols) {
print "table $argv[1] fields out of allow!!(max num. > ".($#cols+1).")/n";
exit;
}
warn "write to: $argv[0]/n";
#生成gb2312编码系统
my $map = unicode::map->new("gb2312");
#产生报表
my $report = spreadsheet::writeexcel::big->new("$argv[0]") || die "不能生成报表文件:$!";
#创建报表的工作表
my $sheet = $report->add_worksheet('data_report');
#创建格式
my $title_style = $report->add_format(); $title_style->set_size(11); $title_style->set_bold(); $title_style->set_align('center');
#初始化数据指针
my $sheet_col = 0;
#创建表格
for (my $i=0;$i<=$#cols_name ;$i++) {
$sheet->set_column($cols[$i], length($cols_name[$i])+4);
$sheet->write_unicode($sheet_col,$i,$map->to_unicode($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 '');
$sheet->write_unicode($sheet_col,$i,$map->to_unicode($row[$i]));
}
}
warn "all done!!!/n";
#结束
end {
$report->close() if ($report);
$dbh->disconnect();
}
新闻热点
疑难解答