·设为首页收藏本站📧邮箱修改🎁免费下载专区💎积分✅卡密📒收藏夹👽聊天室
返回列表 发布新帖

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

405 1
发表于 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";
复制代码
我要说一句 收起回复
创宇盾启航版免费网站防御网站加速服务

评论1

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
我要说一句 收起回复

回复

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

本版积分规则

创宇盾启航版免费网站防御网站加速服务
投诉/建议联系

discuzaddons@vip.qq.com

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

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

您的IP:3.137.200.139,GMT+8, 2024-12-22 20:42 , Processed in 0.234575 second(s), 84 queries , Gzip On, Redis On.

Powered by Discuz! X5.0 Licensed

© 2001-2024 Discuz! Team.

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