不乱于心,不困于情。
不畏将来,不念过往。如此,安好。

PHP操作excel

1. 读写操作

  1. <?php
  2. require_once "lib\PHPExcel-1.8\Classes\PHPExcel.php";
  3. echo "<P>test phpexcel</P>";
  4. //读数据
  5. $filename = 'C:\\ProgramData\\1.xls';
  6. $objReader = PHPExcel_IOFactory::createReaderForFile($filename);; //准备打开文件
  7. $objPHPExcel = $objReader->load($filename); //载入文件
  8. $objPHPExcel->setActiveSheetIndex(0); //设置第一个Sheet
  9. $data = $objPHPExcel->getActiveSheet()->getCell('A2')->getValue(); //获取单元格A2的值
  10. echo $data;
  11. //写数据
  12. $objPHPExcel->getActiveSheet()->setCellValue('A2', 'Hello');//指定要写的单元格位置
  13. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  14. $objWriter->save('2.xls');
  15. ?>

2.循环读出每个单元格的数据

  1. <?php
  2. require_once "lib\PHPExcel-1.8\Classes\PHPExcel.php";
  3. // Check prerequisites
  4. $reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
  5. $PHPExcel = $reader->load("C:\\ProgramData\\1.xls"); // 载入excel文件
  6. $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
  7. $highestRow = $sheet->getHighestRow(); // 取得总行数
  8. $highestColumm = $sheet->getHighestColumn(); // 取得总列数
  9. /** 循环读取每个单元格的数据 */
  10. for ($row = 1; $row <= $highestRow; $row++) //行号从1开始
  11. {
  12. for ($column = 'A'; $column <= $highestColumm; $column++) //列数是以A列开始
  13. {
  14. $dataset[] = $sheet->getCell($column.$row)->getValue();
  15. echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br\>";
  16. }
  17. }
  18. ?>

 

3. 各种读写相关的方法参考

  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.  
  166. //Save Excel 5 file 保存
  167. require_once('Classes/PHPExcel/Writer/Excel5.php');
  168. $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
  169. $objWriter->save(str_replace('.php', '.xls', __FILE__));
  170. //1.6.2新版保存
  171. require_once('Classes/PHPExcel/IOFactory.php');
  172. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  173. $objWriter->save(str_replace('.php', '.xls', __FILE__));

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('Classes/PHPExcel/Writer/HTML.php');
  2. //Write to HTML format
  3. $objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
  4. $objWriter->setSheetIndex(0);
  5. $objWriter->save(str_replace('.php', '.htm', __FILE__));

 

 

6.写PDF

  1. require_once('Classes/PHPExcel/IOFactory.php');
  2. //Write to PDF format
  3. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
  4. $objWriter->setSheetIndex(0);
  5. $objWriter->save(str_replace('.php', '.pdf', __FILE__));
  6. //Echo memory peak usage
  7. echo date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";
赞(0)
未经允许不得转载:seo优化_前端开发_渗透技术 » PHP操作excel