首页 > 开发 > PHP > 正文

使用PHPExcel操作Excel用法实例分析

2024-05-04 23:33:24
字体:
来源:转载
供稿:网友

这篇文章主要介绍了使用PHPExcel操作Excel用法,实例分析了使用PHPExcel进行读写及生成等常用技巧,非常具有实用价值,需要的朋友可以参考下

本文实例分析了使用PHPExcel操作Excel用法。分享给大家供大家参考。具体分析如下:

PHPExcel下载地址:

http://www.codeplex.com/PHPExcel

http://www.phpexcel.net

开发包Tests目录有详细使用实例 支持中文,注意文件编码 文件保存为utf-8

1.header部分:

  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.写excel:

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


3.读excel

 

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

4.读写csv

 

 
  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__)); 

5.写html

 

 
  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__)); 

6.写pdf

 

 
  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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表