最近找到一个不错的套件PHPExcel,这个套件解决我数据汇出的问题,以往我在汇出数据都是采用CSV文件,此种方法最简单,只要用逗号隔开就可轻易的汇出档案,但此种方法也有着很多的缺点,以下列举几个我比较常发生的缺点: 1.只能用于BIG5编码 2.数字前面为0,用excel
最近找到一个不错的套件PHPExcel,这个套件解决我数据汇出的问题,以往我在汇出数据都是采用CSV文件,此种方法最简单,只要用”逗号”隔开就可轻易的汇出档案,但此种方法也有着很多的缺点,以下列举几个我比较常发生的缺点:
1.只能用于BIG5编码
2.数字前面为0,用excel 开启0会自动消失
3.如果是UTF8汇出,在转成BIG5时,容易找不到对应的字符,而产生乱码
4.汇出的内容有逗号需全部转为全型,否则档案的字段会乱掉
说了这么多缺点,汇出成CSV真的不好吗?其实见人见智啦!如果使用时,能避开容易出问题的地方,其实CSV又快又简单,废话说了一堆,回到正题吧!
PHPExcel官网:http://www.codeplex.com/PHPExcel
PHPExcel下载:http://phpexcel.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=10717
如果在windows下载下来就可直接使用,在linux还需要安装ZipArchive,仅提供CentOS安装方法请参考:
[Linux]CentOS解决Fatal error: Class ‘ZipArchive’ not found in问题
PHPExcel汇出设定档说明如下:(此档案需放在Classes里面)
<?PHP
include ‘PHPExcel.php’;
/** PHPExcel_Writer_Excel2007 */
//include ‘PHPExcel/Writer/Excel2007.php’;
/** Error reporting */
error_reporting(E_ALL);
/** PHPExcel */
require_once ‘../Classes/PHPExcel.php’;
/** PHPExcel_IOFactory */
require_once ‘../Classes/PHPExcel/IOFactory.php’;
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
//合并储存隔
$objPHPExcel->getActiveSheet()->mergeCells(‘A1:D2′);
//设定渐层背景颜色双色(灰/白)
$objPHPExcel->getActiveSheet()->getStyle(‘A1:D2′)->applyFromArray(
array(
‘font’ => array(
‘bold’ => true
),
‘alignment’ => array(
‘horizontal’ => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
‘borders’ => array(
‘top’ => array(
’style’ => PHPExcel_Style_Border::BORDER_THIN
)
),
‘fill’ => array(
‘type’ => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
‘rotation’ => 90,
’startcolor’ => array(
‘rgb’ => ‘DCDCDC’
),
‘endcolor’ => array(
‘rgb’ => ‘FFFFFF’
)
)
)
);
//设定字号
$objPHPExcel->getActiveSheet()->getStyle(‘A1′)->getFont()->setSize(16);
//设定A1字段显示文字PHPEXCEL TEST
$objPHPExcel->getActiveSheet()->setCellValue(‘A1′,’PHPEXCEL TEST’);
//设定字体颜色
//$objPHPExcel->getActiveSheet()->getStyle(‘A1′)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLUE);
//设定背景颜色单色
$objPHPExcel->getActiveSheet()->getStyle(‘A3:D3′)->applyFromArray(
array(‘fill’ => array(
‘type’ => PHPExcel_Style_Fill::FILL_SOLID,
‘color’ => array(‘rgb’ => ‘D1EEEE’)
),
)
);
//设定字段值
$objPHPExcel->getActiveSheet()->setCellValue(‘A3′,’test1′);
$objPHPExcel->getActiveSheet()->setCellValue(‘B3′,’test2′);
$objPHPExcel->getActiveSheet()->setCellValue(‘C3′,’test3′);
$objPHPExcel->getActiveSheet()->setCellValue(‘D3′,’test4′);
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle(sheet);
//设定的字段宽度(自动)
$objPHPExcel->getActiveSheet()->getColumnDimension(‘A’)->setAutoSize(true);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Export to Excel2007 (.xlsx) 汇出成2007
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007′);
$objWriter->save(‘test.xlsx’);
// Export to Excel5 (.xls) 汇出成2003
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5′);
$objWriter->save(‘test.xls’);
?>
延伸阅读:php excel类phpExcel使用方法