Change the line
$objValidation->setFormula1($configs);
to
$objValidation->setFormula1("'".$configs."'");
Because in the structure the data is with in single quotes(‘).
Sample working code
$objValidation2 = $sheet -> getCell('E1') -> getDataValidation();
$objValidation2 -> setType(PHPExcel_Cell_DataValidation::TYPE_LIST);
$objValidation2 -> setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_INFORMATION);
$objValidation2 -> setAllowBlank(true);
$objValidation2 -> setShowInputMessage(true);
$objValidation2 -> setShowErrorMessage(true);
$objValidation2 -> setShowDropDown(true);
$objValidation2 -> setErrorTitle('Invalid date');
$objValidation2 -> setError('Date is not in list.');
$objValidation2 -> setPromptTitle('Select DOB date');
$objValidation2 -> setPrompt('Please pick a date from the drop-down list.');
$dates = '"01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31"';
$objValidation2 -> setFormula1("'".$dates."'");
Code to write down selections where users can pick an option from, not allowing any data not within the itemize selection to be inputed in a particular cell. This kind of data validation, specifically can be referred as a drop down list validation, can straightforwardly achieve with PhpSpreadsheet when creating an xlsx file.
Requirements:
- Composer
- PHP 7.2 or newer
Step 1.
Setup dependencies.
{
"require": {
"phpoffice/phpspreadsheet": "^1.3"
}
}
Step 2.
Install phpspreadsheet.
$ composer install
Step 3.
Create a new PHP file, and start coding.
<?php
// Autoload dependencies
require 'vendor/autoload.php';
// Import the core class of PhpSpreadsheet
use PhpOfficePhpSpreadsheetSpreadsheet;
// Import the Xlsx writer class
use PhpOfficePhpSpreadsheetWriterXlsx;
// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();
// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();
/**
* Set cell B3 with the "Select from the drop down options:"
* string value, will serve as the 'Select Option Title'.
*/
$sheet->setCellValue('B3', 'Select from the drop down options:');
/**
* Set the 'drop down list' validation on C3.
*/
$validation = $sheet->getCell('C3')->getDataValidation();
/**
* Since the validation is for a 'drop down list',
* set the validation type to 'List'.
*/
$validation->setType(PhpOfficePhpSpreadsheetCellDataValidation::TYPE_LIST);
/**
* List drop down options.
*/
$validation->setFormula1('"A, B, C, D"');
/**
* Do not allow empty value.
*/
$validation->setAllowBlank(false);
/**
* Show drop down.
*/
$validation->setShowDropDown(true);
/**
* Display a cell 'note' about the
* 'drop down list' validation.
*/
$validation->setShowInputMessage(true);
/**
* Set the 'note' title.
*/
$validation->setPromptTitle('Note');
/**
* Describe the note.
*/
$validation->setPrompt('Must select one from the drop down options.');
/**
* Show error message if the data entered is invalid.
*/
$validation->setShowErrorMessage(true);
/**
* Do not allow any other data to be entered
* by setting the style to 'Stop'.
*/
$validation->setErrorStyle(PhpOfficePhpSpreadsheetCellDataValidation::STYLE_STOP);
/**
* Set descriptive error title.
*/
$validation->setErrorTitle('Invalid option');
/**
* Set the error message.
*/
$validation->setError('Select one from the drop down list.');
// Write a new .xlsx file
$writer = new Xlsx($spreadsheet);
// Save the new .xlsx file
$writer->save('create-xlsx-files-with-drop-down-list-data-validation.xlsx');
Test.
Run the following codes.
$ php create-xlsx-files-with-drop-down-list-data-validation.php
Result.
Open the generated file create-xlsx-files-with-drop-down-list-data-validation.xlsx.
/**
* Set cell B3 with the "Select from the drop down options:"
* string value, will serve as the 'Select Option Title'.
*/
$sheet->setCellValue('B3', 'Select from the drop down options:');
/**
* Set the 'drop down list' validation on C3.
*/
$validation = $sheet->getCell('C3')->getDataValidation();
/p>
Check the settings.
Click on Data.
Click on cell C3.
Click on ‘Data Validation’.
The ‘Data ValidationData Validation‘ window should show up.
Under the Settings Tab of the ‘Data Validation‘ window.
/**
* Since the validation is for a 'drop down list',
* set the validation type to 'List'.
*/
$validation->setType(PhpOfficePhpSpreadsheetCellDataValidation::TYPE_LIST);
/**
* List drop down options.
*/
$validation->setFormula1('"A, B, C, D"');
/**
* Do not allow empty value.
*/
$validation->setAllowBlank(false);
/**
* Show drop down.
*/
$validation->setShowDropDown(true);
Under the Input Message Tab of the ‘Data Validation‘ window.
/**
* Display a cell 'note' about the
* 'drop down list' validation.
*/
$validation->setShowInputMessage(true);
/**
* Set the 'note' title.
*/
$validation->setPromptTitle('Note');
/**
* Describe the note.
*/
$validation->setPrompt('Must select one from the drop down options.');
Under the Error Alert Tab of the ‘Data Validation‘ window.
/**
* Show error message if the data entered is invalid.
*/
$validation->setShowErrorMessage(true);
If the data entered is not on the drop down options, the ‘Error Window‘ should appear.
/**
* Do not allow any other data to be entered
* by setting the style to 'Stop'.
*/
$validation->setErrorStyle(PhpOfficePhpSpreadsheetCellDataValidation::STYLE_STOP);
/**
* Set descriptive error title.
*/
$validation->setErrorTitle('Invalid option');
/**
* Set the error message.
*/
$validation->setError('Select one from the drop down list.');
References:
- How to install PhpSpreadsheet
- Create xlsx files with cell data validation settings
- Create xlsx files with future date data validation
- Create xlsx files with past date data validation
- Create xlsx files with date range data validation
- Creating a spreadsheet
- Reading and writing to file
- PhpSpreadsheet Recipes
Posted
August 22, 2020
in
Мне нужно создать выпадающий список в Excel с помощью PHP. На самом деле мне нужно ограничить ввод пользователя для данного значения мной. посмотрите на изображение.
Я успешно создал файл Excel, но не могу создать выпадающий список. Нет никакой помощи от Google:) пожалуйста, посмотрите на изображение. заранее спасибо
0
Решение
If you are using PHPEXCEL API to generate the excel sheet then you can use this:
please use this: $objPHPExcel->getActiveSheet()->setAutoFilter('A1:I20');
или это
$objPHPExcel->getActiveSheet()->setAutoFilter(
$objPHPExcel->getActiveSheet()->calculateWorksheetDimension()
);
0
Другие решения
Я нашел решение следующим образом:
$objValidation = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getDataValidation();
$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
$objValidation->setAllowBlank(false);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setShowDropDown(true);
$objValidation->setErrorTitle('Input error');
$objValidation->setError('Value is not in list.');
$objValidation->setPromptTitle('Pick from list');
$objValidation->setPrompt('Please pick a value from the drop-down list.');
$objValidation->setFormula1('"Rate,Margin"');
0
-
#1
Нужно сгенерировать xls файл со списком и реализовать выборку с записью в др.колонке.
Гуглил 4 дня решил использовать PHPExel, c реализацией самого списка разобрался, а вот как выбираемые значение через запятую записывались в др.колонку завис. Натолкните на идею.
http://www.planetaexcel.ru/techniques/1/181/ пример что должно получиться
Пример моего кода:
<?
require_once ‘Classes/PHPExcel.php’; // подключение библиотеки
$objPHPExcel = new PHPEXcel();
$objPHPExcel->setActiveSheetIndex(0);//метод PHPEXcel новый активный лист
//$objPHPExcel->createSheet();
$objPHPExcel->getActiveSheet()
->setCellValue(‘A7’, «List:») //Добавление данных в таблицу
->setCellValue(‘D2’, «1»)
->setCellValue(‘D3’, «2»)
->setCellValue(‘D4’, «3»)
->setCellValue(‘D5’, «4»)
->setCellValue(‘D6’, «5»)
$objValidation = $objPHPExcel->getActiveSheet()->getCell(«B7»)->getDataValidation();// занесение данных в ячейку
$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
$objValidation->setAllowBlank(false);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setShowDropDown(true);// дропдаун
$objValidation->setErrorTitle(‘Input error’);
$objValidation->setError(‘Value is not in list.’);
$objValidation->setPromptTitle(‘Pick from list’);
$objValidation->setPrompt(‘Please pick a value from the drop-down list.’);
$objValidation->setFormula1(‘$D$2:$D$6’); //формула выводимых данных
header(«Content-Type:application/vnd.ms-excel»); // Вывод и сохранение файла.
header(«Content-Disposition:attachment;filename=’simple.xls'»);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5’);//версия EXEL
$objWriter->save(‘php://output’);
exit();
?>