Home Backend Development PHP Tutorial Example code for phpExcel to export excel and add hyperlinks

Example code for phpExcel to export excel and add hyperlinks

Jul 25, 2016 am 08:55 AM

  1. //写excel

  2. //Include class

  3. require_once(‘Classes/PHPExcel.php’);
  4. require_once(‘Classes/PHPExcel/Writer/Excel2007.php’);
  5. $objPHPExcel = new PHPExcel();

  6. /**

  7. * phpExcel导出excel
  8. * by bbs.it-home.org
  9. */

  10. //Set properties 设置文件属性

  11. $objPHPExcel->getProperties()->setCreator(“Maarten Balliauw”);
  12. $objPHPExcel->getProperties()->setLastModifiedBy(“Maarten Balliauw”);
  13. $objPHPExcel->getProperties()->setTitle(“Office 2007 XLSX Test Document”);
  14. $objPHPExcel->getProperties()->setSubject(“Office 2007 XLSX Test Document”);
  15. $objPHPExcel->getProperties()->setDescription(“Test document for Office 2007 XLSX, generated using PHP classes.”);
  16. $objPHPExcel->getProperties()->setKeywords(“office 2007 openxml php”);
  17. $objPHPExcel->getProperties()->setCategory(“Test result file”);

  18. //Add some data 添加数据

  19. $objPHPExcel->setActiveSheetIndex(0);
  20. $objPHPExcel->getActiveSheet()->setCellValue(‘A1′, ‘Hello’);//可以指定位置
  21. $objPHPExcel->getActiveSheet()->setCellValue(‘A2′, true);
  22. $objPHPExcel->getActiveSheet()->setCellValue(‘A3′, false);
  23. $objPHPExcel->getActiveSheet()->setCellValue(‘B2′, ‘world!’);
  24. $objPHPExcel->getActiveSheet()->setCellValue(‘B3′, 2);
  25. $objPHPExcel->getActiveSheet()->setCellValue(‘C1′, ‘Hello’);
  26. $objPHPExcel->getActiveSheet()->setCellValue(‘D2′, ‘world!’);
  27. //循环
  28. for($i = 1;$i<200;$i++) {
  29. $objPHPExcel->getActiveSheet()->setCellValue(‘A’ . $i, $i);
  30. $objPHPExcel->getActiveSheet()->setCellValue(‘B’ . $i, ‘Test value’);
  31. }
  32. //日期格式化
  33. $objPHPExcel->getActiveSheet()->setCellValue(‘D1′, time());
  34. $objPHPExcel->getActiveSheet()->getStyle(‘D1′)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);

  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(“rn”);
  40. $objPHPExcel->getActiveSheet()->getComment(‘E11′)->getText()->createTextRun(‘Total amount on the current invoice, excluding VAT.’);

  41. //Add rich-text string 添加文字 可设置样式

  42. $objRichText = new PHPExcel_RichText( $objPHPExcel->getActiveSheet()->getCell(‘A18′) );
  43. $objRichText->createText(‘This invoice is ‘);
  44. $objPayable = $objRichText->createTextRun(‘payable within thirty days after the end of the month’);
  45. $objPayable->getFont()->setBold(true);
  46. $objPayable->getFont()->setItalic(true);
  47. $objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );
  48. $objRichText->createText(‘, unless specified otherwise on the invoice.’);

  49. //Merge cells 合并分离单元格

  50. $objPHPExcel->getActiveSheet()->mergeCells(‘A18:E22′);
  51. $objPHPExcel->getActiveSheet()->unmergeCells(‘A18:E22′);

  52. //Protect cells 保护单元格

  53. $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);//Needs to be set to true in order to enable any worksheet protection!
  54. $objPHPExcel->getActiveSheet()->protectCells(‘A3:E13′, ‘PHPExcel’);

  55. //Set cell number formats 数字格式化

  56. $objPHPExcel->getActiveSheet()->getStyle(‘E4′)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);
  57. $objPHPExcel->getActiveSheet()->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle(‘E4′), ‘E5:E13′ );

  58. //Set column widths 设置列宽度

  59. $objPHPExcel->getActiveSheet()->getColumnDimension(‘B’)->setAutoSize(true);
  60. $objPHPExcel->getActiveSheet()->getColumnDimension(‘D’)->setWidth(12);

  61. //Set fonts 设置字体

  62. $objPHPExcel->getActiveSheet()->getStyle(‘B1′)->getFont()->setName(‘Candara’);
  63. $objPHPExcel->getActiveSheet()->getStyle(‘B1′)->getFont()->setSize(20);
  64. $objPHPExcel->getActiveSheet()->getStyle(‘B1′)->getFont()->setBold(true);
  65. $objPHPExcel->getActiveSheet()->getStyle(‘B1′)->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  66. $objPHPExcel->getActiveSheet()->getStyle(‘B1′)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);

  67. //Set alignments 设置对齐

  68. $objPHPExcel->getActiveSheet()->getStyle(‘D11′)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  69. $objPHPExcel->getActiveSheet()->getStyle(‘A18′)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
  70. $objPHPExcel->getActiveSheet()->getStyle(‘A18′)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
  71. $objPHPExcel->getActiveSheet()->getStyle(‘A3′)->getAlignment()->setWrapText(true);

  72. //Set column borders 设置列边框

  73. $objPHPExcel->getActiveSheet()->getStyle(‘A4′)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  74. $objPHPExcel->getActiveSheet()->getStyle(‘A10′)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  75. $objPHPExcel->getActiveSheet()->getStyle(‘E10′)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  76. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
  77. $objPHPExcel->getActiveSheet()->getStyle(‘E13′)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);

  78. //Set border colors 设置边框颜色

  79. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getLeft()->getColor()->setARGB(‘FF993300′);
  80. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getTop()->getColor()->setARGB(‘FF993300′);
  81. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getBottom()->getColor()->setARGB(‘FF993300′);
  82. $objPHPExcel->getActiveSheet()->getStyle(‘E13′)->getBorders()->getRight()->getColor()->setARGB(‘FF993300′);

  83. //Set fills 设置填充

  84. $objPHPExcel->getActiveSheet()->getStyle(‘A1′)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
  85. $objPHPExcel->getActiveSheet()->getStyle(‘A1′)->getFill()->getStartColor()->setARGB(‘FF808080′);

  86. //Add a hyperlink to the sheet 添加链接

  87. $objPHPExcel->getActiveSheet()->setCellValue(‘E26′, ‘www.phpexcel.net’);
  88. $objPHPExcel->getActiveSheet()->getCell(‘E26′)->getHyperlink()->setUrl(‘http://www.phpexcel.net’);
  89. $objPHPExcel->getActiveSheet()->getCell(‘E26′)->getHyperlink()->setTooltip(‘Navigate to website’);
  90. $objPHPExcel->getActiveSheet()->getStyle(‘E26′)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

  91. //Add a drawing to the worksheet 添加图片

  92. $objDrawing = new PHPExcel_Worksheet_Drawing();
  93. $objDrawing->setName(‘Logo’);
  94. $objDrawing->setDescription(‘Logo’);
  95. $objDrawing->setPath(‘./images/officelogo.jpg’);
  96. $objDrawing->setHeight(36);
  97. $objDrawing->setCoordinates(‘B15′);
  98. $objDrawing->setOffsetX(110);
  99. $objDrawing->setRotation(25);
  100. $objDrawing->getShadow()->setVisible(true);
  101. $objDrawing->getShadow()->setDirection(45);
  102. $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());

  103. //Play around with inserting and removing rows and columns

  104. $objPHPExcel->getActiveSheet()->insertNewRowBefore(6, 10);
  105. $objPHPExcel->getActiveSheet()->removeRow(6, 10);
  106. $objPHPExcel->getActiveSheet()->insertNewColumnBefore(‘E’, 5);
  107. $objPHPExcel->getActiveSheet()->removeColumn(‘E’, 5);

  108. //Add conditional formatting

  109. $objConditional1 = new PHPExcel_Style_Conditional();
  110. $objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);
  111. $objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN);
  112. $objConditional1->setCondition(’0′);
  113. $objConditional1->getStyle()->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED);
  114. $objConditional1->getStyle()->getFont()->setBold(true);

  115. //Set autofilter 自动过滤

  116. $objPHPExcel->getActiveSheet()->setAutoFilter(‘A1:C9′);

  117. //Hide “Phone” and “fax” column 隐藏列

  118. $objPHPExcel->getActiveSheet()->getColumnDimension(‘C’)->setVisible(false);
  119. $objPHPExcel->getActiveSheet()->getColumnDimension(‘D’)->setVisible(false);

  120. //Set document security 设置文档安全

  121. $objPHPExcel->getSecurity()->setLockWindows(true);
  122. $objPHPExcel->getSecurity()->setLockStructure(true);
  123. $objPHPExcel->getSecurity()->setWorkbookPassword(“PHPExcel”);

  124. //Set sheet security 设置工作表安全

  125. $objPHPExcel->getActiveSheet()->getProtection()->setPassword(‘PHPExcel’);
  126. $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);// This should be enabled in order to enable any of the following!
  127. $objPHPExcel->getActiveSheet()->getProtection()->setSort(true);
  128. $objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true);
  129. $objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true);

  130. //Calculated data 计算

  131. echo ‘Value of B14 [=COUNT(B2:B12)]: ‘ . $objPHPExcel->getActiveSheet()->getCell(‘B14′)->getCalculatedValue() . “rn”;

  132. //Set outline levels

  133. $objPHPExcel->getActiveSheet()->getColumnDimension(‘E’)->setOutlineLevel(1);
  134. $objPHPExcel->getActiveSheet()->getColumnDimension(‘E’)->setVisible(false);
  135. $objPHPExcel->getActiveSheet()->getColumnDimension(‘E’)->setCollapsed(true);

  136. //Freeze panes

  137. $objPHPExcel->getActiveSheet()->freezePane(‘A2′);

  138. //Rows to repeat at top

  139. $objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);

  140. //Set data validation 验证输入值

  141. $objValidation = $objPHPExcel->getActiveSheet()->getCell(‘B3′)->getDataValidation();
  142. $objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_WHOLE );
  143. $objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
  144. $objValidation->setAllowBlank(true);
  145. $objValidation->setShowInputMessage(true);
  146. $objValidation->setShowErrorMessage(true);
  147. $objValidation->setErrorTitle(‘Input error’);
  148. $objValidation->setError(‘Number is not allowed!’);
  149. $objValidation->setPromptTitle(‘Allowed input’);
  150. $objValidation->setPrompt(‘Only numbers between 10 and 20 are allowed.’);
  151. $objValidation->setFormula1(10);
  152. $objValidation->setFormula2(20);
  153. $objPHPExcel->getActiveSheet()->getCell(‘B3′)->setDataValidation($objValidation);

  154. //Create a new worksheet, after the default sheet 创建新的工作标签

  155. $objPHPExcel->createSheet(); bbs.it-home.org
  156. $objPHPExcel->setActiveSheetIndex(1);

  157. //Set header and footer. When no different headers for odd/even are used, odd header is assumed. 页眉页脚

  158. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader(‘&C&HPlease treat this document as confidential!’);
  159. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter(‘&L&B’ . $objPHPExcel->getProperties()->getTitle() . ‘&RPage &P of &N’);

  160. //Set page orientation and size 方向大小

  161. $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
  162. $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);

  163. //Rename sheet 重命名工作表标签

  164. $objPHPExcel->getActiveSheet()->setTitle(‘Simple’);

  165. //Set active sheet index to the first sheet, so Excel opens this as the first sheet

  166. $objPHPExcel->setActiveSheetIndex(0);

  167. //Save Excel 2007 file 保存

  168. $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
  169. $objWriter->save(str_replace(‘.php’, ‘.xlsx’, __FILE__));

  170. //Save Excel 5 file 保存

  171. require_once(‘Classes/PHPExcel/Writer/Excel5.php’);
  172. $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
  173. $objWriter->save(str_replace(‘.php’, ‘.xls’, __FILE__));

  174. //1.6.2新版保存

  175. require_once(‘Classes/PHPExcel/IOFactory.php’);
  176. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007′);
  177. $objWriter->save(str_replace(‘.php’, ‘.xls’, __FILE__));

  178. //读excel

  179. //Include class
  180. require_once(‘Classes/PHPExcel/Reader/Excel2007.php’);
  181. $objReader = new PHPExcel_Reader_Excel2007;

  182. $objPHPExcel = $objReader->load(“05featuredemo.xlsx”);

  183. //读写csv

  184. require_once(“05featuredemo.inc.php”);
  185. require_once(‘Classes/PHPExcel/Writer/CSV.php’);
  186. require_once(‘Classes/PHPExcel/Reader/CSV.php’);
  187. require_once(‘Classes/PHPExcel/Writer/Excel2007.php’);

  188. //Write to CSV format 写

  189. $objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
  190. $objWriter->setDelimiter(‘;’);
  191. $objWriter->setEnclosure(”);
  192. $objWriter->setLineEnding(“rn”);
  193. $objWriter->setSheetIndex(0);
  194. $objWriter->save(str_replace(‘.php’, ‘.csv’, __FILE__));

  195. //Read from CSV format 读

  196. $objReader = new PHPExcel_Reader_CSV();
  197. $objReader->setDelimiter(‘;’);
  198. $objReader->setEnclosure(”);
  199. $objReader->setLineEnding(“rn”);
  200. $objReader->setSheetIndex(0);
  201. $objPHPExcelFromCSV = $objReader->load(str_replace(‘.php’, ‘.csv’, __FILE__));

  202. //Write to Excel2007 format

  203. $objWriter2007 = new PHPExcel_Writer_Excel2007($objPHPExcelFromCSV);
  204. $objWriter2007->save(str_replace(‘.php’, ‘.xlsx’, __FILE__));

  205. //写html

  206. require_once(“05featuredemo.inc.php”);
  207. require_once(‘Classes/PHPExcel/Writer/HTML.php’);

  208. //Write to HTML format

  209. $objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
  210. $objWriter->setSheetIndex(0);
  211. $objWriter->save(str_replace(‘.php’, ‘.htm’, __FILE__));

  212. //写pdf

  213. require_once(“05featuredemo.inc.php”);
  214. require_once(‘Classes/PHPExcel/IOFactory.php’);

  215. //Write to PDF format

  216. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘PDF’);
  217. $objWriter->setSheetIndex(0);
  218. $objWriter->save(str_replace(‘.php’, ‘.pdf’, __FILE__));
  219. //Echo memory peak usage
  220. echo date(‘H:i:s’) . ” Peak memory usage: ” . (memory_get_peak_usage(true) / 1024 / 1024) . ” MBrn”;

复制代码


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles