使用PHPExcel操作Excel用法实例分析


Posted in PHP onMarch 26, 2015

本文实例分析了使用PHPExcel操作Excel用法。分享给大家供大家参考。具体分析如下:

PHPExcel下载地址:
http://www.codeplex.com/PHPExcel
http://www.phpexcel.net
开发包Tests目录有详细使用实例  支持中文,注意文件编码   文件保存为utf-8

1.header部分:

header("Content-Type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=sample.xls"); 
header("Pragma:no-cache"); 
header("Expires:0");

2.写excel:

//Include class 
require_once('Classes/PHPExcel.php'); 
require_once('Classes/PHPExcel/Writer/Excel2007.php'); 
$objPHPExcel = new PHPExcel(); 
 
//Set properties 设置文件属性 
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw"); 
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw"); 
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document"); 
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document"); 
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes."); 
$objPHPExcel->getProperties()->setKeywords("office 2007 openxml php"); 
$objPHPExcel->getProperties()->setCategory("Test result file"); 
 
//Add some data 添加数据 
$objPHPExcel->setActiveSheetIndex(0); 
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello');//可以指定位置 
$objPHPExcel->getActiveSheet()->setCellValue('A2', true); 
$objPHPExcel->getActiveSheet()->setCellValue('A3', false); 
$objPHPExcel->getActiveSheet()->setCellValue('B2', 'world!'); 
$objPHPExcel->getActiveSheet()->setCellValue('B3', 2); 
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'Hello'); 
$objPHPExcel->getActiveSheet()->setCellValue('D2', 'world!'); 
 
//循环 
for($i = 1;$i<200;$i++) { 
$objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $i); 
$objPHPExcel->getActiveSheet()->setCellValue('B' . $i, 'Test value'); 
} 
 
//日期格式化 
$objPHPExcel->getActiveSheet()->setCellValue('D1', time()); 
$objPHPExcel->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH); 
 
//Add comment 添加注释 
$objPHPExcel->getActiveSheet()->getComment('E11')->setAuthor('PHPExcel'); 
$objCommentRichText = $objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun('PHPExcel:'); 
$objCommentRichText->getFont()->setBold(true); 
$objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun("\r\n"); 
$objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun('Total amount on the current invoice, excluding VAT.'); 
 
//Add rich-text string 添加文字 可设置样式 
$objRichText = new PHPExcel_RichText( $objPHPExcel->getActiveSheet()->getCell('A18') ); 
$objRichText->createText('This invoice is '); 
$objPayable = $objRichText->createTextRun('payable within thirty days after the end of the month'); 
$objPayable->getFont()->setBold(true); 
$objPayable->getFont()->setItalic(true); 
$objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) ); 
$objRichText->createText(', unless specified otherwise on the invoice.'); 
 
//Merge cells 合并分离单元格 
$objPHPExcel->getActiveSheet()->mergeCells('A18:E22'); 
$objPHPExcel->getActiveSheet()->unmergeCells('A18:E22'); 
 
//Protect cells 保护单元格 
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);//Needs to be set to true in order to enable any worksheet protection! 
$objPHPExcel->getActiveSheet()->protectCells('A3:E13', 'PHPExcel'); 
 
//Set cell number formats 数字格式化 
$objPHPExcel->getActiveSheet()->getStyle('E4')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE); 
$objPHPExcel->getActiveSheet()->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('E4'), 'E5:E13' ); 
 
//Set column widths 设置列宽度 
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); 
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12); 
 
//Set fonts 设置字体 
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara'); 
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(20); 
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true); 
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); 
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE); 
 
//Set alignments 设置对齐 
$objPHPExcel->getActiveSheet()->getStyle('D11')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
$objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY); 
$objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); 
$objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setWrapText(true); 
 
//Set column borders 设置列边框 
$objPHPExcel->getActiveSheet()->getStyle('A4')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 
$objPHPExcel->getActiveSheet()->getStyle('A10')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 
$objPHPExcel->getActiveSheet()->getStyle('E10')->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK); 
$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK); 
 
//Set border colors 设置边框颜色 
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->getColor()->setARGB('FF993300'); 
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getTop()->getColor()->setARGB('FF993300'); 
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getBottom()->getColor()->setARGB('FF993300'); 
$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getRight()->getColor()->setARGB('FF993300'); 
 
//Set fills 设置填充 
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID); 
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB('FF808080'); 
 
//Add a hyperlink to the sheet 添加链接 
$objPHPExcel->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net'); 
$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('http://www.phpexcel.net'); 
$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()->setTooltip('Navigate to website'); 
$objPHPExcel->getActiveSheet()->getStyle('E26')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); 
 
//Add a drawing to the worksheet 添加图片 
$objDrawing = new PHPExcel_Worksheet_Drawing(); 
$objDrawing->setName('Logo'); 
$objDrawing->setDescription('Logo'); 
$objDrawing->setPath('./images/officelogo.jpg'); 
$objDrawing->setHeight(36); 
$objDrawing->setCoordinates('B15'); 
$objDrawing->setOffsetX(110); 
$objDrawing->setRotation(25); 
$objDrawing->getShadow()->setVisible(true); 
$objDrawing->getShadow()->setDirection(45); 
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); 
 
