I am trying to create an Excel spreadsheet using PHPExcel.
I would like to validate a specific column. I know how to validate a cell, but I can't seem to find a method for validating a column. Can I do better than manually looping through all cells of a column?
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';<br/>
$filename='test.xlsx';<br/>
if(file_exists($filename)){<br/>
unlink($filename);<br/>
}
$objExcel = new PHPExcel();<br/>
$objWriter = new PHPExcel_Writer_Excel5($objExcel);<br/>
$objExcel->setActiveSheetIndex(0);<br/>
$objActSheet = $objExcel->getActiveSheet();<br/>
$objValidation = $objActSheet->getCell("A1")->getDataValidation(); //这一句为要设置数据有效性的单元格<br/>
$objValidation->setType(PHPExcel_Cell_DataValidation::TYPE_LIST)<br/>
->setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_INFORMATION)<br/>
->setAllowBlank(false)<br/>
->setShowInputMessage(true)<br/>
->setShowErrorMessage(true)<br/>
->setShowDropDown(true)<br/>
->setErrorTitle('输入的值有误')<br/>
->setError('您输入的值不在下拉框列表内.')<br/>
->setFormula1('"列表项1,列表项2,列表项3"')<br/>
->setPromptTitle('设备类型');<br/>
$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');<br/>
$objWriter->save('test.xlsx');<br/>
Yes, you can do better!
For example if you want to apply validation on cells A1:A10, this will do the job:
$objActSheet->setDataValidation("A1:A10", $objValidation);
Sources:
PHPExcel Github issue
Relevant SO answer
PhpSpreadsheet Update (after 2019)
Since PHPExcel was archived in 2019 and should not be used anymore (see PHPExcel Repository), I'll provide an update for people finding this question while using the official PHPExcel successor PhpSpreadsheet.
You'd now create a validation and then apply it to a whole cell range like that:
$validation = $productSheet
->getCell("A1")
->getDataValidation()
->setType(DataValidation::TYPE_LIST)
->setFormula1('"列表项1,列表项2,列表项3"')
->setAllowBlank(false)
->setShowDropDown(true)
->setShowInputMessage(true)
->setPromptTitle('设备类型')
->setShowErrorMessage(true)
->setErrorStyle(DataValidation::STYLE_INFORMATION)
->setErrorTitle('输入的值有误')
->setError('您输入的值不在下拉框列表内.');
// Apply the validation to the rest of column A
$validation->setSqref('A2:A1048576');
Link to the official documentation
Related
I need to create an excel table with help of php. Is that possible? The php code below creates and write to an excel file. I would like to create an excel table with the data, see picture below. I'm using PhpSpreadsheet (sorry I forgot to say that)
Edit: The code below uses library PhpSpreadsheet to ceate a excel file with some content.
I want to create an excel table:
The code works and create the content as the second picture below shows. This is NOT an excel table, just plain text in cells.
But that is not what I want. I want to be able to create the content as the first picture below shows. This is an excel table. When you create an excel table by hand you can choose colrs etc. I do not care about the colors. Excel add the column name and push the content down.
What I have tried is to add: $sheet->setAutoFilter('A1:B5'); to the code, but this does not create an excel table as shown in the third picture below.
So the question is: What do I need to add to the code above to be able to create the content as shown in the first picture below
The fourth picture below shows how to crate an excel table in excel (and this is what I want the php code to do)
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'A1');
$sheet->setCellValue('A2', 'A2');
$sheet->setCellValue('A3', 'A3');
$sheet->setCellValue('A4', 'A4');
$sheet->setCellValue('A5', 'A5');
//$sheet->setCellValue('A6', 'A6');
$sheet->setCellValue('B1', 'B1');
$sheet->setCellValue('B2', 'B2');
$sheet->setCellValue('B3', 'B3');
$sheet->setCellValue('B4', 'B4');
$sheet->setCellValue('B5', 'B5');
$writer = new Xlsx($spreadsheet);
$writer->save('CreateExcelTable.xlsx');
The picture below show the tableI would like to create
With the code above this is created:
With the code added:
$sheet->setAutoFilter('A1:B5');
The picture below show what is created.It is not a table
Insert/Table is simply a GUI "shortcut" method for styling and setting autofilters against a block of cells. Both of these can be done as individual tasks using PHPSpreadSheet, but the library does not provide a "shortcut" way of doing this with a single method call.
Take a look at section of the Developer documentation.
I have a similar problem.
My Excel Template had some array formulas that refer to Named Data Tables,
(instead of writing in the array formula A2:A150 i would simply write NameOfMyTable[NameOfColumn])
When i inserted some data in my template using PhpSpreadSheet and downloaded the produced excel file, Each instance of NameOfMyTable[NameOfColumn] was replaced with REF!
Instead of searching how make or preserve Named Data Tables while using PHPSpreasheet. I simply converted all my Named tables back to simple ranges. (you can easily do this conversion through TableTools in excel without having to change every formula in your Excel Template).
I have a code I wrote, use it if you want
look at the code
using
$excelExport = new ExcelExport(['name' => 'dılo'], 'file');
$excelExport->download();
shortest excel creation example with php
basic example
<?php
$file="demo.xls";
$test="<table ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>
I try to have multiple formatted tables in one worksheet. The template looks like following example: Template
The tables are styled with table format templates.
If i run the code:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
$inputFileName = 'template/Age.xlsx';
$inputFileType = 'Xlsx';
if (!file_exists($inputFileName)) {
echo('File ' . $inputFileNameShort . ' does not exist');
}
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$writer = new Xlsx($spreadsheet);
$writer->save(Age.xlsx);
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
The formation is not overtaken to the new Age.xlsx file.
If I try to style the tables by hand, I run in an issue with the AutoFilter. It seams to be that only one filter range can be set. I tried following code:
$ageSheet =$spreadsheet->getSheet(0);
$ageSheet->setAutoFilter('A3:B10');
$ageSheet->setAutoFilter('D3:E9');
$ageSheet->setAutoFilter('A17:B24');
$ageSheet->setAutoFilter('D17:E23');
Only the last range will be set.
My questions are:
Is it possible to have more then one table in a worksheet using PHPSpreadsheet?
How can I realize this kind of output shown above?
Version
Excel MS Excel 2013
PHPSpreadsheet [1.2.1] - 2018-04-10
In MS excel can be set only one real filter. To have more then one on a Worksheet, you have to use format templates. Format templates uses pivot tables to realize the multifilter behavior.
PHPspreadsheet uses the table filtering and overrides the filtering every time by use of the setAutoFilter method. That means onlyone per worksheet is posible.
There is at the Moment no support of pivot tables in PHPspreadsheet.
At the moment it is not possible to have more the one filtered table in one worksheet.
After looking over the documentation for Box/Spout I do not see a way to format cells for currency.
NOTE: PhpExcel and PhpSpreadsheet are not an option.
Is there a way to format a cell?
While styling, is there a way to set the width of the cells?
This is my code so far.
It works, but is lacking currency formatting and width:
$writer = WriterFactory::create(Type::XLSX); // for XLSX files
$writer->openToFile($tmpfile); // write data to a file or to a PHP stream
$writer_sheet = $writer->getCurrentSheet();
$writer_sheet->setName($invoiceSheetName);
$headerStyle = (new StyleBuilder())
->setFontBold()
->setFontUnderline()
->build();
// add header with style
$writer->addRowWithStyle($header, $headerStyle);
$writer->addRows($resultsArray); // add multiple rows at a time
$writer->close();
$excelOutput = file_get_contents($tmpfile);
Documentation:
Spout Documentation
Help is greatly appreciated.
Decided to implement my own implementation with unzipping the xlsx file and modifying the correct xml file.
I wanted to append data in the pre formated excel sheet that is basically header footer in the excel sheet I wanted to append the contents. And will create many files dynamically.
A simple workaround is:
create a html table with the formatting you need
add values in php to the table (or generate table with php)
save file as .xls (filled with content from html table)
open file (will show formatted table in Excel)
Reason:
handling XLS files is very complex and many libraries have big limits (only available on windows servers....)
html table saved as .xls can be opened in Excel.
Thanks I have found the way PHPExcel is a good library.
In order to get PHPExcel http://www.codeplex.com/PHPExcel working with CodeIgniter, there are a few steps you must take to ensure compatibility with CodeIgniter's naming standards.
1: Class names must match the file names. PHPExcel has a few files(such as PHPExcel/IOFactory.php) that have names like PHPExcel_IOFactory. Change these names by removing the "PHPExcel_" part. These constructors in these files must be public in order for CI to access them.
$this->load->library('phpexcel');
$this->load->library('PHPExcel/iofactory');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("title")
->setDescription("description");
// Assign cell values
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'cell value here');
// Save it as an excel 2003 file
$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save("nameoffile.xls");
I'm trying to set up the print options for an excel file in PHPExcel. I'm working from the packaged API documents (version 1.7.7) but can't find any methods to do this. Am I missing a setting somewhere?
This setting is found in MS Excel under Print > Page Setup > Sheet.
$objPHPExcel->getActiveSheet()->setPrintGridlines(TRUE);
EDIT
setPrintGridlines() identifies whether gridlines around cells should be displayed when printing a worksheet from MS Excel; the default is FALSE. setShowGridlines() identifies whether gridlines around cells should be displayed when the spreadsheet is shown in the MS EXcel GUI; the default is TRUE;
I've found the one I was looking for. It was under the Worksheet class and not the page setup class as I'd previously thought.
For anyone looking in future, this is the method you need:
PHPExcel_Worksheet setPrintGridlines( [boolean $pValue = false])
There are two functions very similar though: setPrintGridlines and setShowGridlines. I'm not quite sure of the difference. Can anyone enlighten me?