本文实例讲述了php 自定义函数实现将数据 以excel 表格形式导出。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/** * 导出数据为excel表格 * @param * array $data 一个二维数组,结构如同从数据库查出来的数组 * array $title excel的第一行标题,一个数组,如果为空则没有标题 * String $filename 下载的文件名 */ function exportexcel( $data = array (), $title = array (), $filename = 'report' ){ header( "Content-type:application/octet-stream" ); header( "Accept-Ranges:bytes" ); header( "Content-type:application/vnd.ms-excel" ); header( "Content-Disposition:attachment;filename=" . $filename . ".xls" ); header( "Pragma: no-cache" ); header( "Expires: 0" ); //导出xls 开始 if (! empty ( $title )){ foreach ( $title as $k => $v ) { $title [ $k ]=iconv( "UTF-8" , "GB2312" , $v ); } $title = implode( "\t" , $title ); echo "$title\n" ; } if (! empty ( $data )){ foreach ( $data as $key => $val ){ foreach ( $val as $ck => $cv ) { $data [ $key ][ $ck ]=mb_convert_encoding( $cv , "GB2312" , "UTF-8" ); } $data [ $key ]=implode( "\t" , $data [ $key ]); } echo implode( "\n" , $data ); } } |
php内置函数讲解
String mb_convert_encoding( $str, $encoding1,$encoding2 )
$str
,要转换编码的字符串
$encoding1
,目标编码,如utf-8,gbk,大小写均可
$encoding2
,原编码,如utf-8,gbk,大小写均可
demo
1
2
3
4
|
$title = array ( "title1" , "title2" , "title3" ); $data = array ( "数据1" , "数据2" , "数据3" ); $fileName = "demo" ; exportexcel( $data , $title , $fileName ); |
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/u014559227/article/details/72965441