Рубрики
Uncategorized

PHP использование электронной таблицы PHP для работы с Excel

Автор оригинала: David Wong.

В этой статье рассказывается о том, как PHP использует электронную таблицу php для работы с Excel . Подробности заключаются в следующем:

1. Введение в электронную таблицу php

1. Что такое электронная таблица php

Phpspredsheet-это библиотека, написанная на чистом PHP, которая предоставляет набор классов, позволяющих читать и записывать различные форматы файлов электронных таблиц.Phpspredsheet предоставляет богатый интерфейс API, который может задавать множество свойств ячеек и документов, включая стиль, изображение, дату, функцию и многие другие приложения. Одним словом, электронная таблица php может выполнять любую форму excel ты хочешь

  • Разработчику PHP с электронной таблицей php требуется версия 7.1 или выше
  • Электронная таблица Php поддерживает работу с цепочками
2. Форматы файлов, поддерживаемые электронной таблицей php
3. Официальный сайт электронной таблицы php
  • Официальный сайт электронной таблицы php
4. Установка электронных таблиц PHP
  • композитору требуется php office/электронная таблица php

2, Базовые знания

1. Погрузка
PhpSpreadsheet\Spreadsheet;
  #Instantiate the spreadsheet object
  $spreadsheet = new Spreadsheet();
2. Получить рабочие тетради
  • Получить таблицу активности
getActiveSheet();
3. Получить сотовый
  • Два способа получить клетки
  • getCell
  • Получить Cellbycolumnandrow
getActiveSheet();
  #Get cell
  $cell = $sheet->getCell('A1');
  $cell = $sheet->getCellByColumnAndRow(1,1);
4. Установить ячейку
  • Значение набора
  • Параметры: значения ячеек
getActiveSheet();

	#Get cell
	$cellA = $sheet->getCell('A1');
	#Set cell value
	$cella - > setValue ('ouyang Ke ');

	#Get cell
	$cellB = $sheet->getCellByColumnAndRow(1,2);
	#Set cell value
	$cellb - > setValue ('huangrong ');

	#Get set cell, chain operation
	$sheet - > getcell ('a3 ') - > setValue ('guo Jing');
	$sheet - > getcellbycolumnandrow (1,4) - > setValue ('yang Kang ');
5. Получить значение ячейки
  • GetValue возвращает значение ячейки
  • Getcoordinate получает координаты ячейки
getActiveSheet();

	#Get cell
	$cellA = $sheet->getCell('A1');
	#Set cell value
	$cella - > setValue ('ouyang Ke ');

	Echo 'Value:', $cella - > getvalue(), PHP_ EOL;
	Echo 'coordinate:', $cella - > getcoordinate();
6. Сохранить форму
getActiveSheet();

	#Get cell
	$cellA = $sheet->getCell('A1');
	#Set cell value
	$cella - > setValue ('ouyang Ke ');

	#Get cell
	$cellB = $sheet->getCellByColumnAndRow(1,2);
	#Set cell value
	$cellb - > setValue ('huangrong ');

	#Get set cell, chain operation
	$sheet - > getcell ('a3 ') - > setValue ('guo Jing');
	$sheet - > getcellbycolumnandrow (1,4) - > setValue ('yang Kang ');

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');

3, Укрепить клетку

