search
HomeBackend DevelopmentPHP TutorialExample code for phpExcel to export excel and add hyperlinks

  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$objPHPExcel->getActiveSheet()->setCellValue(‘A’ . $i, $i);
  29. $objPHPExcel->getActiveSheet()->setCellValue(‘B’ . $i, ‘Test value’);
  30. }
  31. //日期格式化
  32. $objPHPExcel->getActiveSheet()->setCellValue(‘D1′, time());
  33. $objPHPExcel->getActiveSheet()->getStyle(‘D1′)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
  34. //Add comment 添加注释

  35. $objPHPExcel->getActiveSheet()->getComment(‘E11′)->setAuthor(‘PHPExcel’);
  36. $objCommentRichText = $objPHPExcel->getActiveSheet()->getComment(‘E11′)->getText()->createTextRun(‘PHPExcel:’);
  37. $objCommentRichText->getFont()->setBold(true);
  38. $objPHPExcel->getActiveSheet()->getComment(‘E11′)->getText()->createTextRun(“rn”);
  39. $objPHPExcel->getActiveSheet()->getComment(‘E11′)->getText()->createTextRun(‘Total amount on the current invoice, excluding VAT.’);
  40. //Add rich-text string 添加文字 可设置样式

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

  49. $objPHPExcel->getActiveSheet()->mergeCells(‘A18:E22′);
  50. $objPHPExcel->getActiveSheet()->unmergeCells(‘A18:E22′);
  51. //Protect cells 保护单元格

  52. $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);//Needs to be set to true in order to enable any worksheet protection!
  53. $objPHPExcel->getActiveSheet()->protectCells(‘A3:E13′, ‘PHPExcel’);
  54. //Set cell number formats 数字格式化

  55. $objPHPExcel->getActiveSheet()->getStyle(‘E4′)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);
  56. $objPHPExcel->getActiveSheet()->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle(‘E4′), ‘E5:E13′ );
  57. //Set column widths 设置列宽度

  58. $objPHPExcel->getActiveSheet()->getColumnDimension(‘B’)->setAutoSize(true);
  59. $objPHPExcel->getActiveSheet()->getColumnDimension(‘D’)->setWidth(12);
  60. //Set fonts 设置字体

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

  67. $objPHPExcel->getActiveSheet()->getStyle(‘D11′)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  68. $objPHPExcel->getActiveSheet()->getStyle(‘A18′)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
  69. $objPHPExcel->getActiveSheet()->getStyle(‘A18′)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
  70. $objPHPExcel->getActiveSheet()->getStyle(‘A3′)->getAlignment()->setWrapText(true);
  71. //Set column borders 设置列边框

  72. $objPHPExcel->getActiveSheet()->getStyle(‘A4′)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  73. $objPHPExcel->getActiveSheet()->getStyle(‘A10′)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  74. $objPHPExcel->getActiveSheet()->getStyle(‘E10′)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  75. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
  76. $objPHPExcel->getActiveSheet()->getStyle(‘E13′)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
  77. //Set border colors 设置边框颜色

  78. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getLeft()->getColor()->setARGB(‘FF993300′);
  79. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getTop()->getColor()->setARGB(‘FF993300′);
  80. $objPHPExcel->getActiveSheet()->getStyle(‘D13′)->getBorders()->getBottom()->getColor()->setARGB(‘FF993300′);
  81. $objPHPExcel->getActiveSheet()->getStyle(‘E13′)->getBorders()->getRight()->getColor()->setARGB(‘FF993300′);
  82. //Set fills 设置填充

  83. $objPHPExcel->getActiveSheet()->getStyle(‘A1′)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
  84. $objPHPExcel->getActiveSheet()->getStyle(‘A1′)->getFill()->getStartColor()->setARGB(‘FF808080′);
  85. //Add a hyperlink to the sheet 添加链接

  86. $objPHPExcel->getActiveSheet()->setCellValue(‘E26′, ‘www.phpexcel.net’);
  87. $objPHPExcel->getActiveSheet()->getCell(‘E26′)->getHyperlink()->setUrl(‘http://www.phpexcel.net’);
  88. $objPHPExcel->getActiveSheet()->getCell(‘E26′)->getHyperlink()->setTooltip(‘Navigate to website’);
  89. $objPHPExcel->getActiveSheet()->getStyle(‘E26′)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  90. //Add a drawing to the worksheet 添加图片

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

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

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

  115. $objPHPExcel->getActiveSheet()->setAutoFilter(‘A1:C9′);
  116. //Hide “Phone” and “fax” column 隐藏列

  117. $objPHPExcel->getActiveSheet()->getColumnDimension(‘C’)->setVisible(false);
  118. $objPHPExcel->getActiveSheet()->getColumnDimension(‘D’)->setVisible(false);
  119. //Set document security 设置文档安全

  120. $objPHPExcel->getSecurity()->setLockWindows(true);
  121. $objPHPExcel->getSecurity()->setLockStructure(true);
  122. $objPHPExcel->getSecurity()->setWorkbookPassword(“PHPExcel”);
  123. //Set sheet security 设置工作表安全

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

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

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

  136. $objPHPExcel->getActiveSheet()->freezePane(‘A2′);
  137. //Rows to repeat at top

  138. $objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
  139. //Set data validation 验证输入值

  140. $objValidation = $objPHPExcel->getActiveSheet()->getCell(‘B3′)->getDataValidation();
  141. $objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_WHOLE );
  142. $objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
  143. $objValidation->setAllowBlank(true);
  144. $objValidation->setShowInputMessage(true);
  145. $objValidation->setShowErrorMessage(true);
  146. $objValidation->setErrorTitle(‘Input error’);
  147. $objValidation->setError(‘Number is not allowed!’);
  148. $objValidation->setPromptTitle(‘Allowed input’);
  149. $objValidation->setPrompt(‘Only numbers between 10 and 20 are allowed.’);
  150. $objValidation->setFormula1(10);
  151. $objValidation->setFormula2(20);
  152. $objPHPExcel->getActiveSheet()->getCell(‘B3′)->setDataValidation($objValidation);
  153. //Create a new worksheet, after the default sheet 创建新的工作标签

  154. $objPHPExcel->createSheet(); bbs.it-home.org
  155. $objPHPExcel->setActiveSheetIndex(1);
  156. //Set header and footer. When no different headers for odd/even are used, odd header is assumed. 页眉页脚

  157. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader(‘&C&HPlease treat this document as confidential!’);
  158. $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter(‘&L&B’ . $objPHPExcel->getProperties()->getTitle() . ‘&RPage &P of &N’);
  159. //Set page orientation and size 方向大小

  160. $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
  161. $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
  162. //Rename sheet 重命名工作表标签

  163. $objPHPExcel->getActiveSheet()->setTitle(‘Simple’);
  164. //Set active sheet index to the first sheet, so Excel opens this as the first sheet

  165. $objPHPExcel->setActiveSheetIndex(0);
  166. //Save Excel 2007 file 保存

  167. $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
  168. $objWriter->save(str_replace(‘.php’, ‘.xlsx’, __FILE__));
  169. //Save Excel 5 file 保存

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

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

  178. //Include class
  179. require_once(‘Classes/PHPExcel/Reader/Excel2007.php’);
  180. $objReader = new PHPExcel_Reader_Excel2007;
  181. $objPHPExcel = $objReader->load(“05featuredemo.xlsx”);

  182. //读写csv

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

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

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

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

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

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

  212. require_once(“05featuredemo.inc.php”);
  213. require_once(‘Classes/PHPExcel/IOFactory.php’);
  214. //Write to PDF format

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


Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor