平时在工做中,时常会出现将数据库表导出为Excel或者将Excel导入数据库表的需求。这一需求早早就已经实现过了,为了方便导入导出,我将其封装成了两个方法,做为记录。php
phpexcel拥有强大的Excel处理能力,在packagist上已经拥有数百万次的下载量,不过实话实说,excel的处理速度仍然是很是慢,数据量较大时慎重使用。在packagist上下载或者直接用composer require phpoffice/phpexcel
以后,即可以使用phpexcel了。数据库
在绝大多数状况下,导出excel其实就是将二维数组转化为表格。数组
/** * @param $name string 要保存的Excel的名字 * @param $ret_data 转换为表格的二维数组 * @throws PHPExcel_Exception * @throws PHPExcel_Reader_Exception */ function exportExcel($name, $ret_data){ $objPHPExcel = new \PHPExcel\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( \PHPExel\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必须符合格式。app
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\r", "\n", "\r"), "", $objWorksheet->getCellByColumnAndRow($col, $row)->getValue()); $curr[$row][] = $value; } $row++; } array_shift($curr);//第一行通常是字段名(Excel中列的标题),导入时要移除 return $curr; }