1. Установить ячейку
  • Значение setCell
  • Параметр 1: расположение ячейки
  • Параметр 2: значение ячейки
  • setCellValueByColumnАндРоу
  • Параметр 1: положение столбца
  • Параметр 2: положение строки
  • Параметр 3: значение ячейки
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	$sheet->setCellValueByColumnAndRow(1, 3, 2);
	$sheet - > setcellvaluebycolumnandrow (2,3, 'huangrong');
	$sheet - > setcellvaluebycolumnandrow (3,3, '17');
	$sheet->setCellValueByColumnAndRow(4, 3, '165cm');

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
2. Стиль текста ячейки
  • getStyle получает стиль ячейки
  • Getfont получить стиль текста ячейки
  • Установить жирный шрифт задает толщину текста
  • Установить имя установить шрифт текста
  • setSize задает размер текста
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	$sheet->setCellValueByColumnAndRow(1, 3, 2);
	$sheet - > setcellvaluebycolumnandrow (2,3, 'huangrong');
	$sheet - > setcellvaluebycolumnandrow (3,3, '17');
	$sheet->setCellValueByColumnAndRow(4, 3, '165cm');

	$sheet - > GetStyle ('b2 ') - > getfont() - > setbold (true) - > setname ('tahoma') - > SetSize (20);

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
3. Цвет текста ячейки
  • Getcolor() получает координатный цвет
  • Setrgb() задает цвет шрифта
  • Getrgb() возвращает цвет шрифта
  • Setargb() задает цвет шрифта
  • Getrgb() возвращает цвет шрифта
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	$sheet->setCellValueByColumnAndRow(1, 3, 2);
	$sheet - > setcellvaluebycolumnandrow (2,3, 'huangrong');
	$sheet - > setcellvaluebycolumnandrow (3,3, '17');
	$sheet->setCellValueByColumnAndRow(4, 3, '165cm');

	$sheet->getStyle('B2')->getFont()->getColor()->setRGB('#AEEEEE');
	echo $sheet->getStyle('B2')->getFont()->getColor()->getRGB(),PHP_EOL;

	$sheet->getStyle('B3')->getFont()->getColor()->setARGB('FFFF0000');
	echo $sheet->getStyle('B3')->getFont()->getColor()->getARGB();

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
4. Формат ячейки
  • Getnumberformat получить формат
  • Setformatcode задает формат
getActiveSheet();

	$sheet->setCellValue('A1','2019-10-10 10:10:10');
	$sheet->setCellValue('A2','2019-10-10 10:10:10');
	$sheet->getStyle('A2')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDD2);

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • Setwraptext задает строку в тексте как: перенос
getActiveSheet();

	$sheet - > setcellvalue ('a1 ','ouyangke huangrong');
	$sheet->getStyle('A1')->getAlignment()->setWrapText(true);

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • Gethyperlink получить ссылку на ячейку
  • Установить URL-адрес установить ссылку на ячейку
getActiveSheet();

	$sheet->setCellValue('A1','www.php.cn');
	$sheet->getCell('A1')->getHyperlink()->setUrl('https://www.php.cn');

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');

4, Пакетная операция

1. Используйте формулу
getActiveSheet();

	$sheet->setCellValue('A1','10');
	$sheet->setCellValue('B1','15');
	$sheet->setCellValue('C1','20');
	$sheet->setCellValue('D1','25');
	$sheet->setCellValue('E1','30');
	$sheet->setCellValue('G1','35');
	$Sheet > setcellvalue ('a2 ','total:');
	$sheet->setCellValue('B2', '=SUM(A1:G1)');
	$Sheet > setcellvalue ('a3 ','average:');
	$sheet->setCellValue('B3', '=AVERAGE(A1:G1)');
	$Sheet > setcellvalue ('a4 ','min:');
	$sheet->setCellValue('B4', '=MIN(A1:G1)');
	$Sheet > setcellvalue ('a5 ','MAX:');
	$sheet->setCellValue('B5', '=MAX(A1:G1)');
	$Sheet > setcellvalue ('a6 ','MAX:');
	$sheet - > setcellvalue ('b6 ',' \ = max (A1: G1 '); // use escape character

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
2. Пакетное назначение
  • Из массива заполняет рабочий лист значениями из массива
  • Параметр 1: данные (массив)
  • Параметр 2: удалите значение
  • Параметр 3: с чего начать
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->fromArray(
		[
			[1, 'Ouyang Ke', '18 years old', '188CM'],
			[2, 'Huang Rong', '17 years old', '165cm'],
			[3, 'Guo Jing', '21 years old', '180cm']
		],
		3,
		'A2'
	);

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
3. Объединение ячеек
getActiveSheet();

	$sheet->mergeCells('A1:B5');

	$sheet - > getcell ('a1 ') - > setValue ('ouyang Ke');

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');

После слияния назначение может быть присвоено только начальным координатам A1.

4. Разделенная ячейка
getActiveSheet();

	$sheet->mergeCells('A1:B5');

	$sheet->unmergeCells('A1:B5');

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
5. Операции со столбцами и строками
  • Getcolumndimension получает столбец
  • getWidth возвращает ширину столбца
  • Задать ширину задает ширину столбца
  • Setautosize задает ширину столбца, которая будет автоматически регулироваться
  • Измерение Getdefaultcolumn возвращает значение столбца по умолчанию
