I want to delete all rows that start with "//", from Excel sheet, with PHPExcel.
My code:
require '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/IOFactory.php';
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
$path = "del_head.xls";
$objPHPExcel = PHPExcel_IOFactory::load($path);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for($row=1; $row < $highestRow; ++$row){
$value = $objPHPExcel->getActiveSheet()->getCell('A'.$row)->getValue();
if (substr($value,0,2) == "//") {
$objPHPExcel->getActiveSheet()->removeRow($row, $row);
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save($path);
But, the code not delete all rows that start with "//".
I think the problem is with function 'removeRow'.
Thank you very much in advance.
Replace this line
$objPHPExcel->getActiveSheet()->removeRow($row, $row);
with
$objPHPExcel->getActiveSheet()->removeRow($row);
There's one obvious problem with your call to removeRow(): The first argument is the starting row, the second is the number of rows to remove; so if you find a // at row 5, then you're telling PHPExcel to remove 5 rows starting from row 5 (i.e. rows 5 to 9).
You're also reading a file with a .xls extension (assuming that it's a BIFF file from the extension), but saving with the same .xls filename as an OfficeOpenXML file (which is normally a .xlsx file).
So what format actually is your file? What does a call to the IOFactory's identify() method recognise it as? If it's actually a comma- or tab-separated value file (most likely to have a leading //), then you'd be better using PHP's fgetcsv() and fputcsv() functions to process it to remove those lines.
Try this code, Its worked me
$filename = 'path/example.xls';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$row_id = 1; // deleted row id
$number_rows = 2; // number of rows count
if ($objWorksheet != NULL) {
if ($objWorksheet->removeRow($row_id, $number_rows)) {
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
}
}
Please, check the value assigned on line:
$highestRow = $objWorksheet->getHighestRow();
I've tested this code and the value is always 1
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.
Need some help...
So, i'm trying to export data from database to excel file.
I'm able to fetch data to database,but when i'm exporting it to excel inside the while loop I only got one record.
Please help.I'm using PHPExcel 1.8.0 libray
Here is my code:
<?php
include('config/config_msdb.php');
/** Set default timezone (will throw a notice otherwise) */
date_default_timezone_set('Asia/Manila');
// include PHPExcel
require('lib/PHPExcel.php');
// create new PHPExcel object
$objPHPExcel = new PHPExcel;
// set default font
$objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri');
// set default font size
$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
/**
* Define currency and number format.
*/
// currency format, € with < 0 being in red color
$currencyFormat = '#,#0.## \€;[Red]-#,#0.## \€';
// number format, with thousands separator and two decimal points.
$numberFormat = '#,#0.##;[Red]-#,#0.##';
// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle('YellowCab');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A2:P2')->getFont()->setBold(true)->setSize(12);
// write header
$objSheet->getCell('A2')->setValue('Date');
$objSheet->getCell('B2')->setValue('TC Within 30 mins');
$objSheet->getCell('C2')->setValue('Total TC');
$objSheet->getCell('D2')->setValue('%');
$objSheet->getCell('E2')->setValue("Within 15 mins");
$objSheet->getCell('F2')->setValue("Total TC");
$objSheet->getCell('G2')->setValue("%");
$objSheet->getCell('H2')->setValue("Excellent TC");
$objSheet->getCell('I2')->setValue("Total TC");
$objSheet->getCell('J2')->setValue("%");
$objSheet->getCell('K2')->setValue('Good TC');
$objSheet->getCell('L2')->setValue('Total TC');
$objSheet->getCell('M2')->setValue('%');
$objSheet->getCell('N2')->setValue('Poor TC');
$objSheet->getCell('O2')->setValue('Total TC');
$objSheet->getCell('P2')->setValue('%');
//get record
$query="SELECT pr.TransDate,pr.TC30,pr.Total_TRX1,cast(round(pr.Hitrate,0) as nvarchar (10))+'%' AS Hitrate ,pr.PDT15,pr.Total_TRX2,cast(round(pr.ProdTime,0) as nvarchar(10))+'%' AS ProdTime,pr.Excellence,pr.Total_TRX4,
cast(round(pr.ExcelPercent,0) as nvarchar(10))+'' AS ExcelPercent,pr.Good,pr.Total_TRX5,cast(round(pr.GoodPercent,0) as nvarchar(10))+'%' AS GoodPercent,
pr.Poor,pr.Total_TRX6,cast(round(pr.PoorPercent,0) as nvarchar(10))+'%' AS PoorPercent,lp.area_name FROM part_view AS pr
LEFT JOIN lp_areas AS lp ON lp.id = pr.StoreID
WHERE lp.is_delete=0 AND lp.area_status=1 AND lp.id!='43' ORDER BY pr.TransDate DESC";
$que = mssql_query($query);
$i = '3';
while($row=mssql_fetch_array($que)){
$transdate=date('Y-m-d',strtotime($row["TransDate"]));
$tc30=$row["TC30"];
$totaltrx1=$row["Total_TRX1"];
$hitrate=$row["Hitrate"];
$pdt15=$row["PDT15"];
$totaltrx2=$row["Total_TRX2"];
$prodtime=$row["ProdTime"];
$excellence=$row["Excellence"];
$totaltrx4=$row["Total_TRX4"];
$excelpercent=$row["ExcelPercent"];
$good=$row["Good"];
$totaltrx5=$row["Total_TRX5"];
$goodpercent=$row["GoodPercent"];
$poor=$row["Poor"];
$totaltrx6=$row["Total_TRX6"];
$poorpercent=$row["PoorPercent"];
$storename=$row["area_name"];
// we could get this data from database, but here we are writing for simplicity
$objSheet->getCell('A'.$i.'')->setValue($transdate);
$objSheet->getCell('B'.$i.'')->setValue($tc30);
$objSheet->getCell('C'.$i.'')->setValue($totaltrx1);
$objSheet->getCell('D'.$i.'')->setValue($hitrate);
$objSheet->getCell('E'.$i.'')->setValue($pdt15);
$objSheet->getCell('F'.$i.'')->setValue($totaltrx2);
$objSheet->getCell('G'.$i.'')->setValue($prodtime);
$objSheet->getCell('H'.$i.'')->setValue($excellence);
$objSheet->getCell('I'.$i.'')->setValue($totaltrx4);
$objSheet->getCell('J'.$i.'')->setValue($excelpercent);
$objSheet->getCell('K'.$i.'')->setValue($good);
$objSheet->getCell('L'.$i.'')->setValue($totaltrx5);
$objSheet->getCell('M'.$i.'')->setValue($goodpercent);
$objSheet->getCell('N'.$i.'')->setValue($poor);
$objSheet->getCell('O'.$i.'')->setValue($totaltrx6);
$objSheet->getCell('P'.$i.'')->setValue($poorpercent);
$i++;
// autosize the columns
$objSheet->getColumnDimension('A')->setAutoSize(true);
$objSheet->getColumnDimension('B')->setAutoSize(true);
$objSheet->getColumnDimension('C')->setAutoSize(true);
$objSheet->getColumnDimension('D')->setAutoSize(true);
$objSheet->getColumnDimension('E')->setAutoSize(true);
$objSheet->getColumnDimension('F')->setAutoSize(true);
$objSheet->getColumnDimension('G')->setAutoSize(true);
$objSheet->getColumnDimension('H')->setAutoSize(true);
$objSheet->getColumnDimension('I')->setAutoSize(true);
$objSheet->getColumnDimension('J')->setAutoSize(true);
$objSheet->getColumnDimension('K')->setAutoSize(true);
$objSheet->getColumnDimension('L')->setAutoSize(true);
$objSheet->getColumnDimension('M')->setAutoSize(true);
$objSheet->getColumnDimension('N')->setAutoSize(true);
$objSheet->getColumnDimension('O')->setAutoSize(true);
$objSheet->getColumnDimension('P')->setAutoSize(true);
//Setting the header type
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="file.xlsx"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
/* If you want to save the file on the server instead of downloading, replace the last 4 lines by
$objWriter->save('test.xlsx');
*/
}//end get rows
?>
Thanks in advance
Just to update I have successfully exported all data fetched from my database.
So here is my solution:
$i = '3';
while($row=mssql_fetch_array($que)){
$transdate=date('Y-m-d',strtotime($row["TransDate"]));
$tc30=$row["TC30"];
$totaltrx1=$row["Total_TRX1"];
$hitrate=$row["Hitrate"];
$pdt15=$row["PDT15"];
$totaltrx2=$row["Total_TRX2"];
$prodtime=$row["ProdTime"];
$excellence=$row["Excellence"];
$totaltrx4=$row["Total_TRX4"];
$excelpercent=$row["ExcelPercent"];
$good=$row["Good"];
$totaltrx5=$row["Total_TRX5"];
$goodpercent=$row["GoodPercent"];
$poor=$row["Poor"];
$totaltrx6=$row["Total_TRX6"];
$poorpercent=$row["PoorPercent"];
$storename=$row["area_name"];
$data[] = array(
'TransDate'=>$transdate,
'TC30'=>$tc30,
'Total_TRX1'=>$totaltrx1,
'Hitrate'=>$hitrate,
'PDT15'=>$pdt15,
'Total_TRX2'=>$totaltrx2,
'ProdTime'=>$prodtime,
'Excellent'=>$excellent,
'Total_TRX4'=>$totaltrx4,
'ExcelPercent'=>$excelpercent,
'Good'=>$good,
'Total_TRX5'=>$totaltrx5,
'GoodPercent'=>$goodpercent,
'Poor'=>$poor,
'Total_TRX6'=>$totaltrx6,
'PoorPercent'=>$poorpercent
);
}
$array = stripslashes(json_encode($data));
$json = (object)json_decode($array);
foreach($json AS $datas){
$objSheet->getCell('A'.$i.'')->setValue($datas->TransDate);
$objSheet->getCell('B'.$i.'')->setValue($datas->TC30);
$objSheet->getCell('C'.$i.'')->setValue($datas->Total_TRX1);
$objSheet->getCell('D'.$i.'')->setValue($datas->Hitrate);
$objSheet->getCell('E'.$i.'')->setValue($datas->PDT15);
$objSheet->getCell('F'.$i.'')->setValue($datas->Total_TRX2);
$objSheet->getCell('G'.$i.'')->setValue($datas->ProdTime);
$objSheet->getCell('H'.$i.'')->setValue($datas->Excellence);
$objSheet->getCell('I'.$i.'')->setValue($datas->Total_TRX4);
$objSheet->getCell('J'.$i.'')->setValue($datas->ExcelPercent);
$objSheet->getCell('K'.$i.'')->setValue($datas->Good);
$objSheet->getCell('L'.$i.'')->setValue($datas->Total_TRX5);
$objSheet->getCell('M'.$i.'')->setValue($datas->GoodPercent);
$objSheet->getCell('N'.$i.'')->setValue($datas->Poor);
$objSheet->getCell('O'.$i.'')->setValue($datas->Total_TRX6);
$objSheet->getCell('P'.$i.'')->setValue($datas->PoorPercent);
$i++;
}
Thanks!
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;
}
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
This is my reader code. I'm not able to read the date in my Excel file using this code; it's returning the code like 030567 some thing.
My Excel file has the date value but this code is not returning the date. I don't know how to resolve this issue.
You need to use format like below code:
getCellByColumnAndRow($col, $row)->getValue())->format('m/d/Y');
Hope this will resolve your problem.
Or you can also try this:
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
$phpDateTimeObject = PHPExcel_Shared_Date::ExcelToPHPObject($data_value);
echo phpDateTimeObject->format('Y-m-d');
So, i have a form which able to read excel files and save to database by uploading an excel file. It is fine when i upload .xls file, but not with the .xlsx. Here is the code:
echo ' File berhasil diupload => '.$dok['file_name']; //success to echo uploaded .xlsx file
//EXCEL READING, load library
$this->load->library('excel');
//Identify the type of $inputFileName
$inputFileType = PHPExcel_IOFactory::identify(FCPATH."/asset/files/uploads/".$dok['file_name']);
//Create a new Reader of the type that has been identified
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
//Failed to echo (if i upload .xlsx file)
echo 'input file type => '.$inputFileType;
//begin to read excel file
$this->excel = $objReader->load(FCPATH."/asset/files/uploads/".$dok['file_name']);
$objWorksheet=$this->excel->getActiveSheet();
$highestRow=$objWorksheet->getHighestRow();
$highestColumm = $objWorksheet->getHighestColumn();
$highestColumm++;
//jika option timpa, maka delete semua data
if($timpa == 'y')
{
$this->_model->del_table_mcactivity();
}
//read per row and save to database
foreach($this->excel->getWorksheetIterator() as $worksheet){
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns= ord($highestColumn) - 64;
for ($row = 2; $row <= $highestRow; ++ $row) {
$kodemak = $objWorksheet->getCell("A$row")->getValue();
$tahun = $objWorksheet->getCell("B$row")->getValue();
$unitkerja = $objWorksheet->getCell("C$row")->getValue();
$nomorkegiatan = $objWorksheet->getCell("D$row")->getValue();
$kegiatan = $objWorksheet->getCell("E$row")->getValue();
$noskkegiatan = $objWorksheet->getCell("F$row")->getValue();
$jenis = $objWorksheet->getCell("G$row")->getValue();
$pagu = $objWorksheet->getCell("H$row")->getValue();
//get for refworkingunit id
$idrefworkingunit = $this->_model->get_workingunit_by_name($unitkerja);
//filtering for budget
$budget = $this->filter_budget($pagu);
//grouping variable to save in database
$activity_data = array('year'=>$tahun, 'idrefworkingunit'=>$idrefworkingunit, 'activitynumber'=>$nomorkegiatan, 'activityname'=>$kegiatan, 'activityreference'=>$noskkegiatan, 'accountnumber'=>$kodemak, 'traveltype'=>$jenis, 'budget'=> $budget);
//insert to database
$this->db->insert('mcactivity', $activity_data);
}
}
I use PHPExcel_IOFactory::identify() to identify the reader should be used. But i think it's failed.I've read this question , then i replace
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
with:
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); but it still doesn't work. Can somebody help me, please ?
XLS and XLSX are two different files types.
XLS
$this->load->library('Excel5');
XLSX
$this->load->library('Excel2007');
Consult the documentation "PHPExcel User Documentation - Reading Spreadsheet Files.doc" that comes with PHPExcel. Page 1 explains the formats, and Page 4 explains different ways of telling PHPExcel what file type to handle.
There are multiple lines where the reference to "Excel2007" and "Excel5" might occur.
Do a search on 'Excel' and not over-look any possibility.
e.g. $objReader = new PHPExcel_Reader_Excel2007(); //was Excel5
Change to _Excel2007 did allow me to read a .xlsx file, but did not break a script that read a .xls file. So there might be backwards compatibility.