国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

php生成EXCEL文檔實例程序

2024-05-04 21:47:27
字體:
來源:轉載
供稿:網友

原生態的寫法

原始方式:發送header,用附件的表頭發送到用戶瀏覽器表示是要下載的,然后讀出數據庫中的數據,一條一條的解析,寫入excel格式的文件中,代碼如下:

  1. <?php   
  2.   $DB_Server = "localhost";   
  3.   $DB_Username = "root";   
  4.   $DB_Password = "";   
  5.   $DB_DBName = "DBName";   
  6.   $DB_TBLName = "DB_TBLName";   
  7.   $savename = date("YmjHis");   
  8.   $Connect = @mysql_connect($DB_Server$DB_Username$DB_Passwordor die("Couldn't connect.");   
  9.   mysql_query("Set Names 'gbk'");   
  10.   $file_type = "vnd.ms-excel";   
  11.   $file_ending = "xls";   
  12.   header("Content-Type: application/$file_type;charset=gbk");   
  13.   header("Content-Disposition: attachment; filename=".$savename.".$file_ending");   
  14.   header("Pragma: no-cache");   
  15.   $now_date = date("Y-m-j H:i:s");   
  16.   $title = "數據庫名:$DB_DBName,數據表:$DB_TBLName,備份日期:$now_date";   
  17.   $sql = "Select * from $DB_TBLName";   
  18.   $ALT_Db = @mysql_select_db($DB_DBName$Connector die("Couldn't select  database");   
  19.   $result = @mysql_query($sql,$Connector die(mysql_error());   
  20.   echo("$titlen");   
  21.   $sep = "t";   
  22.   for ($i = 0;$i < mysql_num_fields($result);$i++)   
  23.      {   
  24.          echo mysql_field_name($result,$i) . "t";   
  25.      }   
  26.   print("n");   
  27.   $i = 0;   
  28.   while($row = mysql_fetch_row($result))   
  29.   {   
  30.     $schema_insert = "";   
  31.     for($j=0; $j<mysql_num_fields($result);$j++)   
  32.       {   
  33.         if(!isset($row[$j])) $schema_insert .= "NULL".$sep;   
  34.         elseif ($row[$j] != ""$schema_insert .= "$row[$j]".$sep;   
  35.         else $schema_insert .= "".$sep;   
  36.        }   
  37.        $schema_insert = str_replace($sep."$"""$schema_insert);   
  38.        $schema_insert .= "t";   
  39.        print(trim($schema_insert));   
  40.        print "n"$i++;   
  41.   }   
  42.   return (true);   
  43.   ?> 

用PHPExcel庫

下面是用PHPExcel實現的與上面功能相同的excel的方法。getCol為遞歸實現的函數,用于根據數字返回對應的列號編碼。因為導出的過程中需要指出行號,列號,行號為簡單的數字,而列號則為“A-Z”的組合,為了方便二維數組的導入,根據列數自動得到列號編碼

使用說明:

1、將后面的代碼存為excel.php,然后在頁面中調用它。

2、然后調用 xlsBOF(),將一些內容寫入到xlswritenunber() 或者 xlswritelabel()中,最后調用 xlsEOF()結束。

也可以用 fwrite 函數直接寫到服務器上,而不是用echo 僅僅在瀏覽器上顯示,下面是PHP代碼:

  1. <?php 
  2. // ----- begin of function library ----- 
  3. // Excel begin of file header 
  4. function xlsBOF() { 
  5. echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); 
  6. return
  7. // Excel end of file footer 
  8. function xlsEOF() { 
  9. echo pack("ss", 0x0A, 0x00); 
  10. return
  11. // Function to write a Number (double) into Row, Col 
  12. function xlsWriteNumber($Row$Col$Value) { 
  13. echo pack("sssss", 0x203, 14, $Row$Col, 0x0); 
  14. echo pack("d"$Value); 
  15. return
  16. // Function to write a label (text) into Row, Col 
  17. function xlsWriteLabel($Row$Col$Value ) { 
  18. $L = strlen($Value); 
  19. echo pack("ssssss", 0x204, 8 + $L$Row$Col, 0x0, $L); 
  20. echo $Value
  21. return
  22. ?> 

下面是調用代碼:

  1. <?php 
  2. header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
  3. header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT"); 
  4. header ("Cache-Control: no-cache, must-revalidate"); 
  5. header ("Pragma: no-cache"); 
  6. header ('Content-type: application/x-msexcel'); 
  7. header ("Content-Disposition: attachment; filename=EmplList.xls" ); 
  8. header ("Content-Description: PHP/INTERBASE Generated Data" ); 
  9. // 
  10. // the next lines demonstrate the generation of the Excel stream 
  11. // 
  12. include ("excel.php"); 
  13. xlsBOF();    // begin Excel stream 
  14. xlsWriteLabel(0,0,"This is a label");   // write a label in A1, use for dates too 
  15. xlsWriteNumber(0,1,9999);   // write a number B1 
  16. xlsEOF(); // close the stream 
  17. ?> 

完整實例代碼如下:

  1. <? 
  2. //設置PHPExcel類庫的include path 
  3. set_include_path('.'. PATH_SEPARATOR . 
  4.                  'D:ZealPHP_LIBS' . PATH_SEPARATOR . 
  5.                  get_include_path()); 
  6. /** 
  7.  * 以下是使用示例,對于以 //// 開頭的行是不同的可選方式,請根據實際需要 
  8.  * 打開對應行的注釋。 
  9.  * 如果使用 Excel5 ,輸出的內容應該是GBK編碼。 
  10.  */ 
  11. require_once 'PHPExcel.php'
  12. // uncomment 
  13. ////require_once 'PHPExcel/Writer/Excel5.php';    // 用于其他低版本xls 
  14. // or 
  15. ////require_once 'PHPExcel/Writer/Excel2007.php'; // 用于 excel-2007 格式 
  16. // 創建一個處理對象實例 
  17. $objExcel = new PHPExcel(); 
  18. // 創建文件格式寫入對象實例, uncomment 
  19. ////$objWriter = new PHPExcel_Writer_Excel5($objExcel);    // 用于其他版本格式 
  20. // or 
  21. ////$objWriter = new PHPExcel_Writer_Excel2007($objExcel); // 用于 2007 格式 
  22. //$objWriter->setOffice2003Compatibility(true); 
  23. //************************************* 
  24. //設置文檔基本屬性 
  25. $objProps = $objExcel->getProperties(); 
  26. $objProps->setCreator("Zeal Li"); 
  27. $objProps->setLastModifiedBy("Zeal Li"); 
  28. $objProps->setTitle("Office XLS Test Document"); 
  29. $objProps->setSubject("Office XLS Test Document, Demo"); 
  30. $objProps->setDescription("Test document, generated by PHPExcel."); 
  31. $objProps->setKeywords("office excel PHPExcel"); 
  32. $objProps->setCategory("Test"); 
  33. //************************************* 
  34. //設置當前的sheet索引,用于后續的內容操作。 
  35. //一般只有在使用多個sheet的時候才需要顯示調用。 
  36. //缺省情況下,PHPExcel會自動創建第一個sheet被設置SheetIndex=0 
  37. $objExcel->setActiveSheetIndex(0); 
  38.  
  39. $objActSheet = $objExcel->getActiveSheet(); 
  40. //設置當前活動sheet的名稱 
  41. $objActSheet->setTitle('測試Sheet'); 
  42. //************************************* 
  43. //設置單元格內容 
  44. // 
  45. //由PHPExcel根據傳入內容自動判斷單元格內容類型 
  46. $objActSheet->setCellValue('A1''字符串內容');  // 字符串內容 
  47. $objActSheet->setCellValue('A2', 26);            // 數值 
  48. $objActSheet->setCellValue('A3', true);          // 布爾值 
  49. $objActSheet->setCellValue('A4''=SUM(A2:A2)'); // 公式 
  50. //顯式指定內容類型 
  51. $objActSheet->setCellValueExplicit('A5''847475847857487584',  
  52.                                    PHPExcel_Cell_DataType::TYPE_STRING); 
  53. //合并單元格 
  54. $objActSheet->mergeCells('B1:C22'); 
  55. //分離單元格 
  56. $objActSheet->unmergeCells('B1:C22'); 
  57. //************************************* 
  58. //設置單元格樣式 
  59. // 
  60. //設置寬度 
  61. $objActSheet->getColumnDimension('B')->setAutoSize(true); 
  62. $objActSheet->getColumnDimension('A')->setWidth(30); 
  63. $objStyleA5 = $objActSheet->getStyle('A5'); 
  64. //設置單元格內容的數字格式。 
  65. // 
  66. //如果使用了 PHPExcel_Writer_Excel5 來生成內容的話, 
  67. //這里需要注意,在 PHPExcel_Style_NumberFormat 類的 const 變量定義的 
  68. //各種自定義格式化方式中,其它類型都可以正常使用,但當setFormatCode 
  69. //為 FORMAT_NUMBER 的時候,實際出來的效果被沒有把格式設置為"0"。需要 
  70. //修改 PHPExcel_Writer_Excel5_Format 類源代碼中的 getXf($style) 方法, 
  71. //在 if ($this->_BIFF_version == 0x0500) { (第363行附近)前面增加一 
  72. //行代碼:  
  73. //if($ifmt === '0') $ifmt = 1; 
  74. // 
  75. //設置格式為PHPExcel_Style_NumberFormat::FORMAT_NUMBER,避免某些大數字 
  76. //被使用科學記數方式顯示,配合下面的 setAutoSize 方法可以讓每一行的內容 
  77. //都按原始內容全部顯示出來。 
  78. $objStyleA5 
  79.     ->getNumberFormat() 
  80.     ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER); 
  81. //設置字體 
  82. $objFontA5 = $objStyleA5->getFont(); 
  83. $objFontA5->setName('Courier New'); 
  84. $objFontA5->setSize(10); 
  85. $objFontA5->setBold(true); 
  86. $objFontA5->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); 
  87. $objFontA5->getColor()->setARGB('FF999999'); 
  88. //設置對齊方式 
  89. $objAlignA5 = $objStyleA5->getAlignment(); 
  90. $objAlignA5->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
  91. $objAlignA5->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); 
  92. //設置邊框 
  93. $objBorderA5 = $objStyleA5->getBorders(); 
  94. $objBorderA5->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 
  95. $objBorderA5->getTop()->getColor()->setARGB('FFFF0000'); // color 
  96. $objBorderA5->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 
  97. $objBorderA5->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 
  98. $objBorderA5->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 
  99. //設置填充顏色 
  100. $objFillA5 = $objStyleA5->getFill(); 
  101. $objFillA5->setFillType(PHPExcel_Style_Fill::FILL_SOLID); 
  102. $objFillA5->getStartColor()->setARGB('FFEEEEEE'); 
  103. //從指定的單元格復制樣式信息. 
  104. $objActSheet->duplicateStyle($objStyleA5'B1:C22'); 
  105.  
  106. //************************************* 
  107. //添加圖片 
  108. $objDrawing = new PHPExcel_Worksheet_Drawing(); 
  109. $objDrawing->setName('ZealImg'); 
  110. $objDrawing->setDescription('Image inserted by Zeal'); 
  111. $objDrawing->setPath('./zeali.net.logo.gif'); 
  112. $objDrawing->setHeight(36); 
  113. $objDrawing->setCoordinates('C23'); 
  114. $objDrawing->setOffsetX(10); 
  115. $objDrawing->setRotation(15); 
  116. $objDrawing->getShadow()->setVisible(true); 
  117. $objDrawing->getShadow()->setDirection(36); 
  118. $objDrawing->setWorksheet($objActSheet); 
  119.  
  120. //添加一個新的worksheet 
  121. $objExcel->createSheet(); 
  122. $objExcel->getSheet(1)->setTitle('測試2'); 
  123. //保護單元格 
  124. $objExcel->getSheet(1)->getProtection()->setSheet(true); 
  125. $objExcel->getSheet(1)->protectCells('A1:C22''PHPExcel'); 
  126.  
  127. //************************************* 
  128. //輸出內容 
  129. // 
  130. $outputFileName = "output.xls"
  131. //到文件 
  132. ////$objWriter->save($outputFileName); 
  133. //or 
  134. //到瀏覽器 
  135. ////header("Content-Type: application/force-download"); 
  136. ////header("Content-Type: application/octet-stream"); 
  137. ////header("Content-Type: application/download"); 
  138. ////header('Content-Disposition:inline;filename="'.$outputFileName.'"'); 
  139. ////header("Content-Transfer-Encoding: binary"); 
  140. ////header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
  141. ////header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
  142. ////header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
  143. ////header("Pragma: no-cache"); 
  144. ////$objWriter->save('php://output'); 
  145. ?>

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 三都| 巴马| 威信县| 盐津县| 漳浦县| 那坡县| 固安县| 涡阳县| 青州市| 阿克苏市| 土默特右旗| 金湖县| 陵川县| 腾冲县| 安庆市| 金山区| 敦煌市| 神农架林区| 山东省| 迭部县| 西乌| 泌阳县| 全州县| 田林县| 南通市| 靖安县| 兖州市| 陆河县| 团风县| 武城县| 云和县| 定州市| 黄大仙区| 天全县| 湛江市| 科技| 芷江| 酒泉市| 东山县| 民和| 合川市|