代码:
<?php
// 创建文件
$dir=dirname(__FILE__); //找到当前脚本所在路径
require $dir."./PHPExcel-1.8/Classes/PHPExcel.php"; //引入文件
$objPHPExcel=new PHPExcel(); //实例化PHPExcel类
$objSheet=$objPHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
/**
* 设置单元格格式
*/
// 文本居中
$objSheet->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
// 合并单元格
$objSheet->mergeCells("A3:D6");
// 设置字体
$objSheet->getDefaultStyle()->getFont()->setName('Arial')->setSize(18)->setBold(true);
// 文本保留两位小数
// $llv2=sprintf("%.2f",123);
$llv2=123;
$objSheet->getStyle('E7')->getNumberFormat()->setFormatCode('0.000');
$objSheet->setCellValue('E7',$llv2,PHPExcel_Cell_DataType::TYPE_STRING);
// 设置边框
$style_array = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objSheet->getStyle('A1:D20')->applyFromArray($style_array);
// 填充数据
$objSheet->setTitle('demo');
$objSheet->setCellValue('A1','姓名')->setCellValue('B1','分数'); //填充数据
$objSheet->setCellValue('A2','张三')->setCellValue('B2','50');
$objWrite=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
// 保存文件(到服务器)
$objWrite->save($dir.'/demo.xlsx');