getActiveSheet();

	echo $sheet->getColumnDimension('A')->getWidth();

	$sheet->getColumnDimension('A')->setWidth(100);

	$sheet->getColumnDimension('B')->setAutoSize(true);

	$sheet->getDefaultColumnDimension()->setWidth(1);

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • Getrowdimension получает строку
  • Getrowheight получает высоту строки
  • Setrowheight задает высоту строки
getActiveSheet();

	echo $sheet->getRowDimension(1)->getRowHeight();

	$sheet->getRowDimension(1)->setRowHeight(100);

	$sheet->getDefaultRowDimension()->setRowHeight(1);

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • Gethighestcolumn возвращает общее количество столбцов
  • Gethighestrow получает общее количество строк
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	$sheet->setCellValueByColumnAndRow(1, 3, 2);
	$sheet - > setcellvaluebycolumnandrow (2,3, 'huangrong');
	$sheet - > setcellvaluebycolumnandrow (3,3, '17');
	$sheet->setCellValueByColumnAndRow(4, 3, '165cm');

	echo $sheet->getHighestColumn();
	echo $sheet->getHighestRow();

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');
6. Стиль ячейки
  • applyFromArray
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	$styleArray = [
		//Use phpoffice / phpspredsheet / style / alignment; constants in the file are parameters
		// Alignment::HORIZONTAL_ Center level in the middle
		// Alignment::VERTICAL_ Center vertical center
		'alignment' => [
			// 'horizontal' => Alignment::HORIZONTAL_ Center, // Center
			// 'vertical' => Alignment::VERTICAL_ Center, // center vertically
			'horizontal' = >'center ', // center horizontally
			'vertical' = >'center ', // center vertically
		],
		//Use phpoffice / phpspredsheet / style / border; constants in the file are parameters
		// Border::BORDER_ Think border style
		'borders' => [
			'outline' => [
				// 'borderStyle' => '\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK',
				'borderStyle' => 'thick',
				'color' => ['argb' => 'FFFF0000'],
			],
		],
		'font' => [
			'name' = >'bold ',
			'bold' => true,
			'size' => 22
		]
	];

	$sheet->getStyle('A1')->applyFromArray($styleArray);

	#The xlsx class saves the spreadsheet to a file
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	$writer = new Xlsx($spreadsheet);
	$writer->save('1.xlsx');

5, Работа с рабочей книгой

1. Загрузка файла Xlsx
  • Iofactory:: createwriter запись в файл
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	//MIME Protocol, file type, not set, will default to HTML
	header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	//Extension of MIME Protocol
	header('Content-Disposition:attachment;filename=1.xlsx');
	//Cache control
	header('Cache-Control:max-age=0');

	$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
	//  php://output  It is a write only stream that allows you to write to the output buffer in the same way as print and echo. 
	$writer->save('php://output');
2. Загрузка файла Xls
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	$filename = '1.xls';
	header('Content-Type:application/vnd.ms-excel');
	header('Content-Disposition:attachment;filename=1.xls');
	header('Cache-Control:max-age=0');

	$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
	$writer->save('php://output');
3. Задать заголовок рабочей книги
  • сетТитль
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','name');
	$Sheet > setcellvalue ('c1 ','age');
	$Sheet > setcellvalue ('d1 ','height');

	$sheet->setCellValueByColumnAndRow(1, 2, 1);
	$sheet - > setcellvaluebycolumnandrow (2,2, 'Ouyang Ke');
	$sheet - > setcellvaluebycolumnandrow (3,2, '18');
	$sheet->setCellValueByColumnAndRow(4, 2, '188cm');

	$Sheet > settitle ('ouyang Ke ');

	//MIME Protocol, file type, not set, will default to HTML
	header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	//Extension of MIME Protocol
	header('Content-Disposition:attachment;filename=1.xlsx');
	//Cache control
	header('Cache-Control:max-age=0');

	$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
	//  php://output  It is a write only stream that allows you to write to the output buffer in the same way as print and echo. 
	$writer->save('php://output');
4. Прочитать таблицу
load('1.xlsx');
	#Get activity workbooks
	$sheet = $spreadsheet->getActiveSheet();

	#Get cell values and coordinates
	$cellC1 = $sheet->getCell('B2');
	Echo 'Value:', $cellc1 - > getvalue(), PHP_ EOL;
	Echo 'coordinate:', $cellc1 - > getcoordinate()_ EOL;

	$Sheet > setcellvalue ('b2 ','ouyang Feng');

	#Get cell values and coordinates
	$cellC2 = $sheet->getCell('B2');
	Echo 'Value:', $cellc2 - > getvalue(), PHP_ EOL;
	Echo 'coordinate:', $cellc2 - > getcoordinate();

