我在PHP项目里要求把数据导出为Excel,并且数据中包含中文.
网上大概了解一下可是使用PHPExcel,可是相对我的需求,这个框架太复杂了.于是还是想找找简单做法.
网上发现其实最简单可以这样写,但问题是这种做法中文的编码不可靠..
01
<?php
02
header(
"Content-type:application/vnd.ms-excel"
);
03
header(
"Content-Disposition:attachment;filename=export_data.xls"
);
04
05
echo
"姓名"
.
"\t"
;
06
echo
"繁體"
.
"\t"
;
07
echo
"博客"
.
"\t"
;
08
echo
"\n"
;
09
echo
"jason"
.
"\t"
;
10
echo
"@"
.
"\t"
;
11
echo
"javaeye"
.
"\t"
;
12
?>
有些同学会想到header加入字符集
1
header(
"Content-type:application/vnd.ms-excel;charset=UTF-8"
);
问题: 这里只是告诉浏览器要选什么字符集查看,最终我的需求还是要生成xls文件.
当然.有些同学还会想到用iconv转码.
1
echo
iconv(
"当前编码"
,
"GB18030"
,
"此博客来源于javaeye,by jason"
);
问题: 这样文件里的汉字编码就GB18030,可是Excel这么知道用什么编码打开呢?只能完全依赖OS默认.可是如果碰到繁体BIG5这么办,还是会乱码. 所以还是不靠谱.
最后我采用phpMyAdmin的做法.用HTMLExcel, HTML我们比较熟悉,格式如下.
01
<
html
xmlns:o
=
"urn:schemas-microsoft-com:office:office"
02
xmlns:x
=
"urn:schemas-microsoft-com:office:excel"
03
xmlns
=
"http://www.w3.org/TR/REC-html40"
>
04
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05
<
html
>
06
<
head
>
07
<
meta
http-equiv
=
"Content-type"
content
=
"text/html;charset=UTF-8"
/>
08
<
style
id
=
"Classeur1_16681_Styles"
></
style
>
09
</
head
>
10
<
body
>
11
<
div
id
=
"Classeur1_16681"
align
=
center
x:publishsource
=
"Excel"
>
12
<
table
x:str
border
=
0
cellpadding
=
0
cellspacing
=
0
width
=
100
%
style
=
"border-collapse: collapse"
>
13
<
tr
><
td
class
=
xl2216681
nowrap>1234</
td
><
td
class
=
xl2216681
nowrap>Robbin会吐口水</
td
></
tr
>
14
<
tr
><
td
class
=
xl2216681
nowrap>5678</
td
><
td
class
=
xl2216681
nowrap>javaeye网站</
td
></
tr
>
15
</
table
>
16
</
div
>
17
</
body
>
18
</
html
>
这下可以直接echo了,又不需要iconv转码,只要设置好HTML里的Content-type(这里用的是UTF-8),是不是有舒服的感觉呢? 当然header还是要加上
1
header(
"Content-type:application/vnd.ms-excel"
);
2
header(
"Content-Disposition:attachment;filename=export_data.xls"
);
一点小经验和各位同学分享一下.. :)