//Play around with inserting and removing rows and columns 
$objPHPExcel->getActiveSheet()->insertNewRowBefore(6, 10); 
$objPHPExcel->getActiveSheet()->removeRow(6, 10); 
$objPHPExcel->getActiveSheet()->insertNewColumnBefore('E', 5); 
$objPHPExcel->getActiveSheet()->removeColumn('E', 5); 
 
//Add conditional formatting 
$objConditional1 = new PHPExcel_Style_Conditional(); 
$objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS); 
$objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN); 
$objConditional1->setCondition('0'); 
$objConditional1->getStyle()->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED); 
$objConditional1->getStyle()->getFont()->setBold(true); 
 
//Set autofilter 自动过滤 
$objPHPExcel->getActiveSheet()->setAutoFilter('A1:C9'); 
 
//Hide "Phone" and "fax" column 隐藏列 
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setVisible(false); 
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setVisible(false); 
 
//Set document security 设置文档安全 
$objPHPExcel->getSecurity()->setLockWindows(true); 
$objPHPExcel->getSecurity()->setLockStructure(true); 
$objPHPExcel->getSecurity()->setWorkbookPassword("PHPExcel"); 
 
//Set sheet security 设置工作表安全 
$objPHPExcel->getActiveSheet()->getProtection()->setPassword('PHPExcel'); 
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);// This should be enabled in order to enable any of the following! 
$objPHPExcel->getActiveSheet()->getProtection()->setSort(true); 
$objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true); 
$objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true); 
 
//Calculated data 计算 
echo 'Value of B14 [=COUNT(B2:B12)]: ' . $objPHPExcel->getActiveSheet()->getCell('B14')->getCalculatedValue() . "\r\n"; 
 
//Set outline levels 
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1); 
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setVisible(false); 
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setCollapsed(true); 
 
//Freeze panes 
$objPHPExcel->getActiveSheet()->freezePane('A2'); 
 
//Rows to repeat at top 
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1); 
 
//Set data validation 验证输入值 
$objValidation = $objPHPExcel->getActiveSheet()->getCell('B3')->getDataValidation(); 
$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_WHOLE ); 
$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
$objValidation->setAllowBlank(true);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setErrorTitle('Input error');
$objValidation->setError('Number is not allowed!');
$objValidation->setPromptTitle('Allowed input');
$objValidation->setPrompt('Only numbers between 10 and 20 are allowed.'); 
$objValidation->setFormula1(10);
$objValidation->setFormula2(20);
$objPHPExcel->getActiveSheet()->getCell('B3')->setDataValidation($objValidation);
 
//Create a new worksheet, after the default sheet 创建新的工作标签
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(1);
 
//Set header and footer. When no different headers for odd/even are used, odd header is assumed. 页眉页脚
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader('&C&HPlease treat this document as confidential!');
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N');
 
//Set page orientation and size 方向大小
$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
 
//Rename sheet 重命名工作表标签 
$objPHPExcel->getActiveSheet()->setTitle('Simple');
 
//Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
 
//Save Excel 2007 file 保存 
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
 
//Save Excel 5 file 保存 
require_once('Classes/PHPExcel/Writer/Excel5.php'); 
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel); 
$objWriter->save(str_replace('.php', '.xls', __FILE__));
 
//1.6.2新版保存 
require_once('Classes/PHPExcel/IOFactory.php');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 
$objWriter->save(str_replace('.php', '.xls', __FILE__));

3.读excel

//Include class 
require_once('Classes/PHPExcel/Reader/Excel2007.php'); 
$objReader = new PHPExcel_Reader_Excel2007; 
$objPHPExcel = $objReader->load("05featuredemo.xlsx");

4.读写csv

require_once("05featuredemo.inc.php");
require_once('Classes/PHPExcel/Writer/CSV.php');
require_once('Classes/PHPExcel/Reader/CSV.php');
require_once('Classes/PHPExcel/Writer/Excel2007.php'); 
//Write to CSV format 写 
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->setDelimiter(';'); 
$objWriter->setEnclosure(''); 
$objWriter->setLineEnding("\r\n"); 
$objWriter->setSheetIndex(0); 
$objWriter->save(str_replace('.php', '.csv', __FILE__));
//Read from CSV format 读 
$objReader = new PHPExcel_Reader_CSV();
$objReader->setDelimiter(';'); 
$objReader->setEnclosure(''); 
$objReader->setLineEnding("\r\n");
$objReader->setSheetIndex(0); 
$objPHPExcelFromCSV = $objReader->load(str_replace('.php', '.csv', __FILE__));
//Write to Excel2007 format 
$objWriter2007 = new PHPExcel_Writer_Excel2007($objPHPExcelFromCSV);
$objWriter2007->save(str_replace('.php', '.xlsx', __FILE__));

