Php excel выпадающий список

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

<?php use PhpOfficePhpSpreadsheetCellDataValidation; use PhpOfficePhpSpreadsheetNamedRange; use PhpOfficePhpSpreadsheetSpreadsheet; require __DIR__ . ‘/../Header.php’; // Create new Spreadsheet object $helper->log(‘Create new Spreadsheet object’); $spreadsheet = new Spreadsheet(); // Set document properties $helper->log(‘Set document properties’); $spreadsheet->getProperties() ->setCreator(‘PHPOffice’) ->setLastModifiedBy(‘PHPOffice’) ->setTitle(‘PhpSpreadsheet Test Document’) ->setSubject(‘PhpSpreadsheet Test Document’) ->setDescription(‘Test document for PhpSpreadsheet, generated using PHP classes.’) ->setKeywords(‘Office PhpSpreadsheet php’) ->setCategory(‘Test result file’); function transpose($value) { return [$value]; } // Add some data $continentColumn = ‘D’; $column = ‘F’; // Set data for dropdowns $continents = glob(__DIR__ . ‘/data/continents/*’); foreach ($continents as $key => $filename) { $continent = pathinfo($filename, PATHINFO_FILENAME); $helper->logLoading $continent«); $continent = str_replace(‘ ‘, ‘_’, $continent); $countries = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $countryCount = count($countries); // Transpose $countries from a row to a column array $countries = array_map(‘transpose’, $countries); $spreadsheet->getActiveSheet() ->fromArray($countries, null, $column . ‘1’); $spreadsheet->addNamedRange( new NamedRange( $continent, $spreadsheet->getActiveSheet(), ‘$’ . $column . ‘$1:$’ . $column . ‘$’ . $countryCount ) ); $spreadsheet->getActiveSheet() ->getColumnDimension($column) ->setVisible(false); $spreadsheet->getActiveSheet() ->setCellValue($continentColumn . ($key + 1), $continent); ++$column; } // Hide the dropdown data $spreadsheet->getActiveSheet() ->getColumnDimension($continentColumn) ->setVisible(false); $spreadsheet->addNamedRange( new NamedRange( ‘Continents’, $spreadsheet->getActiveSheet(), ‘$’ . $continentColumn . ‘$1:$’ . $continentColumn . ‘$’ . count($continents) ) ); // Set selection cells $spreadsheet->getActiveSheet() ->setCellValue(‘A1’, ‘Continent:’); $spreadsheet->getActiveSheet() ->setCellValue(‘B1’, ‘Select continent’); $spreadsheet->getActiveSheet() ->setCellValue(‘B3’, ‘=’ . $column . 1); $spreadsheet->getActiveSheet() ->setCellValue(‘B3’, ‘Select country’); $spreadsheet->getActiveSheet() ->getStyle(‘A1:A3’) ->getFont()->setBold(true); // Set linked validators $validation = $spreadsheet->getActiveSheet() ->getCell(‘B1’) ->getDataValidation(); $validation->setType(DataValidation::TYPE_LIST) ->setErrorStyle(DataValidation::STYLE_INFORMATION) ->setAllowBlank(false) ->setShowInputMessage(true) ->setShowErrorMessage(true) ->setShowDropDown(true) ->setErrorTitle(‘Input error’) ->setError(‘Continent is not in the list.’) ->setPromptTitle(‘Pick from the list’) ->setPrompt(‘Please pick a continent from the drop-down list.’) ->setFormula1(‘=Continents’); $spreadsheet->getActiveSheet() ->setCellValue(‘A3’, ‘Country:’); $spreadsheet->getActiveSheet() ->getStyle(‘A3’) ->getFont()->setBold(true); $validation = $spreadsheet->getActiveSheet() ->getCell(‘B3’) ->getDataValidation(); $validation->setType(DataValidation::TYPE_LIST) ->setErrorStyle(DataValidation::STYLE_INFORMATION) ->setAllowBlank(false) ->setShowInputMessage(true) ->setShowErrorMessage(true) ->setShowDropDown(true) ->setErrorTitle(‘Input error’) ->setError(‘Country is not in the list.’) ->setPromptTitle(‘Pick from the list’) ->setPrompt(‘Please pick a country from the drop-down list.’) ->setFormula1(‘=INDIRECT($B$1)’); $spreadsheet->getActiveSheet()->getColumnDimension(‘A’)->setWidth(12); $spreadsheet->getActiveSheet()->getColumnDimension(‘B’)->setWidth(30); // Save $helper->log(‘Not writing to Xls — formulae with defined names not yet supported’); $helper->write($spreadsheet, __FILE__, [‘Xlsx’]);

Мне нужно создать выпадающий список в 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();
?>

Понравилась статья? Поделить с друзьями:
  • Php excel в массиве
  • Php excel без библиотек
  • Php excel with csv
  • Php excel to pdf converter
  • Php excel spreadsheet excel writer