excel.init.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. if (!defined('IS_INITPHP')) exit('Access Denied!');
  3. /*********************************************************************************
  4. * InitPHP 3.8.2 国产PHP开发框架 扩展类库-CURL
  5. *-------------------------------------------------------------------------------
  6. * 版权所有: CopyRight By initphp.com
  7. * 您可以自由使用该源码,但是在使用过程中,请保留作者信息。尊重他人劳动成果就是尊重自己
  8. *-------------------------------------------------------------------------------
  9. * $Author:liuxinming
  10. * $Dtime:2012-05-10
  11. ***********************************************************************************/
  12. class excelInit{
  13. private $header = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
  14. private $coding;
  15. private $type;
  16. private $tWorksheetTitle;
  17. private $filename;
  18. /**
  19. * Excel基础配置
  20. * @param string $coding 编码
  21. * @param boolean $boolean 转换类型
  22. * @param string $title 表标题
  23. * @param string $filename Excel文件名
  24. */
  25. public function config($enCoding,$boolean,$title,$filename){
  26. //编码
  27. $this->coding=$enCoding;
  28. //转换类型
  29. if($boolean==true){
  30. $this->type='Number';
  31. }else{
  32. $this->type='String';
  33. }
  34. //表标题
  35. $title=preg_replace('/[\\\|:|\/|\?|\*|\[|\]]/', '', $title);
  36. $title = substr ($title, 0, 30);
  37. $this->tWorksheetTitle=$title;
  38. //文件名
  39. $filename=preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename);
  40. $this->filename=$filename;
  41. }
  42. /**
  43. * 循环生成Excel行
  44. * @param array $cells
  45. */
  46. public function addRow($data){
  47. $cells='';
  48. foreach ($data as $key => $val){
  49. $type=$this->type;
  50. //字符转换为 HTML 实体
  51. $val=htmlentities($val,ENT_COMPAT,$this->coding);
  52. $cells.="<Cell><Data ss:Type=\"$type\">" . $val . "</Data></Cell>\n";
  53. }
  54. return $cells;
  55. }
  56. /**
  57. * 生成Excel文件
  58. * @param array $data
  59. * @param string $filename
  60. */
  61. public function excelXls($data){
  62. header("Content-Type: application/vnd.ms-excel; charset=" . $this->coding);
  63. header("Content-Disposition: inline; filename=\"" . $this->filename . ".xls\"");
  64. /*打印*/
  65. echo stripslashes (sprintf($this->header, $this->coding));
  66. echo "\n<Worksheet ss:Name=\"" . $this->tWorksheetTitle . "\">\n<Table>\n";
  67. foreach ($data as $key => $val){
  68. $rows=$this->addRow($val);
  69. echo "<Row>\n".$rows."</Row>\n";
  70. }
  71. echo "</Table>\n</Worksheet>\n";
  72. echo "</Workbook>";
  73. }
  74. }
  75. ?>