首页 > 代码库 > PHP操作Excel – PHPExcel 基本用法

PHP操作Excel – PHPExcel 基本用法

1.header

[php] 

  1. header("Content-Type:application/vnd.ms-excel");  
  2. header("Content-Disposition:attachment;filename=sample.xls");  
  3. header("Pragma:no-cache");  
  4. header("Expires:0");  

2.PHPExcel

http://www.codeplex.com/PHPExcel
http://www.phpexcel.net
开发包Tests目录有详细使用实例  支持中文,注意文件编码   文件保存为utf-8

excel

[php] 

  1. //Include class  
  2. require_once(‘Classes/PHPExcel.php‘);  
  3. require_once(‘Classes/PHPExcel/Writer/Excel2007.php‘);  
  4. $objPHPExcel = new PHPExcel();  
  5. //Set properties 设置文件属性  
  6. $objPHPExcel->getProperties()->setCreator("Maarten Balliauw");  
  7. $objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");  
  8. $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");  
  9. $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");  
  10. $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");  
  11. $objPHPExcel->getProperties()->setKeywords("office 2007 openxml php");  
  12. $objPHPExcel->getProperties()->setCategory("Test result file");  
  13. //Add some data 添加数据  
  14. $objPHPExcel->setActiveSheetIndex(0);  
  15. $objPHPExcel->getActiveSheet()->setCellValue(‘A1‘, ‘Hello‘);//可以指定位置  
  16. $objPHPExcel->getActiveSheet()->setCellValue(‘A2‘, true);  
  17. $objPHPExcel->getActiveSheet()->setCellValue(‘A3‘, false);  
  18. $objPHPExcel->getActiveSheet()->setCellValue(‘B2‘, ‘world!‘);  
  19. $objPHPExcel->getActiveSheet()->setCellValue(‘B3‘, 2);  
  20. $objPHPExcel->getActiveSheet()->setCellValue(‘C1‘, ‘Hello‘);  
  21. $objPHPExcel->getActiveSheet()->setCellValue(‘D2‘, ‘world!‘);  
  22. //循环  
  23. for($i = 1;$i<200;$i++) {  
  24. $objPHPExcel->getActiveSheet()->setCellValue(‘A‘ . $i, $i);  
  25. $objPHPExcel->getActiveSheet()->setCellValue(‘B‘ . $i, ‘Test value‘);  
  26. }  
  27. //日期格式化  
  28. $objPHPExcel->getActiveSheet()->setCellValue(‘D1‘, time());  
  29. $objPHPExcel->getActiveSheet()->getStyle(‘D1‘)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);  
  30. //Add comment 添加注释  
  31. $objPHPExcel->getActiveSheet()->getComment(‘E11‘)->setAuthor(‘PHPExcel‘);  
  32. $objCommentRichText = $objPHPExcel->getActiveSheet()->getComment(‘E11‘)->getText()->createTextRun(‘PHPExcel:‘);  
  33. $objCommentRichText->getFont()->setBold(true);  
  34. $objPHPExcel->getActiveSheet()->getComment(‘E11‘)->getText()->createTextRun("\r\n");  
  35. $objPHPExcel->getActiveSheet()->getComment(‘E11‘)->getText()->createTextRun(‘Total amount on the current invoice, excluding VAT.‘);  
  36. //Add rich-text string 添加文字 可设置样式  
  37. $objRichText = new PHPExcel_RichText( $objPHPExcel->getActiveSheet()->getCell(‘A18‘) );  
  38. $objRichText->createText(‘This invoice is ‘);  
  39. $objPayable = $objRichText->createTextRun(‘payable within thirty days after the end of the month‘);  
  40. $objPayable->getFont()->setBold(true);  
  41. $objPayable->getFont()->setItalic(true);  
  42. $objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );  
  43. $objRichText->createText(‘, unless specified otherwise on the invoice.‘);  
  44. //Merge cells 合并分离单元格  
  45. $objPHPExcel->getActiveSheet()->mergeCells(‘A18:E22‘);  
  46. $objPHPExcel->getActiveSheet()->unmergeCells(‘A18:E22‘);  
  47. //Protect cells 保护单元格  
  48. $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);//Needs to be set to true in order to enable any worksheet protection!  
  49. $objPHPExcel->getActiveSheet()->protectCells(‘A3:E13‘, ‘PHPExcel‘);  
  50. //Set cell number formats 数字格式化  
  51. $objPHPExcel->getActiveSheet()->getStyle(‘E4‘)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);  
  52. $objPHPExcel->getActiveSheet()->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle(‘E4‘), ‘E5:E13‘ );  
  53. //Set column widths 设置列宽度  
  54. $objPHPExcel->getActiveSheet()->getColumnDimension(‘B‘)->setAutoSize(true);  
  55. $objPHPExcel->getActiveSheet()->getColumnDimension(‘D‘)->setWidth(12);  
  56. //Set fonts 设置字体  
  57. $objPHPExcel->getActiveSheet()->getStyle(‘B1‘)->getFont()->setName(‘Candara‘);  
  58. $objPHPExcel->getActiveSheet()->getStyle(‘B1‘)->getFont()->setSize(20);  
  59. $objPHPExcel->getActiveSheet()->getStyle(‘B1‘)->getFont()->setBold(true);  
  60. $objPHPExcel->getActiveSheet()->getStyle(‘B1‘)->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);  
  61. $objPHPExcel->getActiveSheet()->getStyle(‘B1‘)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);  
  62. //Set alignments 设置对齐  
  63. $objPHPExcel->getActiveSheet()->getStyle(‘D11‘)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);  
  64. $objPHPExcel->getActiveSheet()->getStyle(‘A18‘)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);  
  65. $objPHPExcel->getActiveSheet()->getStyle(‘A18‘)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);  
  66. $objPHPExcel->getActiveSheet()->getStyle(‘A3‘)->getAlignment()->setWrapText(true);  
  67. //Set column borders 设置列边框  
  68. $objPHPExcel->getActiveSheet()->getStyle(‘A4‘)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);  
  69. $objPHPExcel->getActiveSheet()->getStyle(‘A10‘)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);  
  70. $objPHPExcel->getActiveSheet()->getStyle(‘E10‘)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);  
  71. $objPHPExcel->getActiveSheet()->getStyle(‘D13‘)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);  
  72. $objPHPExcel->getActiveSheet()->getStyle(‘E13‘)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);  
  73. //Set border colors 设置边框颜色  
  74. $objPHPExcel->getActiveSheet()->getStyle(‘D13‘)->getBorders()->getLeft()->getColor()->setARGB(‘FF993300‘);  
  75. $objPHPExcel->getActiveSheet()->getStyle(‘D13‘)->getBorders()->getTop()->getColor()->setARGB(‘FF993300‘);  
  76. $objPHPExcel->getActiveSheet()->getStyle(‘D13‘)->getBorders()->getBottom()->getColor()->setARGB(‘FF993300‘);  
  77. $objPHPExcel->getActiveSheet()->getStyle(‘E13‘)->getBorders()->getRight()->getColor()->setARGB(‘FF993300‘);  
  78. //Set fills 设置填充  
  79. $objPHPExcel->getActiveSheet()->getStyle(‘A1‘)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);  
  80. $objPHPExcel->getActiveSheet()->getStyle(‘A1‘)->getFill()->getStartColor()->setARGB(‘FF808080‘);  
  81. //Add a hyperlink to the sheet 添加链接  
  82. $objPHPExcel->getActiveSheet()->setCellValue(‘E26‘, ‘www.phpexcel.net‘);  
  83. $objPHPExcel->getActiveSheet()->getCell(‘E26‘)->getHyperlink()->setUrl(‘http://www.phpexcel.net‘);  
  84. $objPHPExcel->getActiveSheet()->getCell(‘E26‘)->getHyperlink()->setTooltip(‘Navigate to website‘);  
  85. $objPHPExcel->getActiveSheet()->getStyle(‘E26‘)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);  
  86. //Add a drawing to the worksheet 添加图片  
  87. $objDrawing = new PHPExcel_Worksheet_Drawing();  
  88. $objDrawing->setName(‘Logo‘);  
  89. $objDrawing->setDescription(‘Logo‘);  
  90. $objDrawing->setPath(‘./images/officelogo.jpg‘);  
  91. $objDrawing->setHeight(36);  
  92. $objDrawing->setCoordinates(‘B15‘);  
  93. $objDrawing->setOffsetX(110);  
  94. $objDrawing->setRotation(25);  
  95. $objDrawing->getShadow()->setVisible(true);  
  96. $objDrawing->getShadow()->setDirection(45);  
  97. $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());  
  98. //Play around with inserting and removing rows and columns  
  99. $objPHPExcel->getActiveSheet()->insertNewRowBefore(6, 10);  
  100. $objPHPExcel->getActiveSheet()->removeRow(6, 10);  
  101. $objPHPExcel->getActiveSheet()->insertNewColumnBefore(‘E‘, 5);  
  102. $objPHPExcel->getActiveSheet()->removeColumn(‘E‘, 5);  
  103. //Add conditional formatting  
  104. $objConditional1 = new PHPExcel_Style_Conditional();  
  105. $objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);  
  106. $objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN);  
  107. $objConditional1->setCondition(‘0‘);  
  108. $objConditional1->getStyle()->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED);  
  109. $objConditional1->getStyle()->getFont()->setBold(true);  
  110. //Set autofilter 自动过滤  
  111. $objPHPExcel->getActiveSheet()->setAutoFilter(‘A1:C9‘);  
  112. //Hide "Phone" and "fax" column 隐藏列  
  113. $objPHPExcel->getActiveSheet()->getColumnDimension(‘C‘)->setVisible(false);  
  114. $objPHPExcel->getActiveSheet()->getColumnDimension(‘D‘)->setVisible(false);  
  115. //Set document security 设置文档安全  
  116. $objPHPExcel->getSecurity()->setLockWindows(true);  
  117. $objPHPExcel->getSecurity()->setLockStructure(true);  
  118. $objPHPExcel->getSecurity()->setWorkbookPassword("PHPExcel");  
  119. //Set sheet security 设置工作表安全  
  120. $objPHPExcel->getActiveSheet()->getProtection()->setPassword(‘PHPExcel‘);  
  121. $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);// This should be enabled in order to enable any of the following!  
  122. $objPHPExcel->getActiveSheet()->getProtection()->setSort(true);  
  123. $objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true);  
  124. $objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true);  
  125. //Calculated data 计算  
  126. echo ‘Value of B14 [=COUNT(B2:B12)]: ‘ . $objPHPExcel->getActiveSheet()->getCell(‘B14‘)->getCalculatedValue() . "\r\n";  
  127. //Set outline levels  
  128. $objPHPExcel->getActiveSheet()->getColumnDimension(‘E‘)->setOutlineLevel(1);  
  129. $objPHPExcel->getActiveSheet()->getColumnDimension(‘E‘)->setVisible(false);  
  130. $objPHPExcel->getActiveSheet()->getColumnDimension(‘E‘)->setCollapsed(true);  
  131. //Freeze panes  
  132. $objPHPExcel->getActiveSheet()->freezePane(‘A2‘);  
  133. //Rows to repeat at top  
  134. $objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);  
  135. //Set data validation 验证输入值  
  136. $objValidation = $objPHPExcel->getActiveSheet()->getCell(‘B3‘)->getDataValidation();  
  137. $objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_WHOLE );  
  138. $objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );  
  139. $objValidation->setAllowBlank(true);  
  140. $objValidation->setShowInputMessage(true);  
  141. $objValidation->setShowErrorMessage(true);  
  142. $objValidation->setErrorTitle(‘Input error‘);  
  143. $objValidation->setError(‘Number is not allowed!‘);  
  144. $objValidation->setPromptTitle(‘Allowed input‘);  
  145. $objValidation->setPrompt(‘Only numbers between 10 and 20 are allowed.‘);  
  146. $objValidation->setFormula1(10);  
  147. $objValidation->setFormula2(20);  
  148. $objPHPExcel->getActiveSheet()->getCell(‘B3‘)->setDataValidation($objValidation);  
  149. //Create a new worksheet, after the default sheet 创建新的工作标签  
  150. $objPHPExcel->createSheet();  
  151. $objPHPExcel->setActiveSheetIndex(1);  
  152. //Set header and footer. When no different headers for odd/even are used, odd header is assumed. 页眉页脚  
  153. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader(‘&C&HPlease treat this document as confidential!‘);  
  154. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter(‘&L&B‘ . $objPHPExcel->getProperties()->getTitle() . ‘&RPage &P of &N‘);  
  155. //Set page orientation and size 方向大小  
  156. $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);  
  157. $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);  
  158. //Rename sheet 重命名工作表标签  
  159. $objPHPExcel->getActiveSheet()->setTitle(‘Simple‘);  
  160. //Set active sheet index to the first sheet, so Excel opens this as the first sheet  
  161. $objPHPExcel->setActiveSheetIndex(0);  
  162. //Save Excel 2007 file 保存  
  163. $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);  
  164. $objWriter->save(str_replace(‘.php‘, ‘.xlsx‘, __FILE__));  
  165. //Save Excel 5 file 保存  
  166. require_once(‘Classes/PHPExcel/Writer/Excel5.php‘);  
  167. $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);  
  168. $objWriter->save(str_replace(‘.php‘, ‘.xls‘, __FILE__));  
  169. //1.6.2新版保存  
  170. require_once(‘Classes/PHPExcel/IOFactory.php‘);  
  171. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007‘);  
  172. $objWriter->save(str_replace(‘.php‘, ‘.xls‘, __FILE__));  

 

