php处理Excel

## 遇到问题 平时在工作中,时常会出现将数据库表导出为Excel或者将Excel导入数据库表的需求。这一需求早早就已经实现过了,为了方便导入导出,我将其封装成了两个方法,作为记录。 ## 代码实现 ### phpexcel类库的引用 phpexcel拥有强大的Excel处理能力,在[packagist](https://packagist.org/)上已经拥有数百万次的下载量,不过实话实说,excel的处理速度仍然是非常慢,数据量较大时慎重使用。在[packagist](https://packagist.org/packages/phpoffice/phpexcel)上下载或者直接用`composer require phpoffice/phpexcel`之后,便可以使用phpexcel了。 ## 导出成为Excel 在绝大多数情况下,导出excel其实就是将二位数组转化为表格。 use namespace PHPExcel; /** * @param $name string 要保存的Excel的名字 * @param $ret_data 转换为表格的二维数组 * @throws PHPExcel_Exception * @throws PHPExcel_Reader_Exception */ function exportExcel($name, $ret_data){ $objPHPExcel = new PHPExcel(); //设置表格 $objPHPExcel->getProperties()->setCreator($name) ->setLastModifiedBy($name) ->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"); //填充数据 foreach ($ret_data as $key => $row) { $num = $key + 1; //$row = array_values($row); $i=0; foreach ($row as $key2 => $value2) { $objPHPExcel->setActiveSheetIndex(0)->setCellValue( Cell::stringFromColumnIndex($i). ($num), $value2); $i++; } } //设置表格并输出 $objPHPExcel->getActiveSheet()->setTitle($name); header('Content-Type: application/vnd.ms-excel'); header("Content-Disposition: attachment;filename={$name}.xls"); header('Cache-Control: max-age=0'); header('Cache-Control: max-age=1'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); header('Cache-Control: cache, must-revalidate'); header('Pragma: public'); // HTTP/1.0 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; } ## 导入Excel 同理,导入Excel其实就是将Excel的数据转化成为二维数组,这就要求Excel必须符合格式。 function getRows($inputFileName) { if (!file_exists($inputFileName)) { throw new Exception("File not existed"); } $inputFileType = PHPExcel_IOFactory::identify($inputFileName); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($inputFileName); $objWorksheet = $objPHPExcel->getActiveSheet(); $highestRow = $objWorksheet->getHighestRow(); $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数 $row = 1; $curr = array(); while ($row <= $highestRow) { for ($col = 0; $col < $highestColumnIndex; $col++) { $value = str_replace(array("\n", "\n\r", "\r"), "", $objWorksheet->getCellByColumnAndRow($col, $row)->getValue()); $curr[$row][] = $value; } $row++; } array_shift($curr);//第一行一般是字段名(Excel中列的标题),导入时要移除 return $curr; } ## 其他 * 导出时保存的格式是xlsx,想要改成其他格式需要传入不同的参数。 * 导入时如果有多个sheet时需要在上次打开时在要导入的sheet页(以保证当前sheet为activeSheet)关           闭,或者根据sheet名在程序中选择sheet。
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3