PHPExcel:.xls格式下数据验证不起作用

4

我有一个包含两个工作表的Excel文件:

  1. 工作表
  2. 列表- 显示在工作表中的项目列表。

请参见下面的图像:

List Worksheet

我想使用PHPExcel库生成此内容。 我已经尝试过了,但是没有得到预期的结果。 请看下面的代码:

$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Soumya Biswas")
                             ->setLastModifiedBy("Soumya Biswas")
                             ->setTitle("Office 2007 XLSX Test Document")
                             ->setSubject("Office 2007 XLSX Test Document")
                             ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                             ->setKeywords("office 2007 openxml php")
                             ->setCategory("Test result file");


// Create a first sheet
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A5', "List");


// Set data validation
$objValidation = $objPHPExcel->getActiveSheet()->getCell('B5')->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('"$List.$A$1:$A$10"');  // Make sure to put the list items between " and "  !!!

$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(1);
$objPHPExcel->getActiveSheet()->setTitle('List');

for ($i = 1; $i <= 10; $i++) {
    $objPHPExcel->getActiveSheet()->setCellValue("A{$i}", "List Item {$i}");
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);




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

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit; 
1个回答

8

我认为在引用另一个工作表中的单元格范围时,正确的语法是:

List!$A$1:$A$10

所以你应该尝试:

$objValidation->setFormula1('List!$A$1:$A$10'); // tested it, worked for me

http://phpexcel.codeplex.com/discussions/320393获取灵感:

->setFormula1("Worksheet!A1:{$endCell}1");// 工作....

虽然这个人在使用命名范围时遇到了另一个问题。

背景:我认为使用以下代码可以定义命名范围:

$objValidation->setFormula1('"$List.$A$1:$A$10"');

你明确地使用引号之间的给定字符串作为列表值,如此处(你可能是从这里获取这个片段的)或此处所解释的。但是,如果你不想使用固定的列表项而是动态引用它们,应该省略双引号。


2
$objValidation->setFormula1('List!$A$1:$A$10'); 这个可以工作,但如果我输入的值不在列表中,它会提示错误,然后如果你点击接受按钮,它会把错误的值放入单元格,我该如何防止这种情况发生?更新:使用 $objValidation->setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_STOP); - Diego

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接