PHPExcel⽤法(详细)
⾸先到phpexcel官⽹上下载最新的phpexcel类,下周解压缩⼀个classes⽂件夹,⾥⾯包含了PHPExcel.php和PHPExcel的⽂件夹,这个类⽂件和⽂件夹是我们需要的,把classes解压到你项⽬的⼀个⽬录中,重名名为phpexcel,开始喽,(代码都摘⾃⾃带实例)
程序部分
require_once'./phpexcel/PHPExcel.php';
// ⾸先创建⼀个新的对象  PHPExcel object
$objPHPExcel =new PHPExcel();
// 设置⽂件的⼀些属性,在xls⽂件——>属性——>详细信息⾥可以看到这些值,xml表格⾥是没有这些值的
$objPHPExcel
->getProperties() //获得⽂件属性对象,给下⽂提供设置资源
-
>setCreator("Maarten Balliauw")                //设置⽂件的创建者
->setLastModifiedBy("Maarten Balliauw")          //设置最后修改者
->setTitle("Office 2007 XLSX Test Document")    //设置标题
->setSubject("Office 2007 XLSX Test Document")  //设置主题
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")//设置备注
->setKeywords("office 2007 openxml php")        //设置标记
->setCategory("Test result file");              //设置类别
// 位置aaa  *为下⽂代码位置提供锚
// 给表格添加数据
$objPHPExcel->setActiveSheetIndex(0)            //设置第⼀个内置表(⼀个xls⽂件⾥可以有多个表)为活动的
->setCellValue('A1','Hello') //给表的单元格设置数据
->setCellValue('B2','world!')      //数据格式可以为字符串
->setCellValue('C1', 12)            //数字型
->setCellValue('D2', 12)            //
->setCellValue('D3',true)          //布尔型
->setCellValue('D4','=SUM(C1:D2)');//公式
//得到当前活动的表,注意下⽂教程中会经常⽤到$objActSheet
$objActSheet = $objPHPExcel->getActiveSheet();
// 位置bbb  *为下⽂代码位置提供锚
// 给当前活动的表设置名称
$objActSheet->setTitle('Simple2222');
代码还没有结束,可以复制下⾯的代码来决定我们将要做什么
我们将要做的是
1,直接⽣成⼀个⽂件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
$objWriter->save('myexchel.xlsx');
2、提⽰下载⽂件
excel 2003 .xls
// ⽣成2003excel格式的xls⽂件
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
$objWriter->save('php://output');
exit;
excel 2007 .xlsx
// ⽣成2007excel格式的xlsx⽂件
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
$objWriter= PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
$objWriter->save('php://output');
exit;
pdf ⽂件
/
/ 下载⼀个pdf⽂件
header('Content-Type: application/pdf');
header('Content-Disposition: attachment;filename="01simple.pdf"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'PDF');
$objWriter->save('php://output');
exit;
// ⽣成⼀个pdf⽂件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'PDF');
$objWriter->save('a.pdf');
CSV ⽂件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'CSV')->setDelimiter(',')  //设置分隔符
->setEnclosure('"')    //设置包围符
->setLineEnding("\r\n")//设置⾏分隔符
->setSheetIndex(0)      //设置活动表
->save(str_replace('.php','.csv', __FILE__));
HTML ⽂件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');      //将$objPHPEcel对象转换成html格式的
$objWriter->setSheetIndex(0); //设置活动表
//$objWriter->setImagesRoot('ample');
$objWriter->save(str_replace('.php','.htm', __FILE__));    //保存⽂件
设置表格样式和数据格式
设置默认的字体和⽂字⼤⼩锚:aaa
$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
$objPHPExcel->getDefaultStyle()->getFont()->setSize(20);
⽇期格式锚:bbb
//获得秒值变量
$dateTimeNow = time();
//三个表格分别设置为当前实际的⽇期格式、时间格式、⽇期和时间格式
//⾸先将单元格的值设置为由PHPExcel_Shared_Date::PHPToExcel⽅法转换后的excel格式的值,然后⽤过得到该单元格的样式⾥⾯数字样式再设置显⽰格式$objActSheet->setCellValue('C9', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow ));
$objActSheet->getStyle('C9')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
$objActSheet->setCellValue('C10', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow ));
$objActSheet->getStyle('C10')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4);
$objActSheet->setCellValue('C10', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow ));
$objActSheet->getStyle('C10')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4);
//将E4到E13的数字格式设置为EUR
$objPHPExcel->getActiveSheet()->getStyle('E4:E13')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);
设置列的宽度锚:bbb
$objActSheet->getColumnDimension('B')->setAutoSize(true);  //内容⾃适应
$objActSheet->getColumnDimension('A')->setWidth(30);        //30宽
设置⽂件打印的页眉和页脚锚:bbb
//设置打印时候的页眉页脚(设置完了以后可以通过打印预览来看效果)字符串中的&*好像是⼀些变量
$objActSheet->getHeaderFooter()->setOddHeader('&L&G&C&HPlease treat this document as confidential!');
$objActSheet->getHeaderFooter()->setOddFooter('&L&B'. $objPHPExcel->getProperties()->getTitle() .'&RPage &P of &N');
设置页⾯⽂字的⽅向和页⾯⼤⼩锚:bbb
$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);    //A4纸⼤⼩
为页眉添加图⽚    office中有效 wps中⽆效锚:bbb
$objDrawing =new PHPExcel_Worksheet_HeaderFooterDrawing();
$objDrawing->setName('PHPExcel logo');
$objDrawing->setPath('./images/phpexcel_logo.gif');
$objDrawing->setHeight(36);
$objPHPExcel->getActiveSheet()->getHeaderFooter()->addImage($objDrawing, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);
设置单元格的批注锚:bbb
//给单元格添加批注
$objPHPExcel->getActiveSheet()->getComment('E13')->setAuthor('PHPExcel');    //设置作者
$objCommentRichText = $objPHPExcel->getActiveSheet()->getComment('E13')->getText()->createTextRun('PHPExcel:'); //添加批注$objCommentRichText->getFont()->setBold(true);  //将现有批注加粗
$objPHPExcel->getActiveSheet()->getComment('E13')->getText()->createTextRun("\r\n");      //添加更多批注
$objPHPExcel->getActiveSheet()->getComment('E13')->getText()->createTextRun('Total amount on the current invoice, including VAT.');
$objPHPExcel->getActiveSheet()->getComment('E13')->setWidth('100pt');      //设置批注显⽰的宽⾼,在office中有效在wps中⽆效
$objPHPExcel->getActiveSheet()->getComment('E13')->setHeight('100pt');
$objPHPExcel->getActiveSheet()->getComment('E13')->setMarginLeft('150pt');
$objPHPExcel->getActiveSheet()->getComment('E13')->getFillColor()->setRGB('EEEEEE');      //设置背景⾊,在office中有效在wps中⽆效
合并拆分单元格锚:bbb
$objPHPExcel->getActiveSheet()->mergeCells('A28:B28');      // A28:B28合并
$objPHPExcel->getActiveSheet()->unmergeCells('A28:B28');    // A28:B28再拆分
单元格密码保护锚:bbb
// 单元格密码保护不让修改
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);  // 为了使任何表保护,需设置为真
$objPHPExcel->getActiveSheet()->protectCells('A3:E13','PHPExcel');// 将A3到E13保护加密密码是 PHPExcel
$objPHPExcel->getActiveSheet()->getStyle('B1')->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);//去掉保护
设置单元格字体锚:bbb
/
/将B1的⽂字字体设置为Candara,20号的粗体下划线有背景⾊
$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);
⽂字对齐⽅式锚:bbb
$objPHPExcel->getActiveSheet()->getStyle('D11')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);  //⽔平⽅向上对齐$objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);//⽔平⽅向上两端对齐$objPH
PExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);      //垂直⽅向上中间居中设置单元格边框锚:bbb
$styleThinBlackBorderOutline =array(
'borders'=>array(
'outline'=>array(
'style'=> PHPExcel_Style_Border::BORDER_THIN,  //
//'style'=> PHPExcel_Style_Border::BORDER_THICK,  另⼀种样式
'color'=>array('argb'=>'FF000000'),          //设置border颜⾊
getsavefilename
),
),
);
$objPHPExcel->getActiveSheet()->getStyle('A4:E10')->applyFromArray($styleThinBlackBorderOutline);
背景填充颜⾊锚:bbb
//设置填充的样式和背景⾊
$objPHPExcel->getActiveSheet()->getStyle('A1:E1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objPHPExcel->getActiveSheet()->getStyle('A1:E1')->getFill()->getStartColor()->setARGB('FF808080');
综合设置样例
$objPHPExcel->getActiveSheet()->getStyle('A3:E3')->applyFromArray(
给单元格内容设置url超链接锚:bbb
$objActSheet->getCell('E26')->getHyperlink()->setUrl( 'www.phpexcel');    //超链接url地址
$objActSheet->getCell('E26')->getHyperlink()->setTooltip('Navigate to website');  //⿏标移上去连接提⽰信息
给表中添加图⽚锚:bbb
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Paid');
$objDrawing->setDescription('Paid');
$objDrawing->setPath('./images/paid.png');//图⽚引⼊位置
$objDrawing->setCoordinates('B15');//图⽚添加位置
$objDrawing->setOffsetX(210);
$objDrawing->setRotation(25);
$objDrawing->setHeight(36);
$objDrawing->getShadow()->setVisible(true);
$objDrawing->getShadow()->setDirection(45);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
//还可以添加有gd库⽣产的图⽚,详细见⾃带实例25
创建⼀个新⼯作表和设置⼯作表标签颜⾊锚:bbb
$objExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(1);  //设置第2个表为活动表,提供操作句柄
$objExcel->getSheet(1)->setTitle('测试2');  //直接得到第⼆个表进⾏设置,将⼯作表重新命名为测试2
$objPHPExcel->getActiveSheet()->getTabColor()->setARGB('FF0094FF');    //设置标签颜⾊
添加或删除⾏和列锚:bbb
$objPHPExcel->getActiveSheet()->insertNewRowBefore(6, 10);  //在⾏6前添加10⾏
$objPHPExcel->getActiveSheet()->removeRow(6, 10);                //从第6⾏往后删去10⾏
$objPHPExcel->getActiveSheet()->insertNewColumnBefore('E', 5);    //从第E列前添加5类
$objPHPExcel->getActiveSheet()->removeColumn('E', 5);            //从E列开始往后删去5列
隐藏和显⽰某列锚:bbb
$objPHPExcel->getActiveSheet()->getColumnDimension( 'C')->setVisible(false);          //隐藏
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setVisible(true);          //显⽰
重新命名活动的表的标签名称锚:bbb
$objPHPExcel->getActiveSheet()->setTitle('Invoice');
设置⼯作表的安全
$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);
设置⽂档安全锚:bbb
$objPHPExcel->getSecurity()->setLockWindows(true);
$objPHPExcel->getSecurity()->setLockStructure(true);
$objPHPExcel->getSecurity()->setWorkbookPassword("PHPExcel");    //设置密码
样式复制锚:bbb
//将B2的样式复制到B3⾄B7
$objPHPExcel->getActiveSheet()->duplicateConditionalStyle(
$objPHPExcel->getActiveSheet()->getStyle('B2')->getConditionalStyles(),
'B3:B7'
);
Add conditional formatting    锚:bbb
echo date('H:i:s') ," Add conditional formatting", PHP_EOL;
$objConditional1 =new PHPExcel_Style_Conditional();
$objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);
$objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_BETWEEN);
$objConditional1->addCondition('200');
$objConditional1->addCondition('400');
设置分页(主要⽤于打印)锚:bbb
//设置某单元格为页尾
$objPHPExcel->getActiveSheet()->setBreak('A'. $i, PHPExcel_Worksheet::BREAK_ROW);
⽤数组填充表锚:bbb
/
/吧数组的内容从A2开始填充
$dataArray = array( array("2010" ,    "Q1",  "United States",  790),
array("2010",    "Q2", "United States",  730),
);
$objPHPExcel->getActiveSheet()->fromArray($dataArray,NULL,'A2');
设置⾃动筛选锚:bbb
$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension());
//$objPHPExcel->getActiveSheet()->calculateWorksheetDimension()....得到A1⾏的所有内容个
打印出的到所有的公式
$objCalc = PHPExcel_Calculation::getInstance();
print_r($objCalc->listFunctionNames())
设置单元格值的范围锚:bbb
$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->setShowDropDown(true);
$objValidation->setError('Only numbers between 10 and 20 are allowed!');      //错误内容
$objValidation->setPromptTitle('Allowed input');      //设置提⽰标题
$objValidation->setPrompt('Only numbers between 10 and 20 are allowed.'); //提⽰内容
$objValidation->setFormula1(10);    //设置最⼤值
$objValidation->setFormula2(120);  //设置最⼩值
//或者这样设置  $objValidation->setFormula2(1,5,6,7);  设置值是1,5,6,7中的⼀个数
其他
$objPHPExcel->getActiveSheet()->getStyle('B5')->getAlignment()->setShrinkToFit(true);//长度不够显⽰的时候是否⾃动换⾏
$objPHPExcel->getActiveSheet()->getStyle('B5')->getAlignment()->setShrinkToFit(true);//⾃动转换显⽰字体⼤⼩,使内容能够显⽰
$objPHPExcel->getActiveSheet()->getCell(B14)->getValue();        //获得值,有可能得到的是公式
$objPHPExcel->getActiveSheet()->getCell(B14)->getCalculatedValue();//获得算出的值
导⼊或读取⽂件
//通过PHPExcel_IOFactory::load⽅法来载⼊⼀个⽂件,load会⾃动判断⽂件的后缀名来导⼊相应的处理类,读取格式保含xlsx/xls/xlsm/ods/slk/csv/xml/gnumeric require_once'../Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load(
//吧载⼊的⽂件默认表(⼀般都是第⼀个)通过toArray⽅法来返回⼀个多维数组
$dataArray = $objPHPExcel->getActiveSheet()->toArray();

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。