PHP: работа с файлами Excel

Одним из вариантов работы с файлами Эксель является библиотека PhpSpreadsheet.

Установка:

composer require phpoffice/phpspreadsheet

Пример использования:


/require_once('vendor/autoload.php');
 
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\{Font, Border, Alignment};
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$oSpreadsheet = IOFactory::load("akt.xlsx"); // шаблон с шапкой

$oSpreadsheet->getProperties()
   ->setCreator('SSK, OOO')
   ->setLastModifiedBy('SSK, OOO')
   ->setTitle('Акт сверки с клиентом') 
   ->setSubject('Акт сверки с клиентом')
   ->setKeywords('кцмукмц ')
   ->setCategory('узщшамыуозк ')
;

$oSpreadsheet->setActiveSheetIndex(0);
$wSheet = $oSpreadsheet->getActiveSheet();

$wSheet->setCellValueByColumnAndRow(1, 3, "Клиент: " . $res->result->user);
$wSheet->setCellValueByColumnAndRow(1, 4, "Дата с: " . $res->result->from);
$wSheet->setCellValueByColumnAndRow(1, 5, "Дата по: " . $res->result->from);

$totalrow=8;

$balance=0;
foreach($res->result->table as $row) {
    $source="";
    if ($row->doc_reservation>0){$source="уцкацук м №".$row->doc_reservation;};
    if ($row->doc_charge>0){$source="ы укмыу №".$row->doc_charge;};
    if ($row->doc_payment>0){
        $source="уфыкмыукм №".$row->doc_payment;
        if ($row->connector>0){$source=$source.",фыумукау №".$row->connector;};        
    }; 
    
    $wSheet->setCellValueByColumnAndRow(1, $totalrow, $row->date);    //дата
    $wSheet->setCellValueByColumnAndRow(2, $totalrow, $source);    // источник     
    $wSheet->setCellValueByColumnAndRow(3, $totalrow, $row->debit);    // дебет
    $wSheet->setCellValueByColumnAndRow(4, $totalrow, $row->credit);    // кредит
    $wSheet->setCellValueByColumnAndRow(5, $totalrow, $row->balance);    // баланс
    $wSheet->setCellValueByColumnAndRow(6, $totalrow, $row->ezs);    // ЭЗС
    $balance=$row->balance;
    $totalrow++;
}

$wSheet->setCellValueByColumnAndRow(1, $totalrow, "Текущий баланс: " . $balance);
$wSheet->getStyle('A'.$totalrow)->applyFromArray([
    'font' => [
      'name' => 'Arial',
      'bold' => true,
      'italic' => false,
      'underline' => Font::UNDERLINE_DOUBLE,
      'strikethrough' => false,
      'color' => [
          'rgb' => '808080' 
        ]
    ],
    'borders' => [
        'allBorders' => [
            'borderStyle' => Border::BORDER_THIN,
            'color' => [
                'rgb' => '808080'
            ]
        ],
    ],
    'alignment' => [
        'horizontal' => Alignment::HORIZONTAL_CENTER,
        'vertical' => Alignment::VERTICAL_CENTER,
        'wrapText' => true,
    ]
]);
// установить цвет фона ячейки
$wSheet->getStyle('A'.$totalrow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00FF7F');
 

$oWriter = IOFactory::createWriter($oSpreadsheet, 'Xlsx');
$oWriter->save('php://output');