Method for PHPExcel to modify an existing Excel

  • 2021-10-11 17:48:43
  • OfStack

As shown below:


require_once './Classes/PHPExcel/IOFactory.php';
  $filePath = './Template.xlsx';
  // Read a file 
  if (!file_exists($filePath)) {
     exit("you dont have ");
  }
  $objPHPExcel = PHPExcel_IOFactory::load($filePath);
  $sheet = $objPHPExcel->getSheet(0); //  Read the 1 Worksheet 
  $highestColumm = $sheet->getHighestColumn(); //  Get the total number of columns 
  $highestRow = $sheet->getHighestRow(); //  Get the total number of rows 
  /**  Loop to read the data of each cell  */
  $i = 2;
  foreach ($list as $key => $value) {
      $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('Z'.$i, $value['demo'])
            ->setCellValue('AA'.$i, $value['demo']);
      $i++;
  }
  $objPHPExcel->getActiveSheet()->setTitle('Simple');
  $objPHPExcel->setActiveSheetIndex(0);
  /**  Output to the specified directory  */
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save('simple.xlsx');// File save path 
  /**  Output to the browser and download it directly  */
  $file_name = 'batchTemplate.xlsx';
  header('Content-Type:application/vnd.ms-excel'); // Specify the download file type 
  header('Content-Disposition: attachment; filename="'.$file_name.'"'); // Specify the description of the downloaded file 
  header('Content-Length:'.filesize($input_file)); // Specify the size of the downloaded file 
  /**  Read the contents of the file and output it directly for download  */
  readfile($input_file);

Related articles: