#!/usr/bin/perl
use Spreadsheet::WriteExcel;
use Encode;#
use DBI; #(这里增加DBI)
#*连接数据库:数据库名:db_Test ,IP及端口localhost:3306,用户:user ,密码:111
my $dbhA = DBI->connect(“DBI:mysql:jeepay:localhost:3306”, “root”, “123456”)
or die "Couldn’t connect to database: " . DBI->errstr;
#***准备查询语句
my $query_statement = $dbhA->prepare(“select * from t_sys_role”)||die $DBI::errstr;
#执行查询
$query_statement ->execute();
#以下是对Excel操作
#生成Excel文档****
my $xl = Spreadsheet::WriteExcel->new(“TEST.xls”);
#生成Excel表
my $xlsheet = $xl->add_worksheet(decode(‘utf8’ ,“测试写入Excel”));#(中文名称)
#添加格式(表头)
$rptheader = $xl->add_format(); # Add a format
$rptheader->set_bold();
$rptheader->set_size(‘12’);
$rptheader->set_align(‘center’);
#添加格式(表内容)
$normcell = $xl->add_format(); # Add a format
$normcell->set_size(‘9’);
$normcell->set_align(‘center’);
$normcell->set_bg_color(‘22’);
#设置列的宽度
$xlsheet->set_column(‘A:A’,10);
$xlsheet->set_column(‘B:B’,12);
$xlsheet->set_column(‘C:C’,17);
$xlsheet->set_column(‘D:D’,18);
$xlsheet->set_column(‘E:E’,18);
#写表头(格式是使用上面添加的表头格式)
$xlsheet->write(“B2”,decode(‘utf8’,“角色编号”), $rptheader);
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
C
2
"
,
d
e
c
o
d
e
(
′
u
t
f
8
′
,
"
角
色
名
称
"
)
,
xlsheet->write("C2", decode('utf8',"角色名称"),
xlsheet−>write("C2",decode(′utf8′,"角色名称"),rptheader);
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
D
2
"
,
d
e
c
o
d
e
(
′
u
t
f
8
′
,
"
系
统
类
型
"
)
,
xlsheet->write("D2", decode('utf8',"系统类型"),
xlsheet−>write("D2",decode(′utf8′,"系统类型"),rptheader);
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
E
2
"
,
d
e
c
o
d
e
(
′
u
t
f
8
′
,
"
归
属
信
息
"
)
,
xlsheet->write("E2", decode('utf8',"归属信息"),
xlsheet−>write("E2",decode(′utf8′,"归属信息"),rptheader);
$xlsheet->write(“F2”, decode(‘utf8’,“创建时间戳”), $rptheader);
#循环输出到Excel
my $num=3; #excel中的位置
my $record_num = 0; #编号
my $ref = “通过”;
while(my @row = $query_statement->fetchrow_array())
{
$record_num++;
$role_id = $row[0];
$$role_name= $row[1];
$sys_type = $row[2];
$belong_info_id = $row[3];
$updated_at = $row[4];
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
B
xlsheet->write("B
xlsheet−>write("Bnum", decode(‘utf8’,$role_id ), $normcell);
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
C
xlsheet->write("C
xlsheet−>write("Cnum", decode(‘utf8’,
r
o
l
e
n
a
m
e
)
,
role_name),
rolename),normcell);
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
D
xlsheet->write("D
xlsheet−>write("Dnum", decode(‘utf8’,
s
y
s
t
y
p
e
)
,
sys_type),
systype),normcell);
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
E
xlsheet->write("E
xlsheet−>write("Enum", decode(‘utf8’ ,
b
e
l
o
n
g
i
n
f
o
i
d
)
,
belong_info_id ),
belonginfoid),normcell);
x
l
s
h
e
e
t
−
>
w
r
i
t
e
(
"
F
xlsheet->write("F
xlsheet−>write("Fnum", decode(‘utf8’,
u
p
d
a
t
e
d
a
t
)
,
updated_at),
updatedat),normcell);
$num++;
}
$query_statement->finish();#完成
$dbhA->disconnect(); #断开数据库连接
$xl->close(); #关闭操作excel的对象.