·设为首页收藏本站📧邮箱修改🎁免费下载专区📒收藏夹👽聊天室📱AI智能体
返回列表 发布新帖

PHP操作Excel – PHPExcel 基本用法详解

457 2
发表于 2023-4-22 09:19:47 | 查看全部 阅读模式

马上注册,免费下载更多dz插件网资源。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
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.PHPExcel

http://www.codeplex.com/PHPExcel
http://www.phpexcel.net
开发包Tests目录有详细使用实例  支持中文,注意文件编码   文件保存为utf-8
写excel
  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
  1. //Include class
  2. require_once('Classes/PHPExcel/Reader/Excel2007.php');
  3. $objReader = new PHPExcel_Reader_Excel2007;
  4. $objPHPExcel = $objReader->load("05featuredemo.xlsx");
复制代码

读写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__));
复制代码

写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__));
复制代码

写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";
复制代码
我要说一句 收起回复

评论2

TyCodingLv.8 发表于 2023-4-22 09:20:21 | 查看全部
1、设置某一行的高度为35:
$active_sheet->getRowDimension(2)->setRowHeight(35);


2、设置某一行(第二行A单元格到F单元格)的背景色:
$active_sheet->getStyle('A2:F2')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$active_sheet->getStyle('A2:F2')->getFill()->getStartColor()->setARGB("#0cedffb");



3、合并列,并设置此列值
$hcenter      = PHPExcel_Style_Alignment::HORIZONTAL_CENTER;//水平居中
$vcenter      = PHPExcel_Style_Alignment::VERTICAL_CENTER;//上下居中

//表头
$objWorksheet->mergeCells('A1:E1')->setCellValue('A1', '类目')->getStyle('A1')->getAlignment()->setHorizontal($hcenter);

也可以参考:http://www.cnblogs.com/huangcong/p/3687665.html
我要说一句 收起回复
AI智能体Lv.7 发表于 2025-3-16 15:12:06 | 查看全部
PHPExcel 是一个非常强大的 PHP 库,用于处理 Excel 文件。它支持读取、写入和操作 Excel 文件(包括 Excel 2007 及以上版本的 `.xlsx` 文件以及 Excel 5 的 `.xls` 文件)。以下是对你提供的代码的详细解释和一些补充说明。

### 1. 设置 HTTP 头信息
在生成 Excel 文件并输出到浏览器时,需要设置正确的 HTTP 头信息,以确保浏览器能够正确处理文件。

  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");
复制代码


- `Content-Type:application/vnd.ms-excel`:指定文件类型为 Excel 文件。
- `Content-Disposition:attachment;filename=sample.xls`:指定文件名为 `sample.xls`,并告诉浏览器以附件形式下载文件。
- `Pragma:no-cache` 和 `Expires:0`:确保文件不被缓存。

### 2. 引入 PHPExcel 类库
在使用 PHPExcel 之前,需要引入相关的类文件。

  1. require_once('Classes/PHPExcel.php');
  2. require_once('Classes/PHPExcel/Writer/Excel2007.php');
复制代码


### 3. 创建 PHPExcel 对象
创建一个 PHPExcel 对象,用于操作 Excel 文件。

  1. $objPHPExcel = new PHPExcel();
复制代码


### 4. 设置文件属性
可以通过 `getProperties()` 方法设置 Excel 文件的属性,如创建者、标题、主题等。

  1. $objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
  2. $objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
  3. $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
  4. $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
  5. $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
  6. $objPHPExcel->getProperties()->setKeywords("office 2007 openxml php");
  7. $objPHPExcel->getProperties()->setCategory("Test result file");
复制代码


### 5. 添加数据到工作表
可以通过 `setCellValue()` 方法向工作表的指定单元格添加数据。

  1. $objPHPExcel->setActiveSheetIndex(0);
  2. $objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello');
  3. $objPHPExcel->getActiveSheet()->setCellValue('A2', true);
  4. $objPHPExcel->getActiveSheet()->setCellValue('A3', false);
  5. $objPHPExcel->getActiveSheet()->setCellValue('B2', 'world!');
  6. $objPHPExcel->getActiveSheet()->setCellValue('B3', 2);
  7. $objPHPExcel->getActiveSheet()->setCellValue('C1', 'Hello');
  8. $objPHPExcel->getActiveSheet()->setCellValue('D2', 'world!');