5.写html

require_once("05featuredemo.inc.php"); 
require_once('Classes/PHPExcel/Writer/HTML.php');
//Write to HTML format 
$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
$objWriter->setSheetIndex(0); 
$objWriter->save(str_replace('.php', '.htm', __FILE__));

6.写pdf

require_once("05featuredemo.inc.php");
require_once('Classes/PHPExcel/IOFactory.php');
//Write to PDF format
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->setSheetIndex(0);
$objWriter->save(str_replace('.php', '.pdf', __FILE__));
//Echo memory peak usage
echo date('H:i:s')." Peak memory usage: ".(memory_get_peak_usage(true) / 1024 / 1024)." MB\r\n";

 
希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
生成静态页面的PHP类
Nov 25 PHP
php中用文本文件做数据库的实现方法
Mar 27 PHP
PHP 判断常量,变量和函数是否存在
Apr 26 PHP
PHP定时执行计划任务的多种方法小结
Dec 19 PHP
php数组删除元素示例
Mar 21 PHP
php中array_column函数简单实现方法
Jul 11 PHP
如何使用PHP给图片加水印
Oct 12 PHP
PHP环形链表实现方法示例
Sep 15 PHP
PHP的curl函数的用法总结
Feb 14 PHP
Yii框架日志操作图文与实例详解
Sep 09 PHP
Laravel框架Eloquent ORM简介、模型建立及查询数据操作详解
Dec 04 PHP
如何用PHP实现分布算法之一致性哈希算法
May 26 PHP
mysql_connect localhost和127.0.0.1的区别(网络层阐述)
Mar 26 #PHP
php实现RSA加密类实例
Mar 26 #PHP
PHP中实现crontab代码分享
Mar 26 #PHP
PHP利用hash冲突漏洞进行DDoS攻击的方法分析
Mar 26 #PHP
ThinkPHP、ZF2、Yaf、Laravel框架路由大比拼
Mar 25 #PHP
CentOS 安装 PHP5.5+Redis+XDebug+Nginx+MySQL全纪录
Mar 25 #PHP
MacOS 安装 PHP的图片裁剪扩展Tclip
Mar 25 #PHP
You might like
如何在PHP中使用Oracle数据库(2)
2006/10/09 PHP
字母顺序颠倒而单词顺序不变的php代码
2010/08/08 PHP
Ajax提交表单时验证码自动验证 php后端验证码检测
2016/07/20 PHP
Thinkphp5.0 框架的请求方式与响应方式分析
2019/10/14 PHP
js滚动条回到顶部的代码
2011/12/06 Javascript
再谈javascript面向对象编程
2012/03/18 Javascript
js split 的用法和定义 js split分割字符串成数组的实例代码
2012/05/13 Javascript
关于jQuery中.attr()和.prop()的问题探讨
2013/09/06 Javascript
css如何让浮动元素水平居中
2015/08/07 Javascript
jquery插件jquery.beforeafter.js实现左右拖拽分隔条对比图片的方法
2015/08/07 Javascript
jQuery实现的左右移动焦点图效果
2016/01/14 Javascript
功能强大的Bootstrap使用手册(一)
2016/08/02 Javascript
关于vue.js弹窗组件的知识点总结
2016/09/11 Javascript
JS中利用localStorage防止页面动态添加数据刷新后数据丢失
2017/03/10 Javascript
JS从非数组对象转数组的方法小结
2018/03/26 Javascript
JavaScript作用域、闭包、对象与原型链概念及用法实例总结
2018/08/20 Javascript
JS数组求和的常用方法总结【5种方法】
2019/01/14 Javascript
使用taro开发微信小程序遇到的坑总结
2019/04/08 Javascript
vue.js实现二级菜单效果
2019/10/19 Javascript
微信小程序弹窗禁止页面滚动的实现代码
2020/12/30 Javascript
go和python调用其它程序并得到程序输出
2014/02/10 Python
python中的reduce内建函数使用方法指南
2014/08/31 Python
Python装饰器使用示例及实际应用例子
2015/03/06 Python
使用python在本地电脑上快速处理数据
2017/06/22 Python
OPENCV去除小连通区域,去除孔洞的实例讲解
2018/06/21 Python
Python中最大递归深度值的探讨
2019/03/05 Python
Python任务调度利器之APScheduler详解
2020/04/02 Python
python 字典item与iteritems的区别详解
2020/04/25 Python
Python smtp邮件发送模块用法教程
2020/06/15 Python
W Concept美国:精选全球独立设计师
2017/02/22 全球购物
潘多拉珠宝美国官方网站:Pandora US
2020/06/18 全球购物
技校教师求职简历的自我评价
2013/10/20 职场文书
物流管理毕业生自荐信
2013/10/24 职场文书
高中生毕业学习总结的自我评价
2013/11/14 职场文书
幼教个人求职信范文
2013/12/02 职场文书
创建精神文明单位实施方案
2014/03/08 职场文书