Php to excel output

Экспорт из PHP в Excel с помощью PhpSpreadsheet

В своей профессиональной деятельности я периодически сталкиваюсь с задачами экспорта/генерации данных в формате XLS/XLSX (Excel). Библиотека PhpSpreadsheet позволяет их решить.

Данная библиотека является логичным продолжением библиотеки PHPExcel, которая уже несколько лет не поддерживается.

Скачать и установить библиотеку предлагается с помощью composer:

composer require phpoffice/phpspreadsheet

Опишу реализацию типичных задач.

Обратите внимание, что для корректной работы XMLWriter (библиотеки PHP) необходима корректная его настройка:

Типовой Hello World

getActiveSheet(); $sheet->setCellValue('A1', 'Hello World !'); $writer = new Xlsx($spreadsheet); $writer->save('hello world.xlsx');

Получение Excel документа через Ajax запрос

Php обработчик генерации XLSX документа:

header('Content-Type: application/json'); require 'vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); //some code. $writer = new Xlsx($spreadsheet); ob_start(); $writer->save('php://output'); $xlsData = ob_get_contents(); ob_end_clean(); echo json_encode('data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'.base64_encode($xlsData));
$.ajax(< type:'POST', url:". ", // path to php handler data: , // some post data dataType:'json' >).done(function(data)< var $a = $(""); $a.attr("href",data); $("body").append($a); $a.attr("download","Report.xlsx"); $a[0].click(); $a.remove(); >);

PHP обработчик формирует Excel документ и кодирует его в base64. Далее JS создает временную ссылку и в тег «href» кладёт этот закодированный контент. После инициации клика по ссылке происходит скачивание XLSX документа, а сама ссылка удаляется со страницы. Этакая мгновенная генерация Excel документа.

Установка заголовка листа

$sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Some title');

Добавление текстового контента в ячейку

Можно добавлять по координатам (отчет начинается с единицы):

$sheet = $spreadsheet->getActiveSheet(); //$columnIndex - номер колонки //$row - номер строки //$data - текстовые данные для добавления $sheet->setCellValueByColumnAndRow($columnIndex, $row, $data);

Также можно воспользоваться символьными идентификаторами:

$sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Some data');

Выравнивание

$sheet->getStyleByColumnAndRow(1,1) ->getAlignment() ->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);

Через идентификатор ячейки:

$sheet->getStyle('B1') ->getAlignment() ->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);

Через интервал идентификаторов ячеек:

$sheet->getStyle('B1:B5') ->getAlignment() ->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);

Установка стиля границы (border) ячейки/ячеек

$borderStyleArray = array( 'borders' => array( 'outline' => array( 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, 'color' => array('rgb' => '000000'), ), 'horizontal' => array( 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, 'color' => array('rgb' => '000000'), ), 'vertical' => array( 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, 'color' => array('rgb' => '000000'), ), ), ); $sheet->getStyle('F4:J4')->applyFromArray($borderStyleArray);

Объединение ячеек

Заливка ячейки/ячеек цветом

$sheet->getStyle('F4') ->getFill() ->setFillType(PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID) ->getStartColor() ->setRGB('ecf9fd');

p.s. более подробную документацию по PhpSpreadsheet можно найти в самой библиотеке, скачанной с помощью composer-а:

Источник

exporting php output as excel

this is my export2excel.php file and func1,2,3 are in functions.php file and produces table output all work well except character encoding in a strange way. I am using utf-8 encoding for all my files. 2nd else if statement above produces healthy encoded output but rest 2 are encodes my output with strange characters like «BÜTÇE İÇİ». it is «BÜTÇE İÇİ» in turkish. in short. same files, same encoding, same database but different results. any idea?

3 Answers 3

Excel uses UTF-16LE + BOM as default Unicode encoding.
So you have to convert your output to UTF-16LE and prepend the UTF-16LE-BOM «\xFF\xFE» .

Instead I would use one of the existing libraries

  • PHP Excel Extension PECL extension by Ilia Alshanetsky (Core PHP Developer & Release Master)
  • Spreadsheet_Excel_Writer PEAR Package
  • PHPExcel

Edit:
Some code that could help if you really not want to use an existing library

  Foo IñtërnâtiônàlizætiøöäÄn  Bar Перевод русского текста в транслит   EOT; // Convert to UTF-16LE $output = mb_convert_encoding($output, 'UTF-16LE', 'UTF-8'); // Prepend BOM $output = "\xFF\xFE" . $output; header('Pragma: public'); header("Content-type: application/x-msexcel"); header('Content-Disposition: attachment; filename="utf8_bom.xls"'); echo $output; 

In windows everything works fine but In redhat linux line fwrite($fh, b»\xFF\xFE»); produces error: «PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /var/www/. » why is it so?

when I change the code like this it worked. $fh = fopen(‘foo.xls’, «wb»); // Prepend BOM fwrite($fh, «\xFF\xFE»);

i am using ms excel 2007 . and there cells are not visible when i export file. it gives message before open that «the file you are trying to open has different format than specified by the extension»

@Dashrath yes, it is actually another format, an html file, but who cares! Excel can open and edit it.

if anyone is trying to use the excel_writer in moodle and is getting encoding issues with output — say if you’re developing a report that has a url as data in a field — then in this instance to simply fix this issue I wrapped the data in quotes so it at least opened up in excel here’s my example:

// Moodles using the PEAR excel_writer export $table->setup(); $ex=new table_excel_export_format($table); $ex->start_document( ); $ex->start_table( ); // heading on the spreadsheet $title = array('Report Title'=>'Report 1'); $ex->add_data($title); // end heading $ex->output_headers( array_keys($table->columns) ); **foreach($data as $row)< $string="'".trim($row->resname,"'")."'"; $row->resname=$string; $ex->add_data( $table->get_row_from_keyed($row) ); >** $ex->finish_table(); $ex->finish_document(); 

Источник

Читайте также:  Hidden class in java
Оцените статью