复制代码


### 6. 循环添加数据
可以通过循环向工作表中添加数据。

  1. for($i = 1; $i <= 10; $i++) {
  2.     $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $i);
  3.     $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, 'Test value');
  4. }
复制代码


### 7. 日期格式化
可以通过 `getNumberFormat()` 方法设置单元格的日期格式。

  1. $objPHPExcel->getActiveSheet()->setCellValue('D1', time());
  2. $objPHPExcel->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
复制代码


### 8. 添加注释
可以通过 `getComment()` 方法为单元格添加注释。

  1. $objPHPExcel->getActiveSheet()->getComment('E11')->setAuthor('PHPExcel');
  2. $objCommentRichText = $objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun('PHPExcel:');
  3. $objCommentRichText->getFont()->setBold(true);
  4. $objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun("\r\n");
  5. $objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun('Total amount on the current invoice, excluding VAT.');
复制代码


### 9. 添加富文本
可以通过 `PHPExcel_RichText` 类向单元格添加富文本。

  1. $objRichText = new PHPExcel_RichText($objPHPExcel->getActiveSheet()->getCell('A18'));
  2. $objRichText->createText('This invoice is ');
  3. $objPayable = $objRichText->createTextRun('payable within thirty days after the end of the month');
  4. $objPayable->getFont()->setBold(true);
  5. $objPayable->getFont()->setItalic(true);
  6. $objPayable->getFont()->setColor(new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_DARKGREEN));
  7. $objRichText->createText(', unless specified otherwise on the invoice.');
复制代码


### 10. 合并单元格
可以通过 `mergeCells()` 方法合并单元格。

  1. $objPHPExcel->getActiveSheet()->mergeCells('A18:E22');
  2. $objPHPExcel->getActiveSheet()->unmergeCells('A18:E22');
复制代码


### 11. 保护单元格
可以通过 `protectCells()` 方法保护单元格。

  1. $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
  2. $objPHPExcel->getActiveSheet()->protectCells('A3:E13', 'PHPExcel');
复制代码


### 12. 设置数字格式
可以通过 `getNumberFormat()` 方法设置单元格的数字格式。

  1. $objPHPExcel->getActiveSheet()->getStyle('E4')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);
  2. $objPHPExcel->getActiveSheet()->duplicateStyle($objPHPExcel->getActiveSheet()->getStyle('E4'), 'E5:E13');
复制代码


### 13. 设置列宽度
可以通过 `getColumnDimension()` 方法设置列的宽度。

  1. $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
  2. $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
复制代码


### 14. 设置字体
可以通过 `getFont()` 方法设置单元格的字体样式。

  1. $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara');
  2. $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(20);
  3. $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
  4. $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  5. $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
复制代码


### 15. 设置对齐方式
可以通过 `getAlignment()` 方法设置单元格的对齐方式。

  1. $objPHPExcel->getActiveSheet()->getStyle('D11')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  2. $objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
  3. $objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
  4. $objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setWrapText(true);
复制代码


### 16. 设置边框
可以通过 `getBorders()` 方法设置单元格的边框。

  1. $objPHPExcel->getActiveSheet()->getStyle('A4')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  2. $objPHPExcel->getActiveSheet()->getStyle('A10')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  3. $objPHPExcel->getActiveSheet()->getStyle('E10')->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  4. $objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
  5. $objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
复制代码


### 17. 设置边框颜色
可以通过 `getColor()` 方法设置边框的颜色。

  1. $objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->getColor()->setARGB('FF993300');
  2. $objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getTop()->getColor()->setARGB('FF993300');
  3. $objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getBottom()->getColor()->setARGB('FF993300');
  4. $objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getRight()->getColor()->setARGB('FF993300');
复制代码


### 18. 设置填充
可以通过 `getFill()` 方法设置单元格的填充颜色。

  1. $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
  2. $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB('FF808080');
复制代码


### 19. 添加超链接
可以通过 `getHyperlink()` 方法为单元格添加超链接。

  1. $objPHPExcel->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
  2. $objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('http://www.phpexcel.net');
  3. $objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setTooltip('Navigate to website');
  4. $objPHPExcel->getActiveSheet()->getStyle('E26')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
复制代码


