How can PHP be integrated with Excel for easy data transfer and manipulation?

To integrate PHP with Excel for easy data transfer and manipulation, you can use the PHPExcel library. This library allows you to read, write, and manipulate Excel files directly from PHP code. By using PHPExcel, you can easily import data from Excel files into your PHP application, perform calculations or data manipulations, and then export the results back to Excel.

// Include PHPExcel library
require_once 'PHPExcel/Classes/PHPExcel.php';

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// Load Excel file
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load('example.xlsx');

// Get data from Excel file
$sheet = $objPHPExcel->getActiveSheet();
$data = $sheet->toArray(null, true, true, true);

// Manipulate data
// Example: Add a new column with calculated values
foreach ($data as $row => $rowData) {
    $newValue = $rowData['A'] + $rowData['B'];
    $sheet->setCellValue('C' . $row, $newValue);
}

// Save changes back to Excel file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('example_modified.xlsx');