Во-первых: Установите php office/электронную таблицу php
composer require phpoffice/phpspreadsheet
II: Подробное описание интерфейса API электронных таблиц phpoffice/php
Электронная таблица Php предоставляет богатый интерфейс API, который может задавать множество атрибутов ячеек и документов, включая стиль, изображение, дату, функцию и многие другие приложения. Короче говоря, какая таблица Excel вам нужна, электронная таблица Php может это сделать.
Перед использованием интерфейса API электронной таблицы php office/php убедитесь, что введены и созданы правильные файлы
Use PhpOfficePhpSpreadsheetSpreadsheet;//Introduce files $spreadsheet = new PhpOffice PhpSpreadsheet Spreadsheet ();// Create a new excel document $sheet = $spreadsheet - > getActiveSheet (); // Get the object of the current operation sheet
1: Установите шрифты:
$sheet->getStyle('A7:B7')->getFont()->setBold(true)->setName('Arial')
-> SetSize (10); // Set the cells A7 to B7 to bold, Arial, 10
$sheet - > getStyle ('B1') - > getFont () - > setBold (true); // Set B1 cells to bold type2: Установите цвет
$sheet - > getStyle ('A1') - > getFont () - > getColor () - > setARGB ( PhpOffice PhpSpreadsheet Style Color:: COLOR_RED); //Set the text color of cell A1 to red3: Установите ширину столбца
$sheet - > getColumnDimension ('A') - > setWidth (20); // Set the width of column A to 20 (characters)
$sheet - > getColumnDimension ('B') - > setAutoSize (true); // Set the width of column B to automatic width
$sheet - > getDefaultColumnDimension () - > setWidth (12); // Set default column width to 124: Установите высоту линии
$sheet - > getRowDimension ('10') - > setRowHeight (100); /// Set the height of the tenth line to 100pt
$sheet - > getDefaultRowDimension () - > setRowHeight (15); // Set default row height to 155:Выравнивание
$sheet->getStyle('A:D')->getAlignment()
-> SetVertical ( PhpOffice PhpSpreadsheet Style Alignment:: VERTICAL_CENTER) /// Set Vertical Centralization
-> SetHorizontal ( PhpOffice PhpSpreadsheet Style Alignment:: HORIZONTAL_CENTER)/// Settings are in the middle
-> setWrapText (true); // Set automatic line break6: Объединение ячеек
$sheet - > mergeCells ('A1: D2'); //A1 to D2 merged into one cell7: Разделите объединенные ячейки
$sheet - > unmergeCells ('A1: D2'); // Split the merged cells.8: Используйте applyFromArray для реализации настроек стиля ячеек
// Style variables
$style = [
// Setting font style
'font' => [
'name' => 'Arial',
'bold' => true,
'italic' => false,
'underline' => Font::UNDERLINE_DOUBLE,
'strikethrough' => false,
'color' => [
'rgb' => '808080'
]
],
// Set the border style
'borders' => [
// All Borders Border Styles
// Left border
'bottom' => [
'borderStyle' => Border::BORDER_DASHDOT,
'color' => [
'rgb' => '808080'
]
],
// Upper border
'top' => [
'borderStyle' => Border::BORDER_DASHDOT,
'color' => [
'rgb' => '808080'
]
]
],
// Alignment Style
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
// Whether to use prefix
'quotePrefix' => true
];
$sheet->getStyle('A1:D1')->applyFromArray($style);9. Настройка заголовка рабочего листа
$sheet - > setTitle ('Hello'); and // Set the current worksheet title.10: Форматирование ячеек
$sheet->getStyle('D2')->getNumberFormat()
-> setFormatCode ( PhpOffice PhpSpreadsheet Style NumberFormat:: FORMAT_TEXT); // Set the format of D2 cells to text format
$sheet->getStyle('A1:D2')->getNumberFormat()
-> setFormatCode ( PhpOffice PhpSpreadsheet Style NumberFormat:: FORMAT_TEXT); // Set cells A1 to D2 to text format11:Изменение строки
$sheet - > getCell ('A4') - > setValue ("hello nworld"); and // wrap the hello and world lines of cells A412: Гиперссылки
// Set up the A2 cell content blog and click jump https://www.wj0511.com
$sheet->setCellValue('A2', 'blog');
$sheet->getCell('A2')->getHyperlink()->setUrl('https://www.wj0511.com');13: Использование функций
Общие функции: сумма (SUM), максимум (MAX), минимум (MIN), среднее (AVERAGE).
$sheet - > setCellValue ('B5','= SUM (B1: B4)'); and // Set the contents of B5 cells to the sum of B1 to B414: Настройка свойств Документа
$spreadsheet->getProperties()
-> setCreator ("author"//author)
-> setLastModifiedBy ("last-author")// Last ModifiedBy
-> setTitle ("title")// title
-> setSubject ("subject"// subtitle
-> setDescription ("description"//description)
-> setKey ("keywords") // keyword
-> setCategory ("category"); //classificationТри: Простая реализация генерации Excel (здесь я загружаю фреймворк Yii с помощью метода загрузки)
yii\web\Controller;
class ExcelController extends Controller
{
/**
* Digital transliteration (similar to Excel column labels)
*@ Param Int $index index value
*@ Param Int $start letter start value
*@ Return String returns letters
*/
public function intToChr($index, $start = 65)
{
$str = '';
if (floor($index / 26) > 0) {
$str .= $this->intToChr(floor($index / 26)-1);
}
return $str . chr($index % 26 + $start);
}
public function actionIndex()
{
// Header information
$header = [
'Name',
'Gender',
'Education',
'Age',
'Height',
];
// Content
$data = [
[
Xiaoming,
'male',
'Specialist',
'18',
'175'
],
[
'Xiaohong',
'female',
'Undergraduate',
'18',
'155'
],
[
'Little Blue',
'male',
'Specialist',
'20',
'170'
],
[
'Zhang San',
'male',
'Undergraduate',
'19',
'165'
],
[
'Li Si',
'male',
'Specialist',
'22',
'175'
],
[
Wang Er,
'male',
'Specialist',
'25',
'175'
],
[
'Mazi',
'male',
'Undergraduate',
'22',
'180'
],
];
$header = array_values($header);
$data = array_values($data);
// Get column information
$column = []; //['A','B','C','D','E']
foreach ($header as $k => $item) {
$column[$k] = $this->intToChr($k);
}
// Get the initial and final columns
$firstColum = $column[0];
$lastColum = $column[count($column) - 1];
// Get the initial and final rows
$firstRow = 1;
$lastRow = count($data) + 1;
$row = 1;
$spreadsheet = new Spreadsheet ();// Create a new excel document
$sheet = $spreadsheet - > getActiveSheet (); // Get the object of the current operation sheet
$sheet - > setTitle ('Title'); // Set Title
$sheet->getStyle("{$firstColum}:{$lastColum}")->getAlignment()
-> SetVertical (Alignment:: VERTICAL_CENTER)// Set Vertical Centralization
-> Set Horizontal (Alignment:: HORIZONTAL_CENTER)// Setting level is in the middle
-> setWrapText (true); // Set automatic line break
// Set width
$sheet->getDefaultColumnDimension()->setWidth(20);
$headerStyle = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
'font' => [
'bold' => true,
'size' => 14,
],
];
$cellStyle = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['argb' => 'FF000000'],
]
],
'font' => [
'size' => 10,
],
];
// Set Excel cell format to text format
$sheet->getStyle("{$firstColum}{$firstRow}:{$lastColum}{$lastRow}")->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);
// Setting header information style
$sheet - > getRowDimension ($row) - > setRowHeight (30); // Set line height
$sheet->getStyle("{$firstColum}{$row}:{$lastColum}{$row}")->applyFromArray($headerStyle);
// Setting header information
foreach ($header as $key => $item) {
$sheet->setCellValue("{$column[$key]}{$row}", $item);
}
$row++;
foreach ($data as $key => $model) {
$sheet - > getRowDimension ($row) - > setRowHeight (30); // Set line height
$sheet->getStyle("{$firstColum}{$row}:{$lastColum}{$row}")->applyFromArray($cellStyle);
$i = 0;
foreach ($model as $value) {
$sheet->setCellValue("{$column[$i]}{$row}", $value);
$i++;
}
$row++;
}
$file = table'.'. xlsx'; // save address
$writer = new Xlsx($spreadsheet);
$writer - > save ($file); // generate excel file
Yii: $app - > response - > sendFile ($file,'download excel name. xlsx') - > send ();
}
}4: Чтение файлов Excel
$title = []; //excel worksheet title
$info = []; //excel content
FileName = table. xlsx;
$spreadsheet = IOFactory::load($fileName);
// $worksheet = $spreadsheet - > getActiveSheet (); // Get the current file content
$sheetAllCount = $spreadsheet - > getSheetCount (); // Total worksheet
For ($index = 0; $index < $sheetAllCount; $index ++) {// worksheet title
$title[] = $spreadsheet->getSheet($index)->getTitle();
}
// Read the first worksheet
$whatTable = 0;
$sheet = $spreadsheet->getSheet($whatTable);
$highest_row = $sheet - > get Highest Row (); // Get the total number of rows
$highest_column = $sheet - > getHighestColumn (); /// Gets the column numeral abc...
$highestColumnIndex = Coordinate:: ColumnIndexFromString ($highest_column); // Converted to a number;
for ($i = 1; $i <= $highestColumnIndex; $i++) {
for ($j = 1; $j <= $highest_row; $j++) {
$conent = $sheet->getCellByColumnAndRow($i, $j)->getCalculatedValue();
$info[$j][$i] = $conent;
}
}
var_dump($info);Ссылка: https://phpspreadsheet.readth…