### 20. 添加图片
可以通过 `PHPExcel_Worksheet_Drawing` 类向工作表中添加图片。

  1. $objDrawing = new PHPExcel_Worksheet_Drawing();
  2. $objDrawing->setName('Logo');
  3. $objDrawing->setDescription('Logo');
  4. $objDrawing->setPath('./images/officelogo.jpg');
  5. $objDrawing->setHeight(36);
  6. $objDrawing->setCoordinates('B15');
  7. $objDrawing->setOffsetX(110);
  8. $objDrawing->setRotation(25);
  9. $objDrawing->getShadow()->setVisible(true);
  10. $objDrawing->getShadow()->setDirection(45);
  11. $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
复制代码


### 21. 插入和删除行/列
可以通过 `insertNewRowBefore()`、`removeRow()`、`insertNewColumnBefore()` 和 `removeColumn()` 方法插入和删除行/列。

  1. $objPHPExcel->getActiveSheet()->insertNewRowBefore(6, 10);
  2. $objPHPExcel->getActiveSheet()->removeRow(6, 10);
  3. $objPHPExcel->getActiveSheet()->insertNewColumnBefore('E', 5);
  4. $objPHPExcel->getActiveSheet()->removeColumn('E', 5);
复制代码


### 22. 条件格式化
可以通过 `PHPExcel_Style_Conditional` 类设置条件格式化。

  1. $objConditional1 = new PHPExcel_Style_Conditional();
  2. $objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);
  3. $objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN);
  4. $objConditional1->setCondition('0');
  5. $objConditional1->getStyle()->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED);
  6. $objConditional1->getStyle()->getFont()->setBold(true);
复制代码


### 23. 自动过滤
可以通过 `setAutoFilter()` 方法设置自动过滤。

  1. $objPHPExcel->getActiveSheet()->setAutoFilter('A1:C9');
复制代码


### 24. 隐藏列
可以通过 `setVisible(false)` 方法隐藏列。

  1. $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setVisible(false);
  2. $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setVisible(false);
复制代码


### 25. 设置文档安全
可以通过 `getSecurity()` 方法设置文档的安全选项。

  1. $objPHPExcel->getSecurity()->setLockWindows(true);
  2. $objPHPExcel->getSecurity()->setLockStructure(true);
  3. $objPHPExcel->getSecurity()->setWorkbookPassword("PHPExcel");
复制代码


### 26. 设置工作表安全
可以通过 `getProtection()` 方法设置工作表的安全选项。

  1. $objPHPExcel->getActiveSheet()->getProtection()->setPassword('PHPExcel');
  2. $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
  3. $objPHPExcel->getActiveSheet()->getProtection()->setSort(true);
  4. $objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true);
  5. $objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true);
复制代码


### 27. 计算数据
可以通过 `getCalculatedValue()` 方法获取单元格的计算值。

  1. echo 'Value of B14 : ' . $objPHPExcel->getActiveSheet()->getCell('B14')->getCalculatedValue() . "\r\n";
复制代码


### 28. 设置大纲级别
可以通过 `setOutlineLevel()` 方法设置列的大纲级别。

  1. $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1);
  2. $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setVisible(false);
  3. $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setCollapsed(true);
复制代码


### 29. 冻结窗格
可以通过 `freezePane()` 方法冻结窗格。

  1. $objPHPExcel->getActiveSheet()->freezePane('A2');
复制代码


### 30. 设置重复行
可以通过 `setRowsToRepeatAtTopByStartAndEnd()` 方法设置重复行。

  1. $objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
复制代码


### 31. 数据验证
可以通过 `getDataValidation()` 方法设置数据验证。

  1. $objValidation = $objPHPExcel->getActiveSheet()->getCell('B3')->getDataValidation();
  2. $objValidation->setType(PHPExcel_Cell_DataValidation::TYPE_WHOLE);
  3. $objValidation->setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_STOP);
  4. $objValidation->setAllowBlank(true);
  5. $objValidation->setShowInputMessage(true);
  6. $objValidation->setShowErrorMessage(true);
  7. $objValidation->setErrorTitle('Input error');
  8. $objValidation->setError('Number is not allowed!');
  9. $objValidation->setPromptTitle('Allowed input');
  10. $objValidation->setPrompt('Only numbers between 10 and 20 are allowed.');
  11. $objValidation->setFormula1(10);
  12. $objValidation->setFormula2(20);
  13. $objPHPExcel->getActiveSheet()->getCell('B3')->setDataValidation($objValidation);
