PHP通过PHPExcel类导入导出excel
PHPExcel 是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言,可以使用它来读取、写入不同格式的电子表格.
导出类:PHPExcel类导出excel,同时对PHPExcel做了些精简处理,基本上可以满足数据导出excel的功能,代码如下:
- 代码如下 复制代码
-
- require './phpexcel/PHPExcel.php';
-
-
- $objPHPExcel = new PHPExcel();
-
-
- $objProps = $objPHPExcel->getProperties();
- $objProps->setCreator("Lao Mao");
- $objProps->setLastModifiedBy("Lao Mao");
- $objProps->setTitle("Office XLS Test Document");
- $objProps->setSubject("Office XLS Test Document, Demo");
- $objProps->setDescription("Test document, generated by PHPExcel.");
- $objProps->setKeywords("office excel PHPExcel");
- $objProps->setCategory("Test");
-
-
-
-
- $objPHPExcel->setActiveSheetIndex(0);
-
-
- $objActSheet = $objPHPExcel->getActiveSheet();
- $objActSheet->setTitle('测试Sheet');
-
-
- $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'a1');
- $objPHPExcel->getActiveSheet()->SetCellValue('A2', 'a2');
- $objPHPExcel->getActiveSheet()->SetCellValue('A3', 'a3');
- $objPHPExcel->getActiveSheet()->SetCellValue('A4', 'a4');
- $objPHPExcel->getActiveSheet()->SetCellValue('A5', 'a5');
-
- $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'b1');
- $objPHPExcel->getActiveSheet()->SetCellValue('B2', 'b2');
- $objPHPExcel->getActiveSheet()->SetCellValue('B3', 'b3');
- $objPHPExcel->getActiveSheet()->SetCellValue('B4', 'b4');
- $objPHPExcel->getActiveSheet()->SetCellValue('B5', 'b5');
-
- $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'c1');
- $objPHPExcel->getActiveSheet()->SetCellValue('C2', 'c2');
- $objPHPExcel->getActiveSheet()->SetCellValue('C3', 'c3');
- $objPHPExcel->getActiveSheet()->SetCellValue('C4', 'c4');
- $objPHPExcel->getActiveSheet()->SetCellValue('C5', 'c5');
-
-
- $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
-
-
-
-
-
-
-
-
- $objWriter->save(dirname(__FILE__) . '/demo.xls');
导入excel的方法,代码:
-
- include(dirname(__FILE__).'/phpexcel/PHPExcel.php');
-
- $Obj = new PHPExcel_Reader_Excel5();
- $Obj->setReadDataOnly(true);
-
-
- $phpExcel = $Obj->load(dirname(__FILE__).'/output.xls');
-
-
- $objWorksheet = $phpExcel->getActiveSheet();
-
-
- $highestRow = $objWorksheet->getHighestRow();
-
-
- $highestColumn = $objWorksheet->getHighestColumn();
- $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
-
-
- $data = array();
- for($row = 1; $row <= $highestRow; ++$row) {
- for($col = 0; $col < $highestColumnIndex; ++$col) {
- $val = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
- $data[$row][$col] = trim($val);
- }
- }
-
- echo '<pre>';
- print_r($data);
- echo '</pre>';
但是这种方式有缺陷,老版本的excel有个数据上限,最多65536行数据,这时我们就无法通过excel来实现大数据的导出, 但我估计也没几个有这么多数据吧,当然如果有可以考虑使用csv来操作.