php导出中文内容excel文件类实例

这篇文章主要介绍了php导出中文内容excel文件类,实例分析了php操作带有中文内容的Excel文件及文件导出的实现方法,需要的朋友可以参考下。

本文实例讲述了php导出中文内容excel文件类,分享给大家供大家参考,具体如下:

  1. <?php
  2. class toExcel{
  3. public $link = null;
  4. function __construct(){
  5. }
  6. /***************************************************************************
  7. * $mapping:数组格式头信息$map=array('No','Name','Email','Age');
  8. * $datalist:数据库查出来的结果集
  9. * $fileName:Excel文件名称
  10. * return:Excel格式文件
  11. **************************************************************************/
  12. public function toExcel($mapping,$datalist,$fileName) {
  13. header("Content-type:application/vnd.ms-excel");
  14. header("Content-Disposition:filename=".iconv('utf-8', 'gb2312', $fileName).".xls");
  15. echo'<html xmlns:o="urn:schemas-microsoft-com:office:office"
  16. xmlns:x="urn:schemas-microsoft-com:office:excel"
  17. xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">
  18. <head>
  19. <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
  20. <meta http-equiv=Content-Type content="text/html; charset=UTF-8">
  21. <!--[if gte mso 9]><xml>
  22. <x:ExcelWorkbook>
  23. <x:ExcelWorksheets>
  24. <x:ExcelWorksheet>
  25. <x:Name></x:Name>
  26. <x:WorksheetOptions>
  27. <x:DisplayGridlines/>
  28. </x:WorksheetOptions>
  29. </x:ExcelWorksheet>
  30. </x:ExcelWorksheets>
  31. </x:ExcelWorkbook>
  32. </xml><![endif]-->
  33. </head>
  34. <body link=blue vlink=purple leftmargin=0 topmargin=0>';
  35. echo'<table cellspacing="0" cellpadding="0">';
  36. echo'<tr>';
  37. if(is_array($mapping)) {
  38. foreach($mapping as $key=>$val)
  39. echo"<td >".$val."</td>";
  40. }
  41. echo'</tr>';
  42. foreach($datalist as $k=>$v){
  43. echo'<tr>';
  44. foreach($v as $key=>$val){
  45. if(is_numeric($val) && strlen($val)>=14){
  46. echo"<td >".$val."</td>"; //大于14位的数字转换成字符串输出(如身份证)
  47. }else{
  48. echo"<td>".$val."</td>";
  49. }
  50. }
  51. echo'</tr>';
  52. }
  53. echo'</table>';
  54. echo'</body>';
  55. echo'</html>';
  56. }
  57. }
  58. $map=array('No','Name','Email');
  59. $datal=array(array(1, '管理员', 'admin@163.com'), array(2, 'member', 'member@163.com'));;
  60. $csv=new toExcel;
  61. $csv->toExcel($map,$datal,"dataexport");
  62. ?>

方法二

  1. <?php
  2. header("Content-Type: application/vnd.ms-execl");
  3. header("Content-Disposition: attachment; filename=myExcel.xls");
  4. header("Pragma: no-cache");
  5. header("Expires: 0");
  6. /*first line*/
  7. $data1= "中文测试";
  8. $data1=mb_convert_encoding($data1,"GB2312","UTF-8");
  9. echo $data1."\t";
  10. echo "world"."\t";
  11. echo "\t\n";
  12. /*start of second line*/
  13. echo "this is second line"."\t";
  14. echo "Hi,pretty girl"."\t";
  15. echo "\t\n";
  16. ?>