复制代码


### 32. 创建新的工作表
可以通过 `createSheet()` 方法创建新的工作表。

  1. $objPHPExcel->createSheet();
  2. $objPHPExcel->setActiveSheetIndex(1);
复制代码


### 33. 设置页眉和页脚
可以通过 `getHeaderFooter()` 方法设置页眉和页脚。

  1. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader('&C&HPlease treat this document as confidential!');
  2. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N');
复制代码


### 34. 设置页面方向和大小
可以通过 `getPageSetup()` 方法设置页面的方向和大小。

  1. $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
  2. $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
复制代码


### 35. 重命名工作表
可以通过 `setTitle()` 方法重命名工作表。

  1. $objPHPExcel->getActiveSheet()->setTitle('Simple');
复制代码


### 36. 保存 Excel 文件
可以通过 `PHPExcel_Writer_Excel2007` 或 `PHPExcel_Writer_Excel5` 类保存 Excel 文件。

  1. $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
  2. $objWriter->save(str_replace('.php', '.xlsx', __FILE__));

  3. require_once('Classes/PHPExcel/Writer/Excel5.php');
  4. $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
  5. $objWriter->save(str_replace('.php', '.xls', __FILE__));

  6. require_once('Classes/PHPExcel/IOFactory.php');
  7. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  8. $objWriter->save(str_replace('.php', '.xls', __FILE__));
复制代码


### 37. 读取 Excel 文件
可以通过 `PHPExcel_Reader_Excel2007` 类读取 Excel 文件。

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


### 38. 读写 CSV 文件
可以通过 `PHPExcel_Writer_CSV` 和 `PHPExcel_Reader_CSV` 类读写 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. // 写 CSV
  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. // 读 CSV
  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. // 写 Excel2007
  20. $objWriter2007 = new PHPExcel_Writer_Excel2007($objPHPExcelFromCSV);
  21. $objWriter2007->save(str_replace('.php', '.xlsx', __FILE__));
复制代码


### 39. 写 HTML 文件
可以通过 `PHPExcel_Writer_HTML` 类将 Excel 文件保存为 HTML 格式。

  1. require_once("05featuredemo.inc.php");
  2. require_once('Classes/PHPExcel/Writer/HTML.php');
  3. $objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
  4. $objWriter->setSheetIndex(0);
  5. $objWriter->save(str_replace('.php', '.htm', __FILE__));
复制代码


### 40. 写 PDF 文件
可以通过 `PHPExcel_IOFactory` 类将 Excel 文件保存为 PDF 格式。

  1. require_once("05featuredemo.inc.php");
  2. require_once('Classes/PHPExcel/IOFactory.php');
  3. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
  4. $objWriter->setSheetIndex(0);
  5. $objWriter->save(str_replace('.php', '.pdf', __FILE__));
复制代码


### 41. 输出内存使用情况
可以通过 `memory_get_peak_usage()` 函数输出内存使用情况。

  1. echo date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";
复制代码


### 总结
PHPExcel 提供了丰富的功能来处理 Excel 文件,包括读取、写入、格式化、添加图片、设置安全选项等。通过上述代码示例,你可以轻松地在 PHP 中生成和操作 Excel 文件。如果你有更多关于 PHPExcel 的问题,欢迎继续提问!
-- 本回答由 人工智能 AI智能体 生成,内容仅供参考,请仔细甄别。
我要说一句 收起回复

回复

 懒得打字嘛,点击右侧快捷回复【查看最新发布】   【应用商城享更多资源】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

AI智能体
投诉/建议联系

discuzaddons@vip.qq.com

未经授权禁止转载,复制和建立镜像,
如有违反,按照公告处理!!!
  • 联系QQ客服
  • 添加微信客服

联系DZ插件网微信客服|最近更新|Archiver|手机版|小黑屋|DZ插件网! ( 鄂ICP备20010621号-1 )|网站地图 知道创宇云防御

您的IP:13.58.244.160,GMT+8, 2025-4-4 16:13 , Processed in 0.925657 second(s), 79 queries , Gzip On, Redis On.

Powered by Discuz! X5.0 Licensed

© 2001-2025 Discuz! Team.

关灯 在本版发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表