6, Тип контента, соответствующий офису суффикс

.док приложение/msword
.точка приложение/msword
.docx приложение/vnd.openxmlформаты-officedocument.wordprocessingml.документ
.точка приложение/vnd.openxmlформаты-officedocument.wordprocessingml.шаблон
.докм приложение/vnd.ms-word.документ.макроКоманда.12
.дотм приложение/vnd.ms-word.шаблон.макроКоманда.12
.xls приложение/vnd.ms-excel
.xlt приложение/vnd.ms-excel
.xla приложение/vnd.ms-excel
.xlsx приложение/vnd.openxmlформаты-officedocument.spreadsheetml.лист
.xltx приложение/vnd.openxmlформаты-officedocument.spreadsheetml.шаблон
.xlsm приложение/vnd.ms-excel.лист.макроКоманда.12
.xltm приложение/vnd.ms-excel.шаблон.макроКоманда.12
.xlam приложение/vnd.ms-excel.addin.macroEnabled.12
.xlsb приложение/vnd.ms-excel.лист.двоичный файл.макроКоманда.12
.ррт приложение/vnd.ms-powerpoint
.горшок приложение/vnd.ms-powerpoint
.ппс приложение/vnd.ms-powerpoint
.ппа приложение/vnd.ms-powerpoint
.pptx приложение/vnd.openxmlформаты- приложение/vnd.openxmlформаты-
.горшок приложение/vnd.openxmlформаты-officedocument.presentationml.шаблон
.ppsx приложение/vnd.openxmlформаты-officedocument.презентацияml.слайд-шоу
.ппам приложение/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm приложение/vnd.ms-powerpoint.презентация.макроКоманда.12
.потм приложение/vnd.ms-powerpoint.презентация.макроКоманда.12
.ppsm приложение/vnd.ms-powerpoint.слайд-шоу.с поддержкой макросов.12

7, Фактический бой

1. Экспорт данных
  • таблица журналов login_ Log
CREATE TABLE `login_log` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`Uid ` int (11) default null comment 'administrator ID',
	`client` tinyint(4) unsigned DEFAULT '0' COMMENT '0-PC 1-ios 2-android',
	`add_ Time ` int (11) default '0' comment 'creation time',
	`IP ` bigint (20) unsigned not null default '0' comment 'login IP',
	PRIMARY KEY (`id`) USING BTREE
) ENGINE=MyISAM AUTO_ INCREMENT=1122 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_ 0900_ ai_ Ci comment ='login log ';
  • index.php Страница списка данных




	
		
		< title > export data
		
	
	
		
		
					< th > User ID < / th >
					< th > login device
					< th > landing time
					< th > login IP < / th >
				
ID
  • скачать.операция экспорта php
getActiveSheet();

	$sheet->setCellValue('A1','ID');
	$Sheet > setcellvalue ('b1 ','user ID');
	$Sheet > setcellvalue ('c1 ','login device');
	$Sheet > setcellvalue ('d1 ','login time');
	$Sheet > setcellvalue ('e1 ','login IP');
	$sheet->fromArray(
		$select,
		null,
		'A2'
	);

	//MIME Protocol, file type, not set, will default to HTML
	header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	//Extension of MIME Protocol
	header('Content-Disposition:attachment;filename=1.xlsx');
	//Cache control
	header('Cache-Control:max-age=0');

	$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
	//  php://output  It is a write only stream that allows you to write to the output buffer in the same way as print and echo. 
	$writer->save('php://output');
?>
2. Импорт данных
  • база данных
