Please introduce the PHPExcel library before use
- /**
- * Excel writing, based on PHPExcel library
- * @param array $data
- * @param $file
- * @return bool
- * @throws PHPExcel_Exception
- *
- */
- function excel_insert(array $data,$file){
-
- // $data = [
- // 'Warehouse'=>[
- // ['Warehouse number','Warehouse noun',1],
- // ['Warehouse number','Warehouse noun',1],
- // ['Warehouse number','Warehouse noun',1] ,
- // ['Warehouse number','Warehouse noun',1],
- // ['Warehouse number','Warehouse noun',1],
- // ],
- // 'Warehouse 2'=> [
- // ['Warehouse number','Warehouse noun',1],
- // ['Warehouse number','Warehouse noun',1],
- // ['Warehouse number','Warehouse noun',1 ],
- // ['Warehouse number','Warehouse noun',1],
- // ['Warehouse number','Warehouse noun',1],
- // ],
- // ];
- // excel_insert ($data,'s.xlsx');
-
- if(!$data||!$file){
- return false;
- }
-
- $sheet_id = 0;
- //Create excel operation object
- $objPHPExcel = new PHPExcel();
- //Get the file property object and provide setting resources for the following
- $objPHPExcel->getProperties()->setCreator("Mianyang Carbon Cloud Information Technology Co., Ltd.")
- ->setLastModifiedBy( "Mianyang Carbon Cloud Information Technology Co., Ltd.")
- ->setTitle("Input_Goods_message")
- ->setSubject("Topic 1")
- ->setDescription("Any one described")
- -> ;setKeywords("Keywords separated by spaces")
- ->setCategory("Category");
- for($i=1;$i $objPHPExcel->addSheet (new PHPExcel_Worksheet($objPHPExcel,'sheet'.$i));
- }
- foreach($data as $sheetName => $sheetData){
- $Sheet = $objPHPExcel->setActiveSheetIndex($sheet_id);
- $ Sheet->setTitle($sheetName);
- $insert_id = 1;
- foreach($sheetData as $rowData){
- if(is_array($rowData)&&$rowData){
- foreach($rowData as $id => $cellData){
- if(is_numeric($id)&&(is_string($cellData)||is_numeric($cellData))){
- $Sheet->setCellValue(chr(65+$id).$insert_id,$cellData );
- }else{
- return false;
- }
- }
- $insert_id++;
- }else{
- return false;
- }
- }
- $sheet_id++;
- }
- try{
- $objWriter = PHPExcel_IOFactory::createWriter($objPH PExcel , 'Excel2007');
- $objWriter->save($file);
- }catch (Exception $e){
- return false;
- }
- }
Copy code
Usage:
- $data = [
- 'Warehouse'=>[
- ['Warehouse number','Warehouse noun',1],
- ['Warehouse number','Warehouse noun',1],
- ['Warehouse number','Warehouse noun',1],
- ['Warehouse number','Warehouse noun',1],
- ['Warehouse number','Warehouse noun',1],
- ],
- ' Warehouse 2'=>[
- ['Warehouse number','Warehouse noun',1],
- ['Warehouse number','Warehouse noun',1],
- ['Warehouse number','Warehouse noun',1 ],
- ['Warehouse number','Warehouse noun',1],
- ['Warehouse number','Warehouse noun',1],
- ],
- ];
- excel_insert($data,'s.xlsx') ;
Copy code
|