I am opening excel with com and it is working fine however I am having trouble apply two filters at the same time to same column. Here is the code:
$excel = new COM("excel.application") or die("Unable to instanciate excel");
$excel->Visible = 1;
$excel->DisplayAlerts = 1;
$wb = $excel->Workbooks->Open($dataFile);
$sheet = $wb->Worksheets(1);
// apply filters
$sheet->range("AS1")->AutoFilter(45, '<>'); // works with single filter
However when I want to apply two filters at the same time to same column, it doesnt work:
$sheet->range("AS1")->AutoFilter(45, '<> AND > 0'); // DOES NOT WORK
My guess is that instead of using AND as literal string in above statement, I should use actual excel constant Excel.XlAutoFilterOperator.xlAnd but I am unable to get it.
Any help will be greatly appreciated.
Okay figured it out, I had to pass extra parameters:
define('xlAnd', 1);
$sheet->range("AS1")->AutoFilter(45, '<>', xlAnd, '> 0');
Related
I have to create an Excel file with a data sheet that will vary according to a database and a sheet containing multiple PivotTables that have their own PivotCharts.
"data.xlsx" contains a sheet with all new data.
"graph.xlsx" contains a sheet with old data and a sheet with PivotTables.
My goal is to have "graph.xlsx" containing a sheet with all new data and the sheet with PivotTables.
I found a perfect lib to do this : https://github.com/svrnm/exceldatatables
But I block on the use of it, I would open "graph.xlsx" delete its sheet named "brut data", then to add a new sheet named "brut data" initialized with the new data contained in "data.xlsx".
To do it I saw this function from ExcelWorkbook.php a Class of this lib.
public function addWorksheet(ExcelWorksheet $worksheet, $id = null, $name = null)
But I don't understand how to use it.
(I'm the author of the mentioned library)
There are two steps you need to take, to achieve your goal, the first is reading the data.xlsx. The second is writing that data into your graph.xlsx. The library is solving step two:
require_once('../vendor/autoload.php');
$dataTable = new Svrnm\ExcelDataTables\ExcelDataTable();
$in = 'graph.xlsx';
$out = 'out.xlsx';
$data = /* ... step 1 ... */
$dataTable->showHeaders()->addRows($data)->attachToFile($in, $out);
For step 1 you could leverage PHPExcel. I haven't tested it, but something similar like this:
$r = PHPExcel_IOFactory::createReader('Excel2007');
$data = $r->load($filename)->getActiveSheet()->toArray(null, true, true);
There is another option: You could unpack both graph.xlsx and data.xlsx and merge the sheets.
I have a database field in SQL Server 2012 database. They can contain PDF, WORD, Excel or image files. My Blob field type is varbinary(max). My code works fine using ColdFusion, however I have tried to convert it to PHP and it doesn't seem to be working. Below is the code I am using. Can someone tell me what I am doing wrong?
The example below is just for a word document and when the Word application is launched, I get a "File Conversion" dialog box asking me to select the encoding that makes the document readable none of which makes any difference. The preview window shows a bunch of garbage.
<?PHP
$aserverName = "SQ-ENT12-D01\Dev";
$aconnectionInfo = array( "Database"=>"Event_Registration", "UID"=>$uid, "PWD"=>$pwd, "CharacterSet"=>"UTF-8");
$aconn = sqlsrv_connect( $aserverName, $aconnectionInfo);
// Get the record where the binary data is
$GetBlobSQL = "select * from Congress where Congress_ID = 102";
$GetBlob = sqlsrv_query($aconn, $GetBlobSQL, array(), array('Scrollable' => 'buffered'));
$GetBlobRecordCount = sqlsrv_num_rows($GetBlob);
$brec = sqlsrv_fetch_array( $GetBlob, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, 0);
$WhatFile = ($brec['Document_Agenda']);
$WhatBlob = ($brec['AD_Agenda']);
$MyExt = substr($WhatFile, -4);
$WhatExt = strtolower($MyExt);
header('Content-type: application/ms-word');
header('Content-Disposition: attachment; filename="'.$WhatFile.'"');
echo $WhatBlob;
?>
I know the file or data in the database is not corrupted because my original ColdFusion code works fine to retrieve and display the data.
Try removing "CharacterSet"=>"UTF-8" from the $aconnectionInfo. You may be confusing the database and causing conversions to take place that are not needed or desired.
I have the following Excel file:
I read it in by looping over every cell and getting the value with getCell(...)->getValue():
$highestColumnAsLetters = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); //e.g. 'AK'
$highestRowNumber = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$highestColumnAsLetters++;
for ($row = 1; $row < $highestRowNumber + 1; $row++) {
$dataset = array();
for ($columnAsLetters = 'A'; $columnAsLetters != $highestColumnAsLetters; $columnAsLetters++) {
$dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($columnAsLetters.$row)->getValue();
if ($row == 1)
{
$this->column_names[] = $columnAsLetters;
}
}
$this->datasets[] = $dataset;
}
However, although it reads in the data fine, it reads in the calculations literally:
I understand from discussions like this one that I can use getCalculatedValue() for calculated cells.
The problem is that in the Excel sheets I am importing, I do not know beforehand which cells are calculated and which are not.
Is there a way for me to read in the value of a cell in a way that automatically gets the value if it has a simple value and gets the result of the calculation if it is a calculation?
Answer:
It turns out that getCalculatedValue() works for all cells, makes me wonder why this isn't the default for getValue() since I would think one would usually want the value of the calculations instead of the equations themselves, in any case this works:
...->getCell($columnAsLetters.$row)->getCalculatedValue();
getCalculatedValue() seems to work for all cells, see above
If you are unsure about the content of a cell (value or formula included),
I recommend you to primarily do a check if the cell has a formula and then copy - paste accordingly. getOldCalculatedValue() is very helpful in this case. Here is an example of that:
$code = $sheet->getCell('A'.$y)->getValue();
if(strstr($code,'=')==true)
{
$code = $sheet->getCell('A'.$y)->getOldCalculatedValue();
}
$objPHPExcel4->setActiveSheetIndex(0)
->setCellValue('A'.$l, $code);
For large data sets, getCalculatedValue() function is really cumbersome and lots of memory will be required to perform correctly.
Looks like getCalculatedValue() is deprecated. Try using getFormattedValue() instead.
getCalculatedValue() seems to do the right job you wanted. It will return the correct value if the cell contains FBV ( formula based value ). If not then the normal value will be returned instead.
getCalculatedValue
seems to work for all cells
$sheets = $spreadsheet->getAllSheets();
$priceCasegetCellByColumnAndRow = $sheet->getCellByColumnAndRow(14, ($key))->getCalculatedValue()
$priceCasegetCell = $sheet->getCell('O' . $key)->getCalculatedValue();
I have never imported an excel file in PHP so this is just a stab in the dark.
Why not check the first character in the cell for an "="
If true getCalculatedValue()
if not getCell()
I have the following Excel file:
I read it in by looping over every cell and getting the value with getCell(...)->getValue():
$highestColumnAsLetters = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); //e.g. 'AK'
$highestRowNumber = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$highestColumnAsLetters++;
for ($row = 1; $row < $highestRowNumber + 1; $row++) {
$dataset = array();
for ($columnAsLetters = 'A'; $columnAsLetters != $highestColumnAsLetters; $columnAsLetters++) {
$dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($columnAsLetters.$row)->getValue();
if ($row == 1)
{
$this->column_names[] = $columnAsLetters;
}
}
$this->datasets[] = $dataset;
}
However, although it reads in the data fine, it reads in the calculations literally:
I understand from discussions like this one that I can use getCalculatedValue() for calculated cells.
The problem is that in the Excel sheets I am importing, I do not know beforehand which cells are calculated and which are not.
Is there a way for me to read in the value of a cell in a way that automatically gets the value if it has a simple value and gets the result of the calculation if it is a calculation?
Answer:
It turns out that getCalculatedValue() works for all cells, makes me wonder why this isn't the default for getValue() since I would think one would usually want the value of the calculations instead of the equations themselves, in any case this works:
...->getCell($columnAsLetters.$row)->getCalculatedValue();
getCalculatedValue() seems to work for all cells, see above
If you are unsure about the content of a cell (value or formula included),
I recommend you to primarily do a check if the cell has a formula and then copy - paste accordingly. getOldCalculatedValue() is very helpful in this case. Here is an example of that:
$code = $sheet->getCell('A'.$y)->getValue();
if(strstr($code,'=')==true)
{
$code = $sheet->getCell('A'.$y)->getOldCalculatedValue();
}
$objPHPExcel4->setActiveSheetIndex(0)
->setCellValue('A'.$l, $code);
For large data sets, getCalculatedValue() function is really cumbersome and lots of memory will be required to perform correctly.
Looks like getCalculatedValue() is deprecated. Try using getFormattedValue() instead.
getCalculatedValue() seems to do the right job you wanted. It will return the correct value if the cell contains FBV ( formula based value ). If not then the normal value will be returned instead.
getCalculatedValue
seems to work for all cells
$sheets = $spreadsheet->getAllSheets();
$priceCasegetCellByColumnAndRow = $sheet->getCellByColumnAndRow(14, ($key))->getCalculatedValue()
$priceCasegetCell = $sheet->getCell('O' . $key)->getCalculatedValue();
I have never imported an excel file in PHP so this is just a stab in the dark.
Why not check the first character in the cell for an "="
If true getCalculatedValue()
if not getCell()
Greetings all,
I'm trying to write a script that loads an existing spreadsheet containing a number of array formulas, add data to a worksheet and save it. When opening the file after the script runs, the spreadsheet's formulas are no longer array formulas.
Below is the stripped down version of what I'm attempting:
$excelFile = new PHPExcel();
$fileName = 'blah.xlsx';
$excelReader = PHPExcel_IOFactory::createReader('Excel2007');
$excelFile = $excelReader->load($fileName);
//first sheet contains formulas to process the resulting dump
$excelFile->setActiveSheetIndex(1);
// just to illustrate what's used when retrieving data
...
while($record = db_fetch_object($queryResult)) {
$excelFile->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $record->field);
}
$excelWriter = PHPExcel_IOFactory::createWriter($excelFile, 'Excel2007');
$excelWriter->save($fileName);
After the script runs, a formula that once appeared as:
{=SUM(A1:C6)}
Now appears as:
=SUM(A1:C6)
Thanks in advance for your insight and input
Tony
It seems that the PHPExcel Cell object does not handle a formula element's attributes, so things like "t=array" would be lost by the time you get to createWriter.
To resolve this issue, we've made modifications to the cell and excel2007 reader and writer classes.
In cell.php:
private $_formulaAttributes;
// getter and setter functions
In reader/excel2007.php:
line 769 - after $this->castToFormula...
if(isset($c->f['t'])){
$attributes = array();
$attributes = $c->f;
$docSheet->getCell($r)->setFormulaAttributes($attributes);
}
In writer/excel2007/worksheet.php:
line 1042 - after case 'f':
$attributes = $pCell->getFormulaAttributes();
if($attributes['t'] == 'array') {
$objWriter->startElement('f');
$objWriter->writeAttribute('t', 'array');
$objWriter->writeAttribute('ref', $pCell->getCoordinate());
$objWriter->writeAttribute('aca', '1');
$objWriter->writeAttribute('ca', '1');
$objWriter->text(substr($pCell->getValue(), 1));
$objWriter->endElement();
} else {
$objWriter->writeElement('f', substr($pCell->getValue(), 1));
}
hope this helps someone...
Unfortunately, the PHPExcel readers and writers don't yet support array formulas. I believed that the Excel2007 reader/writer did, but your experience suggests otherwise.