#Commodity classification table
CREATE TABLE `shop_cat` (
	`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
	`PID ` int (10) unsigned default '0' comment 'parent ID',
	`Name ` varchar (50) default null comment 'category name',
	`Status ` tinyint (1) unsigned default '1' comment 'status 1 on 0 off',
	PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_ Increment = 8 default charset = utf8mb4 comment ='classification table ';

INSERT INTO `shop_ Cat ` values (1,0, 'women's wear', 1);
INSERT INTO `shop_ Cat ` values (2,0, 'men's wear', 1);
INSERT INTO `shop_ Cat ` values (3,0, 'Pregnancy', 1);
INSERT INTO `shop_ Cat ` values (4,1, 'dress', 1));
INSERT INTO `shop_ Cat ` values (5,1, 'jeans', 1);
INSERT INTO `shop_ Cat ` values (6,2, 'shirt', 1));
INSERT INTO `shop_ Cat ` values (7,3, 'pajamas', 1);

#Commodity list
CREATE TABLE `shop_list` (
	`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
	`cat_ ID ` int (10) unsigned default null comment 'class ID',
	`cat_ FID ` int (10) unsigned default null comment 'classification parent ID',
	`Title ` varchar (200) not null comment 'commodity title',
	`Price ` double (10,2) unsigned not null comment 'price',
	`IMG ` varchar (200) not null comment 'commodity picture',
	`add_ Time ` int (10) unsigned not null comment 'add time',
	PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_ Increment = 1 default chart = utf8mb4 comment ='commodity table ';
  • index.php Страница импорта



	
		
		< title > export data
		
	
	
		
< button type = "button" > < I >  < / I > upload file < / button > < I >  < / I > sample download
  • Функция импорта
load($file);
	#Get activity workbooks
	$sheet = $spreadsheet->getActiveSheet();

	#Get the total number of columns
	$highestColumn = $sheet->getHighestColumn();
	#Get total number of rows
	$highestRow = $sheet->getHighestRow();

	#Column number changed to digital display
	$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
	$log = [];
	for($a=2;$a<$highestRow;$a++){
		$title = $sheet->getCellByColumnAndRow(1,$a)->getValue();
		$cat_fname = $sheet->getCellByColumnAndRow(2,$a)->getValue();
		$cat_name = $sheet->getCellByColumnAndRow(3,$a)->getValue();
		$price = $sheet->getCellByColumnAndRow(4,$a)->getValue();
		$img = $sheet->getCellByColumnAndRow(5,$a)->getValue();

		$cat_fid = find('shop_cat','id','name="'.$cat_fname.'"');
		$cat_id = find('shop_cat','id','name="'.$cat_name.'"');
		$data = [
			'title' => $title,
			'cat_fid' => $cat_fid['id'],
			'cat_id' => $cat_id['id'],
			'price' => $price,
			'img' => $img,
			'add_time' => time(),
		];
		$ins = insert('shop_list',$data);
		if($ins){
			$log [] ='item '. $A.' inserted successfully ';
		}else{
			$log [] ='item '. $A.', insert failed ';
		}
	}
	echo json_ Encode (['code '= > 0,' MSG '= >'success','data' = > $log]);
  • Скачать образец
getActiveSheet();

	$Sheet > setcellvalue ('a1 ','product title');
	$Sheet > setcellvalue ('b1 ','first level classification');
	$Sheet > setcellvalue ('c1 ','secondary classification');
	$Sheet > setcellvalue ('d1 ','purchase price');
	$Sheet > setcellvalue ('e1 ','picture');

	$data = [
		'Fairy skirt as light as cloud, high-grade nail bead waist long skirt, sleeveless dress with temperament',
		'women's wear',
		'dress',
		279.99,
		'https://gd3.alicdn.com/imgextra/i3/266969832/O1CN01PWUBBB2MV6ekBKtb6_!!266969832.jpg_400x400.jpg',
	];
	$sheet->fromArray(
		$data,
		null,
		'A2'
	);

	//MIME Protocol, file type, not set, will default to HTML
	header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	//Extension of MIME Protocol
	header('Content-Di sposition:attachment;filename= Sample product list. Xlsx ');
	//Cache control
	header('Cache-Control:max-age=0');

	$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
	//  php://output  It is a write only stream that allows you to write to the output buffer in the same way as print and echo. 
	$writer->save('php://output');

Подробнее о содержимом, связанном с PHP, заинтересованные читатели могут ознакомиться с темой сайта: “Краткое описание навыков работы с документами PHP (включая word, Excel, access, “Ppt”, “Навыки работы с массивами PHP”, “Учебник по структуре данных и алгоритмам PHP”, “Краткое описание алгоритма программирования PHP”, “Краткое описание навыков математической работы PHP”, “Краткое описание использования регулярных выражений PHP”, “Краткое описание использования строк PHP” и “Краткое описание навыков работы с общей базой данных PHP”.

Я надеюсь, что эта статья полезна для программирования на PHP.

Оригинал: “https://developpaper.com/php-using-php-spreadsheet-to-operate-excel/”