首先到phpexcel官網上下載最新的phpexcel類,下週解壓縮一個classes文件夾,裏面包含了PHPExcel.php和PHPExcel的文件夾,這個類文件和文件夾是咱們須要的,把classes解壓到你項目的一個目錄中,重名名爲phpexcel,開始嘍,(代碼都摘自自帶實例) 程序部分 require_once './phpexcel/PHPExcel.php'; //首先建立一個新的對象 PHPExcelobject $objPHPExcel = new PHPExcel(); //設置文件的一些屬性,在xls文件——>屬性——>詳細信息裏能夠看到這些值,xml表格裏是沒有這些值的 $objPHPExcel ->getProperties() //得到文件屬性對象,給下文提供設置資源 ->setCreator( "MaartenBalliauw") //設置文件的建立者 ->setLastModifiedBy( "MaartenBalliauw") //設置最後修改者 ->setTitle( "Office2007 XLSX Test Document" ) //設置標題 ->setSubject( "Office2007 XLSX Test Document" ) //設置主題 ->setDescription( "Test document for Office2007 XLSX, generated using PHP classes.") //設置備註 ->setKeywords( "office 2007 openxmlphp") //設置標記 ->setCategory( "Test resultfile"); //設置類別 // 位置aaa *爲下文代碼位置提供錨 //給表格添加數據 $objPHPExcel->setActiveSheetIndex(0) //設置第一個內置表(一個xls文件裏能夠有多個表)爲活動的 ->setCellValue( 'A1', 'Hello' ) //給表的單元格設置數據 ->setCellValue( 'B2', 'world!' ) //數據格式能夠爲字符串 ->setCellValue( 'C1',12) //數字型 ->setCellValue( 'D2',12) // ->setCellValue( 'D3', true ) //布爾型 ->setCellValue( 'D4', '=SUM(C1:D2)' );//公式 //獲得當前活動的表,注意下文教程中會常常用到$objActSheet $objActSheet =$objPHPExcel->getActiveSheet(); // 位置bbb *爲下文代碼位置提供錨 //給當前活動的表設置名稱 $objActSheet->setTitle('Simple2222'); 代碼尚未結束,能夠複製下面的代碼來決定咱們將要作什麼 咱們將要作的是 1,直接生成一個文件 $objWriter =PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('myexchel.xlsx'); 二、提示下載文件 excel 2003 .xls //生成2003excel格式的xls文件 header('Content-Type:application/vnd.ms-excel'); header('Content-Disposition:attachment;filename="01simple.xls"'); header('Cache-Control:max-age=0'); $objWriter =PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; excel 2007 .xlsx //生成2007excel格式的xlsx文件 header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition:attachment;filename="01simple.xlsx"'); header('Cache-Control:max-age=0'); $objWriter =PHPExcel_IOFactory:: createWriter($objPHPExcel, 'Excel2007'); $objWriter->save( 'php://output'); exit; pdf 文件 // 下載一個pdf文件 header('Content-Type:application/pdf'); header('Content-Disposition:attachment;filename="01simple.pdf"'); header('Cache-Control:max-age=0'); $objWriter =PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF'); $objWriter->save('php://output'); exit; // 生成一個pdf文件 $objWriter =PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF'); $objWriter->save('a.pdf'); CSV文件 $objWriter =PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV')->setDelimiter(',' ) //設置分隔符 ->setEnclosure('"' ) //設置包圍符 ->setLineEnding("\r\n" )//設置行分隔符 ->setSheetIndex(0) //設置活動表 ->save(str_replace('.php' , '.csv' ,__FILE__)); HTML文件 $objWriter =PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML'); //將$objPHPEcel對象轉換成html格式的 $objWriter->setSheetIndex(0); //設置活動表 //$objWriter->setImagesRoot('http://www.example.com'); $objWriter->save(str_replace('.php', '.htm',__FILE__)); //保存文件 設置表格樣式和數據格式 設置默認的字體和文字大小 錨:aaa $objPHPExcel->getDefaultStyle()->getFont()->setName( 'Arial'); $objPHPExcel->getDefaultStyle()->getFont()->setSize(20); 日期格式 錨:bbb //得到秒值變量 $dateTimeNow = time(); //三個表格分別設置爲當前實際的日期格式、時間格式、日期和時間格式 //首先將單元格的值設置爲由PHPExcel_Shared_Date::PHPToExcel方法轉換後的excel格式的值,而後用過獲得該單元格的樣式裏面數字樣式再設置顯示格式 $objActSheet->setCellValue( 'C9', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow)); $objActSheet->getStyle( 'C9')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2); $objActSheet->setCellValue( 'C10', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow)); $objActSheet->getStyle( 'C10')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4); $objActSheet->setCellValue( 'C10', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow )); $objActSheet->getStyle( 'C10')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4); //將E4到E13的數字格式設置爲EUR $objPHPExcel->getActiveSheet()->getStyle( 'E4:E13')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE); 設置列的寬度 錨:bbb $objActSheet->getColumnDimension( 'B')->setAutoSize(true); //內容自適應 $objActSheet->getColumnDimension( 'A')->setWidth(30); //30寬 設置文件打印的頁眉和頁腳 錨:bbb //設置打印時候的頁眉頁腳(設置完了之後能夠經過打印預覽來看效果)字符串中的&*好像是一些變量 $objActSheet->getHeaderFooter()->setOddHeader( '&L&G&C&HPlease treat thisdocument as confidential!'); $objActSheet->getHeaderFooter()->setOddFooter( '&L&B' .$objPHPExcel->getProperties()->getTitle(). '&RPage &P of&N' ); 設置頁面文字的方向和頁面大小 錨:bbb $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup:: ORIENTATION_LANDSCAPE); $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup:: PAPERSIZE_A4); //A4紙大小 爲頁眉添加圖片 office中有效 wps中無效 錨:bbb $objDrawing = new PHPExcel_Worksheet_HeaderFooterDrawing(); $objDrawing->setName('PHPExcellogo'); $objDrawing->setPath('./images/phpexcel_logo.gif'); $objDrawing->setHeight(36); $objPHPExcel->getActiveSheet()->getHeaderFooter()->addImage($objDrawing,PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT ); 設置單元格的批註 錨:bbb //給單元格添加批註 $objPHPExcel->getActiveSheet()->getComment( 'E13')->setAuthor('PHPExcel' ); //設置做者 $objCommentRichText =$objPHPExcel->getActiveSheet()->getComment('E13' )->getText()->createTextRun('PHPExcel:'); //添加批註 $objCommentRichText->getFont()->setBold( true); //將現有批註加粗 $objPHPExcel->getActiveSheet()->getComment( 'E13')->getText()->createTextRun("\r\n" ); //添加更多批註 $objPHPExcel->getActiveSheet()->getComment( 'E13')->getText()->createTextRun('Total amount on the currentinvoice, includingVAT.' ); $objPHPExcel->getActiveSheet()->getComment( 'E13')->setWidth('100pt' ); //設置批註顯示的寬高,在office中有效在wps中無效 $objPHPExcel->getActiveSheet()->getComment( 'E13')->setHeight('100pt' ); $objPHPExcel->getActiveSheet()->getComment( 'E13')->setMarginLeft('150pt' ); $objPHPExcel->getActiveSheet()->getComment( 'E13')->getFillColor()->setRGB('EEEEEE' ); //設置背景色,在office中有效在wps中無效 添加文字塊 看效果圖 office中有效wps中無效 錨:bbb //大概翻譯 建立一個富文本框 office有效 wps無效 $objRichText= new PHPExcel_RichText(); $objRichText->createText('This invoice is'); //寫文字 //添加文字並設置這段文字粗體斜體和文字顏色 $objPayable =$objRichText->createTextRun( 'payable within thirty daysafter the end of the month'); $objPayable->getFont()->setBold( true); $objPayable->getFont()->setItalic( true); $objPayable->getFont()->setColor( new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_DARKGREEN )); $objRichText->createText(', unless specifiedotherwise on the invoice.'); //將文字寫到A18單元格中 $objPHPExcel->getActiveSheet()->getCell( 'A18')->setValue($objRichText); PHPExcel <wbr><wbr>學習筆記 合併拆分單元格 錨:bbb $objPHPExcel->getActiveSheet()->mergeCells( 'A28:B28'); //A28:B28合併 $objPHPExcel->getActiveSheet()->unmergeCells( 'A28:B28'); //A28:B28再拆分 單元格密碼保護 錨:bbb // 單元格密碼保護不讓修改 $objPHPExcel->getActiveSheet()->getProtection()->setSheet( true); //爲了使任何表保護,需設置爲真 $objPHPExcel->getActiveSheet()->protectCells( 'A3:E13', 'PHPExcel' ); //將A3到E13保護 加密密碼是PHPExcel $objPHPExcel->getActiveSheet()->getStyle( 'B1')->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); //去掉保護 設置單元格字體 錨:bbb //將B1的文字字體設置爲Candara,20號的粗體下劃線有背景色 $objPHPExcel->getActiveSheet()->getStyle( 'B1')->getFont()->setName('Candara' ); $objPHPExcel->getActiveSheet()->getStyle( 'B1')->getFont()->setSize(20); $objPHPExcel->getActiveSheet()->getStyle( 'B1')->getFont()->setBold(true); $objPHPExcel->getActiveSheet()->getStyle( 'B1')->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); $objPHPExcel->getActiveSheet()->getStyle( 'B1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE); 文字對齊方式 錨:bbb $objPHPExcel->getActiveSheet()->getStyle( 'D11')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //水平方向上對齊 $objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);//水平方向上兩端對齊 $objPHPExcel->getActiveSheet()->getStyle( 'A18')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直方向上中間居中 設置單元格邊框 錨:bbb $styleThinBlackBorderOutline= array( 'borders' => array ( 'outline' => array ( 'style' =>PHPExcel_Style_Border::BORDER_THIN, //設置border樣式 //'style' =>PHPExcel_Style_Border::BORDER_THICK, 另外一種樣式 'color' => array ('argb' => 'FF000000'), //設置border顏色 ), ), ); $objPHPExcel->getActiveSheet()->getStyle( 'A4:E10')->applyFromArray($styleThinBlackBorderOutline); 背景填充顏色 錨:bbb //設置填充的樣式和背景色 $objPHPExcel->getActiveSheet()->getStyle( 'A1:E1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID); $objPHPExcel->getActiveSheet()->getStyle( 'A1:E1')->getFill()->getStartColor()->setARGB('FF808080'); 綜合設置樣例 $objPHPExcel->getActiveSheet()->getStyle( 'A3:E3')->applyFromArray( array( 'font' => array ( 'bold' => true ), 'alignment' => array ( 'horizontal' =>PHPExcel_Style_Alignment::HORIZONTAL_RIGHT , ), 'borders' => array ( 'top' => array ( 'style' =>PHPExcel_Style_Border::BORDER_THIN ) ), 'fill' => array ( 'type' =>PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR , 'rotation' =>90, 'startcolor' => array ( 'argb' => 'FFA0A0A0' ), 'endcolor' => array ( 'argb' => 'FFFFFFFF' ) ) ) ); PHPExcel <wbr><wbr>學習筆記 給單元格內容設置url超連接 錨:bbb $objActSheet->getCell('E26')->getHyperlink()->setUrl( 'http://www.phpexcel.net'); //超連接url地址 $objActSheet->getCell('E26')->getHyperlink()->setTooltip( 'Navigate towebsite'); //鼠標移上去鏈接提示信息 給表中添加圖片 錨:bbb $objDrawing= new PHPExcel_Worksheet_Drawing(); $objDrawing->setName('Paid'); $objDrawing->setDescription('Paid'); $objDrawing->setPath('./images/paid.png'); //圖片引入位置 $objDrawing->setCoordinates('B15'); //圖片添加位置 $objDrawing->setOffsetX(210); $objDrawing->setRotation(25); $objDrawing->setHeight(36); $objDrawing->getShadow()->setVisible (true ); $objDrawing->getShadow()->setDirection(45); $objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); //還能夠添加有gd庫生產的圖片,詳細見自帶實例25 建立一個新工做表和設置工做表標籤顏色 錨:bbb $objExcel->createSheet(); $objPHPExcel->setActiveSheetIndex(1); //設置第2個表爲活動表,提供操做句柄 $objExcel->getSheet(1)->setTitle( '測試2'); //直接獲得第二個表進行設置,將工做表從新命名爲測試2 $objPHPExcel->getActiveSheet()->getTabColor()->setARGB( 'FF0094FF'); //設置標籤顏色 添加或刪除行和列 錨:bbb $objPHPExcel->getActiveSheet()->insertNewRowBefore(6,10); //在行6前添加10行 $objPHPExcel->getActiveSheet()->removeRow(6,10); //從第6行日後刪去10行 $objPHPExcel->getActiveSheet()->insertNewColumnBefore( 'E', 5); //從第E列前添加5類 $objPHPExcel->getActiveSheet()->removeColumn( 'E',5); //從E列開始日後刪去5列 隱藏和顯示某列 錨:bbb $objPHPExcel->getActiveSheet()->getColumnDimension( 'C')->setVisible(false); //隱藏 $objPHPExcel->getActiveSheet()->getColumnDimension( 'D')->setVisible(true); //顯示 從新命名活動的表的標籤名稱 錨:bbb $objPHPExcel->getActiveSheet()->setTitle( 'Invoice'); 設置工做表的安全 $objPHPExcel->getActiveSheet()->getProtection()->setPassword( 'PHPExcel'); $objPHPExcel->getActiveSheet()->getProtection()->setSheet( true); // This should be enabled inorder to enable any of thefollowing! $objPHPExcel->getActiveSheet()->getProtection()->setSort( true); $objPHPExcel->getActiveSheet()->getProtection()->setInsertRows( true); $objPHPExcel->getActiveSheet()->getProtection()->setFormatCells( true); 設置文檔安全 錨:bbb $objPHPExcel->getSecurity()->setLockWindows( true); $objPHPExcel->getSecurity()->setLockStructure( true); $objPHPExcel->getSecurity()->setWorkbookPassword( "PHPExcel"); //設置密碼 樣式複製 錨:bbb //將B2的樣式複製到B3至B7 $objPHPExcel->getActiveSheet()->duplicateConditionalStyle( $objPHPExcel->getActiveSheet()->getStyle( 'B2')->getConditionalStyles(), 'B3:B7' ); Add conditionalformatting 錨:bbb echo date('H:i:s' ), " Add conditionalformatting" ,PHP_EOL; $objConditional1= new PHPExcel_Style_Conditional (); $objConditional1->setConditionType(PHPExcel_Style_Conditional ::CONDITION_CELLIS ); $objConditional1->setOperatorType(PHPExcel_Style_Conditional ::OPERATOR_BETWEEN ); $objConditional1->addCondition('200'); $objConditional1->addCondition('400'); 設置分頁(主要用於打印) 錨:bbb //設置某單元格爲頁尾 $objPHPExcel->getActiveSheet()->setBreak( 'A' .$i, PHPExcel_Worksheet::BREAK_ROW ); 用數組填充表 錨:bbb //吧數組的內容從A2開始填充 $dataArray= array( array("2010" , "Q1", "UnitedStates", 790), array("2010" , "Q2", "UnitedStates", 730), ); $objPHPExcel->getActiveSheet()->fromArray($dataArray, NULL, 'A2'); 設置自動篩選 錨:bbb $objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension()); //$objPHPExcel->getActiveSheet()->calculateWorksheetDimension()....獲得A1行的全部內容個 打印出的到全部的公式 $objCalc =PHPExcel_Calculation::getInstance(); print_r($objCalc->listFunctionNames()) 設置單元格值的範圍 錨:bbb $objValidation =$objPHPExcel->getActiveSheet()->getCell('B3' )->getDataValidation(); $objValidation->setType(PHPExcel_Cell_DataValidation:: TYPE_WHOLE ); $objValidation->setErrorStyle(PHPExcel_Cell_DataValidation:: STYLE_STOP ); $objValidation->setAllowBlank(true); $objValidation->setShowInputMessage( true); //設置顯示提示信息 $objValidation->setShowErrorMessage( true); //設置顯示錯誤信息 $objValidation->setErrorTitle('Inputerror'); //錯誤標題 //$objValidation->setShowDropDown(true); $objValidation->setError('Only numbers between 10 and20 are allowed!'); //錯誤內容 $objValidation->setPromptTitle('Allowedinput'); //設置提示標題 $objValidation->setPrompt('Only numbers between 10 and20 are allowed.'); //提示內容 $objValidation->setFormula1(10); //設置最大值 $objValidation->setFormula2(120); //設置最小值 //或者這樣設置 $objValidation->setFormula2(1,5,6,7); 設置值是1,5,6,7中的一個數 其餘 $objPHPExcel->getActiveSheet()->getStyle( 'B5')->getAlignment()->setShrinkToFit(true); //長度不夠顯示的時候是否自動換行 $objPHPExcel->getActiveSheet()->getStyle( 'B5')->getAlignment()->setShrinkToFit(true); //自動轉換顯示字體大小,使內容可以顯示 $objPHPExcel->getActiveSheet()->getCell(B14)->getValue(); //得到值,有可能獲得的是公式 $objPHPExcel->getActiveSheet()->getCell(B14)->getCalculatedValue();//得到算出的值 導入或讀取文件 //經過PHPExcel_IOFactory::load方法來載入一個文件,load會自動判斷文件的後綴名來導入相應的處理類,讀取格式保含xlsx/xls/xlsm/ods/slk/csv/xml/gnumeric require_once '../Classes/PHPExcel/IOFactory.php'; $objPHPExcel =PHPExcel_IOFactory::load( //吧載入的文件默認表(通常都是第一個)經過toArray方法來返回一個多維數組 $dataArray =$objPHPExcel->getActiveSheet()->toArray(); //讀完直接寫到一個xlsx文件裏 $objWriter =PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); //$objPHPExcel是上文中讀的資源 $objWriter->save(str_replace('.php', '.xlsx', __FILE__)); 讀取xml文件 $objReader =PHPExcel_IOFactory:: createReader('Excel2003XML' ); $objPHPExcel =$objReader->load( "Excel2003XMLTest.xml" ); 讀取ods文件 $objReader =PHPExcel_IOFactory:: createReader('OOCalc' ); $objPHPExcel= $objReader->load("OOCalcTest.ods" ); 讀取numeric文件 $objReader =PHPExcel_IOFactory:: createReader('Gnumeric' ); $objPHPExcel =$objReader->load( "GnumericTest.gnumeric" ); 讀取slk文件 $objPHPExcel =PHPExcel_IOFactory:: load("SylkTest.slk" ); 循環遍歷數據 $objReader =PHPExcel_IOFactory::createReader('Excel2007' ); //建立一個2007的讀取對象 $objPHPExcel =$objReader->load ("05featuredemo.xlsx" ); //讀取一個xlsx文件 foreach ($objPHPExcel->getWorksheetIterator() as $worksheet){ //遍歷工做表 echo 'Worksheet -' ,$worksheet->getTitle() , PHP_EOL; foreach ($worksheet->getRowIterator() as $row){ //遍歷行 echo ' Row number -' ,$row->getRowIndex() , PHP_EOL; $cellIterator=$row->getCellIterator(); //獲得全部列 $cellIterator->setIterateOnlyExistingCells( false); // Loopall cells, even if it is not set foreach ($cellIterator as $cell){ //遍歷列 if (!is_null($cell)){ //若是列不給空就獲得它的座標和計算的值 echo ' Cell -' ,$cell->getCoordinate(), ' -' ,$cell->getCalculatedValue() , PHP_EOL; } } } } 吧數組插入的表中 //插入的數據3行數據 $data= array( array('title' => 'Excel fordummies', 'price' =>17.99, 'quantity' =>2 ), array('title' => 'PHP fordummies', 'price' => 15.99, 'quantity' =>1 ), array('title' => 'InsideOOP', 'price' => 12.95, 'quantity' =>1 ) ); $baseRow=5; //指定插入到第5行後 foreach($data as $r => $dataRow){ $row= $baseRow +$r; //$row是循環操做行的行號 $objPHPExcel->getActiveSheet()->insertNewRowBefore($row,1); //在操做行的號前加一空行,這空行的行號就變成了當前的行號 //對應的咧都附上數據和編號 $objPHPExcel->getActiveSheet()->setCellValue( 'A'.$row,$r+1); $objPHPExcel->getActiveSheet()->setCellValue( 'B'.$row,$dataRow['title']); $objPHPExcel->getActiveSheet()->setCellValue( 'C'.$row,$dataRow['price']); $objPHPExcel->getActiveSheet()->setCellValue( 'D'.$row,$dataRow['quantity']); $objPHPExcel->getActiveSheet()->setCellValue( 'E'.$row, '=C'.$row.'*D' .$row); } $objPHPExcel->getActiveSheet()->removeRow($baseRow-1,1); //最後刪去第4行,這是示例須要,在此處爲你們提供刪除實例