php寫excel檔案的實現代碼

來源:互聯網
上載者:User
本文介紹下,用php實現寫excel檔案的代碼,包括標題與內容等。有需要的朋友參考下。

php寫excel檔案,包括標題。這在日常的開發中經常用到,比如一些連絡人名單、公司通訊錄的操作,都會用到php操作excel檔案的功能。

代碼:

setActiveSheetIndex(0); //設定活動頁面              $activeSheet = $objPHPExcel->getActiveSheet(); //擷取當前活動頁面              $activeSheet->getDefaultColumnDimension()->setWidth(16); //設定列寬16              $activeSheet->setTitle("連絡人"); //設定sheet的名稱                            //設定標題,儲存格第一列為0,第一行為1              $colNum = count($titles);              for($i = 0; $i < $colNum; $i++){                  $activeSheet->getStyleByColumnAndRow($i, 1)->getFont()->setBold(true); //設定標題加粗                  $activeSheet->setCellValueByColumnAndRow($i, 1, $titles[$i]);              }                            //設定 body,row從2開始,第一行已經被設定為標題了              $rowNum = count($elements);              for($row = 0; $row < $rowNum; $row++){      for($col = 0; $col < $colNum; $col++){        $activeSheet->getStyle($this->numToEn($col).($row+2))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);        $activeSheet->setCellValue($this->numToEn($col).($row+2)," ".$elements[$row][$col]);  //在寫入Excels儲存格的內容之前加一個空格,防止長數字被轉化成科學計數法        $activeSheet->getStyle($this->numToEn($col).($row+2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);        }   }                //擷取儲存檔案名稱   $filetype = $this->getFileType($filename);  //根據檔案類型讀取excel檔案  ob_end_clean();   $objWriter = null;  if ($filetype == "xlsx") {    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');    header('Content-Disposition: attachment;filename='.urlencode($filename));    header('Cache-Control: max-age=0');   ob_end_clean();    $objWriter->save('php://output');     $objPHPExcel->disconnectWorksheets();      unset($objPHPExcel);                  exit;              } elseif ($filetype == "xls") {                  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');                  header('Content-Type: application/vnd.ms-excel');                  header('Content-Disposition: attachment;filename='.urlencode($filename));                  header('Cache-Control: max-age=0');                                  ob_end_clean();                  $objWriter->save('php://output');                  $objPHPExcel->disconnectWorksheets();                  unset($objPHPExcel);                  exit;              } else {                  return false;              }          } catch (Exception $e) {               HWS::logErr('EXCEL ERROR:'.$e->getMessage());               $errText = "建立錯誤檔案失敗,請聯絡管理員,稍後再試!";               return array('createFileErr'=>$errText);          }      }    /**      * 擷取檔案類型      * @param $filenamePath 檔案路徑或者檔案名稱      */      private function getFileType($filenamePath){          if (!$filenamePath){              return false;          }          $filenameArr = explode('/', $filenamePath);          $count = count($filenameArr);          $filename = $filenameArr[$count-1];                    $filetypeArr = explode('.', $filename);          $count = count($filetypeArr);          $filetype = $filetypeArr[$count-1];          return $filetype;         }            /**     根據給定的數字產生至多兩位對應EXCEL檔案列的字母     */      private function numToEn($num)      {          $asc = 0;          $en = "";          $num =(int)$num+1;          if($num<26)                      //判斷指定的數字是否需要用兩個字母表示          {              if((int)$num<10)              {                  $asc = ord($num);                  $en =chr($asc+16);              }              else              {                  $num_g = substr($num,1,1);                  $num_s = substr($num,0,1);                  $asc = ord($num_g);                  $en =chr($asc+16+10*$num_s);              }          }          else          {              $num_complementation = floor($num/26);              $en_q = $this->numToEn($num_complementation);              $en_h = $num%26 != 0 ? $this->numToEn($num-$num_complementation*26):"A";              $en = $en_q.$en_h;          }          return $en;      }

代碼說明:exportFileContacts方法中的兩個ob_end_clean();$objPHPExcel->disconnectWorksheets();unset($objPHPExcel);是為了清除緩衝區內容,防止匯出的excel出錯,打不開,報格式化錯誤。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.