I installed Excelbundle with PhpExcel library. I want to read excel files I found this function.
How can I use it? Any suggestion?
public function xlsAction()
{
$filenames = "your-file-name";
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);
foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
echo ' Row number - ' , $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
}
}
}
}
}
My suggestion is "Read the documentation" and start hacking at it. Working with excel is, in my experience, quite complex and time consuming so don't expect other people to solve your problem online.
It seems like you're talking about this bundle:
https://github.com/liuggio/ExcelBundle
It has great documentation, even full examples (see "Fake Controller").
With PHPExcel it is quite easy to read a Excel document.
See my example :
$dir = $this->getContainer()->getParameter("kernel.root_dir") . "/../../data/import/";
$file_name = "my_excel_file.xlsx";
$excel = $this->getContainer()->get('phpexcel')->createPHPExcelObject($dir . DIRECTORY_SEPARATOR . $file_name);
$sheet = $excel->getActiveSheet();
$row = 0;
while ($sheet->getCellByColumnAndRow(1, $row)->getValue()) {
$data = $sheet->getCellByColumnAndRow(2, $row)->getValue(); // get value from nth line and 2nf column
//do stuff -- see doc for functions on $sheet
}
Related
I just started using PHPExcel yesterday. It works like a charm except when I use it to read xlsx file downloaded from internet. It is not able to read the file until I open the dowloaded file and save it explicitly without making any change.
$objPHPExcel = PHPExcel_IOFactory::load($inputFile);
Line I use to load the Excel file.
Where am I going wrong? Am I missing some code. Something else needs to be written along with the above line of code to load the file.
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($col==0){
$val = \PHPExcel_Style_NumberFormat::toFormattedString($val, 'YYYY-MM-DD');
}
$dataArr[$row][$col] = $val;
}
This code is able to read the excel when I open the excel and save it.
So, I'm a fairly new PHP programmer and I'm trying to set up a page that uploads a file, displays the info in a table, then writes the data to a database.
I've got these things working (I found some helpful code online) however my dates are displaying incorrectly.
For example, the date "2/15/2017 17:55" is displaying as "42781.746527778".
Here is the code:
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
echo '<center><table style="width:50%;" border=1>';
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 1; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL, TRUE, FALSE);
echo "<tr>";
foreach($rowData[0] as $k=>$v)
echo "<td>".$v."</td>";
echo "</tr>";
}
echo '</table></center>';
}
else{
echo '<p style="color:red;">Please upload file with xlsx extension only.</p>';
}
I get why it is displaying the date that way, however I'm not having luck in fixing it when trying to display the entire column as a date and time, or displaying it in a single cell as the correct date and time.
var_dump($objPHPExcel->getActiveSheet()->getCell('B2')->getFormattedValue());
This code displays the correct date and time for one of my sample spreadsheets, however I'm not able to get that value in the cell.
Any help would be appreciated. Thank you!
I believe this is what you are looking for? Check if the cell is a Excel date and time then extract and convert the Excel date to a PHP date.
if(PHPExcel_Shared_Date::isDateTime($k)) {
$v = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($v));
}
Searched for quite a while now, but I'm stuck at the following problem.
I am using PHPexcel 1.8.0
The spreadsheet is read using the following code:
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, TRUE);
So far ok and it works well.
But some spreadsheets contain external referenced data.
And for that I want to use "getOldCalculatedValue".
How do I combine "getOldCalculatedValue" with "rangeToArray" ?
Or is "rangeToArray" inappropriate for this ?
Thanks for any help or hints !
Simple answer, you can't combine the two
rangeToArray() is a simple method for a simple purpose, it doesn't try to do anything clever, simply to return the data from the worksheet as efficiently and quickly as possible
getOldCalculatedValue() is used for a very specific circumstance, and isn't guaranteed to be correct even then, because it retrieves the last value calculated for the cell in MS EXcel itself, which ,ay not be correct if the external workbook wasn't available to MS Excel in that circumstance, or MS Excel formula evaluation was disable.
When calculating cells values from a formula, the PHPExcel calculation engine should use the getOldCalculatedValue() as a fallback if it finds an external reference, and rangeToArray() will try to use this method, but it isn't perfect, especially when that reference in nested deep inside other formulae referenced in other cells.
If you know that a formula in a cell contains an external reference, you should use getOldCalculatedValue() directly for that cell
I came up with the following solution.
Maybe not perfect, but it currently does the job. Thanks for any improvements!
With PHPExcel included and the excel file uploaded and ready, I continue with:
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
Create a new array to store the cell values of a row
$arr_row = array();
Loop through the rows
for ($rownumber = 2; $rownumber <= $highestRow; $rownumber++){
$row = $sheet->getRowIterator($rownumber)->current();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
Then loop through the cells of the current row
foreach ($cellIterator as $cell) {
Find cells with a formula
$cellcheck = substr($cell->getValue(),0,1);
if($cellcheck == '='){
$cell_content = $cell->getOldCalculatedValue();
}
else{
$cell_content = $cell->getValue();
}
Add the cell values to the array
array_push($arr_row,$cell_content);
Close cell loop
}
At this point I use the $arr_row to do further calculations and string formatting, before finally inserting it into a mysql table.
Close row loop
}
I made some changes in the function rangeToArray() inside Worksheet.php.
Worked fine!
public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Returnvalue
$returnValue = array();
// Identify the range that we need to extract from the worksheet
list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange);
$minCol = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] -1);
$minRow = $rangeStart[1];
$maxCol = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] -1);
$maxRow = $rangeEnd[1];
$maxCol++;
// Loop through rows
$r = -1;
for ($row = $minRow; $row <= $maxRow; ++$row) {
$rRef = ($returnCellRef) ? $row : ++$r;
$c = -1;
// Loop through columns in the current row
for ($col = $minCol; $col != $maxCol; ++$col) {
$cRef = ($returnCellRef) ? $col : ++$c;
// Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
// so we test and retrieve directly against _cellCollection
if ($this->_cellCollection->isDataSet($col.$row)) {
// Cell exists
$cell = $this->_cellCollection->getCacheData($col.$row);
if ($cell->getValue() !== null) {
if ($cell->getValue() instanceof PHPExcel_RichText) {
$returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
} else {
if ($calculateFormulas)
{ ##################################### CHANGED LINES
if(!preg_match('/^[=].*/', $cell->getValue()))
{
$returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); # THE ORIGINAL CODE ONLY HAD THIS LINE
}
else
{
$returnValue[$rRef][$cRef] = $cell->getOldCalculatedValue();
}
} ##################################### CHANGED LINES
else
{
$returnValue[$rRef][$cRef] = $cell->getValue();
}
}
if ($formatData) {
$style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString(
$returnValue[$rRef][$cRef],
($style && $style->getNumberFormat()) ?
$style->getNumberFormat()->getFormatCode() :
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
}
} else {
// Cell holds a NULL
$returnValue[$rRef][$cRef] = $nullValue;
}
} else {
// Cell doesn't exist
$returnValue[$rRef][$cRef] = $nullValue;
}
}
}
// Return
return $returnValue;
}
Current I have WP code like this. I need to make it translateable by poedit. How do I wrap the code to make it work? Im not sure which method is use for this case. Some thing like:
<?php my_e( 'Total sales' ); ?> or __('Total sales', 'my')
This is the code. I need to translate ["Sales amount"], ["Number of sales"]
foreach ($results as $result) {
$date = $result->formatted_post_date;
$statistics[$date]["Sales amount"] += $wp_list_table->column_total_sales($result->ID);
$statistics[$date]["Number of sales"]++;
$statistics[$date]["date"] = $date;
$max_number_of_sales = max(array($max_number_of_sales,$statistics[$date]["Number of sales"] )); }
Thank you for help
You have to use __('string','textdomain') to assign a translated string to some variable. And _e('string','textdomain') to echo a translated string. See I18n_for_WordPress_Developers.
Two observations:
you'll not be able to translate array keys, see php.net/manual/en/language.types.array.php
what you're doing seems wrong. I'd do it like:
$sales_amount = 0;
$sales_number = 0;
foreach ($results as $result) {
$sales_amount += $wp_list_table->column_total_sales($result->ID);
$sales_number++;
$date = $result->formatted_post_date;
$statistics[$date]["sales_amount"] = $sales_amount;
$statistics[$date]["sales_number"] = $sales_number;
}
echo __( 'Sales Amount', 'my' ) . $sales_amount;
I am trying to rename upload filenames match the Post Title.
This other thread shows how to rename to hash:
Rename files during upload within Wordpress backend
Using this code:
function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
Does anyone know the code to rename the file to match Post Title.extension?
barakadam's answer is almost correct, just a little correction based on the comment I left below his answer.
function new_filename($filename, $filename_raw) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$new = $post->post_title . $ext;
// the if is to make sure the script goes into an indefinate loop
if( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new;
}
add_filter('sanitize_file_name', 'new_filename', 10, 2);
Explanation of code:
Lets assume you upload a file with the original filename called picture one.jpg to a post called "My Holiday in Paris/London".
When you upload a file, WordPress removes special characters from the original filename using the sanitize_file_name() function.
Right at the bottom of the function is where the filter is.
// line 854 of wp-includes/formatting.php
return apply_filters('sanitize_file_name', $filename, $filename_raw);
At this point, $filename would be picture-one.jpg. Because we used add_filter(), our new_filename() function will be called with $filename as picture-one.jpg and $filename_raw as picture one.jpg.
Our new_filename() function then replaces the filename with the post title with the original extension appended. If we stop here, the new filename $new would end up being My Holiday in Paris/London.jpg which all of us know is an invalid filename.
Here is when we call the sanitize_file_name function again. Note the conditional statement there. Since $new != $filename_raw at this point, it tries to sanitize the filename again.
sanitize_file_name() will be called and at the end of the function, $filename would be My-Holiday-in-Paris-London.jpg while $filename_raw would still be My Holiday in Paris/London.jpg. Because of the apply_filters(), our new_filename() function runs again. But this time, because $new == $filename_raw, thats where it ends.
And My-Holiday-in-Paris-London.jpg is finally returned.
Something like this? (considering $post is your post variable, make it global):
function new_filename($filename) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
return $post->post_title . $ext;
}
add_filter('sanitize_file_name', 'new_filename', 10);
Did I understand you?