I am trying to write variables from an array to the excel but i cannot write in certain instances
Code is as below
$workbook =new Spreadsheet_Excel_Writer();
$workbook->send("response.xls");
$row=1;
$col=1;
$workbook->setVersion(8);
$worksheet =& $workbook->addWorksheet('My sheet ');
$Allquestions = $questions->getQuestions();
foreach ($Allquestions as $qkey=>$qval) {
foreach ($studentResponses as $rval){
$astresp= $rval->getResponse($qkey);
//$worksheet->write($row,$col,'hiii');
$worksheet->write($row, $col, $astresp);
$col++;
}
$row++;
$col=1;
}
$workbook->close();
the $astresp when changed to 'hihi' prints hihi in the excel but when it remains as $astresp it fails to open excel.
Related
I have console app made in Symfony3, where user can import CSV file (which is validate) into database. I need to put records which haven't passed validation into separate file.
I use LeagueCSV to read CSV file and I try to use it to write unvalidated records but it doesn't work.
This is my code:
$reader = Reader::createFromPath($input->getArgument('lokalizacja'));
$reader->setDelimiter(';');
$reader->setHeaderOffset(0);
$results = $reader->getRecords();
foreach ($results as $row) {
$year = $row['description'];
$isValid = false;
if ($row['qty'] > 0 && $row['price'] > 0 && !empty($row['mpn'])) {
$isValid = true;
$rok = filter_var($row['description'], FILTER_SANITIZE_NUMBER_INT);
$product = (new Produkt())
->setMpn($row['mpn'])
->setQty($row['qty'])
->setYear($year)
->setPrice($row['price']);
$this->em->persist($product); }
if ($row['qty'] == 0 || $row['price'] == 0 || empty($row['mpn'])) {
$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
$writer->insertOne([$row['mpn'], $row['qty'], $row['price'],
$row['description']]);
continue;
}
}
$this->em->flush();
All records which passed validation are successfully saved in the database but I have problem with others records. In new CSV file I have only first, one record which haven't passed validation and nothing more. What am I doing wrong? I tried with
$writer->insertAll($results); //using an array
Or with if...else statment but that's nothing.
Also I made ...else statement where unvalidated records are saved in other table in database and its works but I don't know how to immediately convert them into CSV file.
Don't know symfony but CSV output is pretty simple. FWIW...
Pass this an array, like a fetchall resultset.
<?php
public function outputCSV($data, $useKeysForHeaderRow = true) {
if ($useKeysForHeaderRow) {
array_unshift($data, array_keys(reset($data)));
}
$outputBuffer = fopen("php://output", 'w');
foreach($data as $v) {
fputcsv($outputBuffer, $v);
}
fclose($outputBuffer);
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="FooBarFileName_' . date('Ymd') . '.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$this->outputCSV($results);
If you look at the doc page for the writer you will see a warning at the top which states
When inserting records into a CSV document using League\Csv\Writer, first insert all the data that need to be inserted before starting manipulating the CSV. If you manipulate your CSV document before insertion, you may change the file cursor position and erase your data.
Your code calls
$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
$writer->insertOne([$row['mpn'], $row['qty'], $row['price'], $row['description']]);
In every iteration the condition is met, this appears to be overwriting or dropping your previous insert every time. You should declare the $writer once before the loop starts in order to preserve each insert.
$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
foreach ($results as $row) {
// do stuff with $writer
}
I'm trying to create a spreadsheet (XLSX) from a array containing 60k entries. When it exports, it gives me a spreadsheet with a PHP OOM warning on it nothing else.
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
$rowIndex = 2;
foreach ($this->_values as $_val){
$activeSheet->setCellValueByColumnAndRow(1, $rowIndex, trim($_val['item1']));
$activeSheet->setCellValueByColumnAndRow(2, $rowIndex, trim($_val['item2']));
$activeSheet->setCellValueByColumnAndRow(3, $rowIndex, trim($_val['item3']));
$activeSheet->setCellValueByColumnAndRow(4, $rowIndex, trim($_val['item4']));
$activeSheet->setCellValueByColumnAndRow(5, $rowIndex, trim($_val['item5']));
$activeSheet->setCellValueByColumnAndRow(6, $rowIndex, trim($_val['item6']));
$activeSheet->setCellValueByColumnAndRow(7, $rowIndex, trim($_val['item7']));
$activeSheet->setCellValueByColumnAndRow(8, $rowIndex, trim($_val['item8']));
$activeSheet->setCellValueByColumnAndRow(9, $rowIndex, trim($_val['item9']));
$activeSheet->setCellValueByColumnAndRow(10, $rowIndex, trim($_val['item10']));
$activeSheet->setCellValueByColumnAndRow(11, $rowIndex, trim($_val['item11']));
$rowIndex += 1;
}
$spreadsheet->garbageCollect();
$writer = new Xlsx($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->setUseDiskCaching(true);
$writer->save("php://temp");
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
An out of memory error is because your system is, well, out of memory. You can simply increase the amount of memory using something like ini_set('memory_limit', '750M'); assuming your system has the space
Or, if XLSX isn't needed (that is: if you could use a CSV instead, which Excel can still open) you could stream the data to the spreadsheet instead of loading it all into memory at once, then printing. That would look like this:
foreach ($this->_values as $_val){
for($i=1; $i<=11; $i++) {
echo trim($_val['item'.$i]);
if($i<11) echo ",";
}
echo "\n";
}
You could also include the CSV header at the top of the PHP file, so the page would prompt a download instead of showing you the contents of the CSV file. This is the CSV header cal: header("Content-type: text/csv");
How to get Excel data into an array in PHP local site. I want to print data in Excel as array in my practice site. I have created Excel in htdocs as test.xlsx. How can I print it's data in PHP?
First include PhpExcel library into your code then use this
PHPExcel_IOFactory::addSearchLocation($filepath, $savedfilename);
$objReader = PHPExcel_IOFactory::load($filepath);
$data = array();
$worksheet = $objReader->getActiveSheet();
foreach ($worksheet->getRowIterator(2) as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$data[$cell->getRow()][$cell->getColumn()] = $cell->getValue();
}
}
print_r($data);
Can you please look at this link once, I think you can get more idea for your question.
http://www.phpgang.com/how-to-read-excel-file-insert-data-into-mysql-database-using-php_609.html
I am trying to export data to Excel using this PHP Class, so far things are working fine and the export is being generated. But now I have a new requirement of generating multiple sheets inside a single excel file.
For example if i have two arrays, i want both to be on separate sheets.
$myarray1 = array (
1 => array ("Oliver", "Peter", "Paul"),
array ("Marlene", "Mica", "Lina")
);
$myarray2 = array (
1 => array ("Oliver", "Peter", "Paul"),
array ("Marlene", "Mica", "Lina")
);
At present both arrays are being exported on a single sheet
$xls = new Excel_XML;
$xls->addArray ( $myarray );
$xls->addArray ( $myarray2 );
$xls->generateXML ( "testfile" );
I am wondering if someone tried this before and was able to achieve it and I will appreciate any help I can get on this.
i would suggest you to use PHPExcel library.supports variety of formats, can do visual formatting and is easy to use.
You can find more about it at their webpage: http://phpexcel.codeplex.com/
You can do a lot more of course, reading excel files, setting visual styles, creating plots, expressions and lot more.
you can even use fgetcsv http://php.net/manual/en/function.fgetcsv.php
this example using PHPExcel
function exportToExcelsheets($data, $fileName){
/* Create new PHPExcel object*/
$objPHPExcel = new PHPExcel();
$sheet_index = 0;
foreach ($data as $s=>$sheet){
/* Create a first sheet, representing sales data*/
$alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','V','W','X','Y','Z'];
$objPHPExcel->setActiveSheetIndex($sheet_index);
$head_keys = array_keys($sheet[0]);
foreach ($head_keys as $a=>$headval){
$objPHPExcel->getActiveSheet()->setCellValue($alpha[$a].'1', $headval);
}
$i=2;
foreach($sheet as $row) {
$index = 0;
foreach ($row as $v=>$value){
$value = isset($value)?$value:'';
$objPHPExcel->getActiveSheet()->setCellValue($alpha[$index].$i,$value);
$index++;
}
$i++;
}
/*Rename sheet*/
$objPHPExcel->getActiveSheet()->setTitle('sheet_'.$s);
/* Create a new worksheet, after the default sheet*/
$objPHPExcel->createSheet();
$sheet_index++;
}
/* Redirect output to a client’s web browser (Excel5)*/
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=\"$fileName\"");
header('Cache-Control: max-age=0');
//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//$objWriter->save('php://output');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
I'm trying to understand how to get data from cells in PHPExcel but I have no idea. I read all documentation and I made this:
<?php
include('PHPExcel/Classes/PHPExcel/Reader/Excel2007.php');
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true;
}
return false;
}
}
$objReader = new PHPExcel_Reader_Excel2007();
$objReader->setReadFilter( new MyReadFilter() );
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("sample_mymails222.xlsx");
print_r($objPHPExcel);
?>
print_r show very big array.
I think there is some functions to get data from cell in $objPHPExcel.
How to do it?
Thanx!
For anyone else who wants a more helpful answer, following the code in the example above, here is a quick snippet that will parse the active worksheet into a multi-dimensional array (this example ignores the ReadFilter that the OP created).
$data = array();
$worksheet = $objPHPExcel->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$data[$cell->getRow()][$cell->getColumn()] = $cell->getValue();
}
}
var_dump($data);
BTW The reason I say "more helpful answer" is that I also had a hard time figuring out the PHPExcel documentation (which consists of 6 separate documents and no real API-like reference) the first time around.
The OP says he "read all the docs", but I am guessing that, like me, he read through the file called PHPExcel User Documentation - Reading Spreadsheet Files.doc which explains how to read in a spreadsheet, but does not cover using the contents.
To find that out, you have to dig into PHPExcel developer documentation.doc and get down to part 4 (which is where I found the example above).
Yup, my fault for not being thorough, but clearly this is a recurring issue. :-)
for reading excel file you can use this
require_once('PHPExcel.php');
$input_file_type = PHPExcel_IOFactory::identify($excel_file);
$obj_reader = PHPExcel_IOFactory::createReader($input_file_type);
$obj_reader->setReadDataOnly(true);
$objPHPExcel = $obj_reader->load($excel_file);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highest_row = $objWorksheet->getHighestRow();
$highest_col = $objWorksheet->getHighestColumn();
//$highest_col_index = PHPExcel_Cell::columnIndexFromString($highest_col);
// start $row from 2, if you want to skip header
for ($counter = 2; $counter <= $highest_row; $counter++)
{
$row = $objWorksheet->rangeToArray('A'.$counter.':'.$highest_col.$counter);
$row = reset($row);
}
Please read the documentation chapter 4.5 (included in the PHPExcel download package)