excel

[php]

  1. //Include class  
  2. require_once(‘Classes/PHPExcel/Reader/Excel2007.php‘);  
  3. $objReader = new PHPExcel_Reader_Excel2007;  
  4. $objPHPExcel = $objReader->load("05featuredemo.xlsx");  

 

读写csv

[php] 

  1. require_once("05featuredemo.inc.php");  
  2. require_once(‘Classes/PHPExcel/Writer/CSV.php‘);  
  3. require_once(‘Classes/PHPExcel/Reader/CSV.php‘);  
  4. require_once(‘Classes/PHPExcel/Writer/Excel2007.php‘);  
  5. //Write to CSV format 写  
  6. $objWriter = new PHPExcel_Writer_CSV($objPHPExcel);  
  7. $objWriter->setDelimiter(‘;‘);  
  8. $objWriter->setEnclosure(‘‘);  
  9. $objWriter->setLineEnding("\r\n");  
  10. $objWriter->setSheetIndex(0);  
  11. $objWriter->save(str_replace(‘.php‘, ‘.csv‘, __FILE__));  
  12. //Read from CSV format 读  
  13. $objReader = new PHPExcel_Reader_CSV();  
  14. $objReader->setDelimiter(‘;‘);  
  15. $objReader->setEnclosure(‘‘);  
  16. $objReader->setLineEnding("\r\n");  
  17. $objReader->setSheetIndex(0);  
  18. $objPHPExcelFromCSV = $objReader->load(str_replace(‘.php‘, ‘.csv‘, __FILE__));  
  19. //Write to Excel2007 format  
  20. $objWriter2007 = new PHPExcel_Writer_Excel2007($objPHPExcelFromCSV);  
  21. $objWriter2007->save(str_replace(‘.php‘, ‘.xlsx‘, __FILE__));  

 

html

[php]

  1. require_once("05featuredemo.inc.php");  
  2. require_once(‘Classes/PHPExcel/Writer/HTML.php‘);  
  3. //Write to HTML format  
  4. $objWriter = new PHPExcel_Writer_HTML($objPHPExcel);  
  5. $objWriter->setSheetIndex(0);  
  6. $objWriter->save(str_replace(‘.php‘, ‘.htm‘, __FILE__));  

 

pdf

[php]

  1. require_once("05featuredemo.inc.php");  
  2. require_once(‘Classes/PHPExcel/IOFactory.php‘);  
  3. //Write to PDF format  
  4. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘PDF‘);  
  5. $objWriter->setSheetIndex(0);  
  6. $objWriter->save(str_replace(‘.php‘, ‘.pdf‘, __FILE__));  
  7. //Echo memory peak usage  
  8. echo date(‘H:i:s‘) . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";  

 

 

 

PHP操作Excel – PHPExcel 基本用法