PHPExcel简易使用教程

在企业里使用PHP进行开发,不可避免总会遇到读/写Excel的需求,遇到这种需求,一般使用PHPExcel类库进行开发。

PHPExcel现在最新版本是1.8.0,最低需要PHP5.2版本,支持读取xls、xlsx、csv等常用的excel格式,下载地址http://phpexcel.codeplex.com/releases/view/119187

1.读取Excel文件

 1 require __DIR__ . '/PHPExcel.php';
 2 
 3 $excelReader = PHPExcel_IOFactory::createReader('Excel2007');//设定读取格式
 4 $excel = $excelReader->load(__DIR__ . '/Quadratic.xlsx');//设定读取文件
 5 $sheet = $excel->setActiveSheetIndex(0);//设定excel工作簿
 6 foreach ($sheet->getRowIterator(1) as $row) {
 7     //读取行,从第1行
 8     var_dump('row:' . $row->getRowIndex());//读取行号
 9     $cellIterator = $row->getCellIterator();
10     foreach ($cellIterator as $cell) {
11         //读取单元格
12         var_dump($cell->getColumn());//获取列名
13         var_dump($cell->getCoordinate());//获取坐标
14         var_dump($cell->getRow());//获取所在行号
15         var_dump($cell->isFormula());//判断值是否为公式
16         var_dump($cell->getValue());//获取值
17     }
18 }

2.写入Excel文件

 1 $excel = new PHPExcel();
 2 $sheet = $excel->setActiveSheetIndex('0');//设定写入的工作簿
 3 //写入数据
 4 for ($row = 0; $row < 10; $row++) {
 5     for ($cell = 0; $cell < 5; $cell++) {
 6         $sheet->setCellValueByColumnAndRow($cell, $row, "row:{$row} col:{$cell}");
 7     }
 8 }
 9 $excelWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');//设定保存格式
10 $excelWriter->save(__DIR__ . '/excel_test.xlsx');//保存文件

3.生成Excel并开始下载

 1 $excel = new PHPExcel();
 2 $sheet = $excel->setActiveSheetIndex('0');//设定写入的工作簿
 3 //写入数据
 4 for ($row = 0; $row < 10; $row++) {
 5     for ($cell = 0; $cell < 5; $cell++) {
 6         $sheet->setCellValueByColumnAndRow($cell, $row, "row:{$row} col:{$cell}");
 7     }
 8 }
 9 $excelWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');//设定保存格式
10 //开始输出内容至浏览器
11 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
12 header('Content-Disposition: attachment;filename="01simple.xlsx"');
13 header('Cache-Control: max-age=0');
14 header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
15 header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
16 header ('Cache-Control: cache, must-revalidate');
17 header ('Pragma: public');
18 $excelWriter->save('php://output');//输出文件
原文地址:https://www.cnblogs.com/koboshi/p/4052022.html