PHPExcel; Issue with Array from MySQL - php

I'm new to PHPExcel, obviously.. I'm also pretty new to PHP in itself.
The website has multiple levels of authority for viewing/editing.
I've been working on a page for a website that gathers information stored in the SQL database and populates an excel template.
application.php contains all the database connections etc.
Basically, the problem I'm having is when I call on the array to populate cells it shows up as duplicates of the same array value. Not only that, but it crams them all onto the same column.
The Values I would need to populate are:
Part No. Description U/Price Q'ty Total
15666562003 Lamp Assembly $20.00 1 $20.00
Freight 131514 $12.35 1 $12.35
The data would show up like this:
Part No. Description U/Price Q'ty Total
Freight Freight 131514 131514 $12.35 $12.35 1 1 $12.35 $12.35
Any help would be much appreciated!!
<?php
include "./include/application.php";
require './Classes/PHPExcel.php';
error_reporting(E_ALL ^ E_NOTICE);
class CForm extends CApplication
{
function CForm()
{
$this->CApplication();
}
//**********************************************************
function Export($msg = "")
{
if ($_SESSION['aID'] == "" && $_SESSION['mID'] == "237" && $_SESSION['mID'] == "178" && $_SESSION['mID'] == "551")
{
$sWhere = " AND dID = '$_SESSION[mID]'";
}
$sql = "SELECT * FROM dl_warranty_claims
INNER JOIN dealers ON (dID = wDealerID)
WHERE 1 ".$sWhere." AND wID = '$_GET[id]'";
$res = $this->SQL($sql);
if (!($row = $this->FetchArray($res)))
{
print "You do not have access to view this report.";
exit();
}
error_reporting(E_ALL ^ E_NOTICE);
// Read the template file
$inputFileType = 'Excel2007';
$inputFileName = './templates/warrantyclaimtemplate2.xlsx';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
// Adding data to the template
$objPHPExcel->getActiveSheet()->setCellValue('A3', ($row['wDealerName']));
$objPHPExcel->getActiveSheet()->setCellValue('B3', ($row['wID']));
$objPHPExcel->getActiveSheet()->setCellValue('C3', ($row['wCustomerName']));
$objPHPExcel->getActiveSheet()->setCellValue('D3', ($row['wModelName']));
$objPHPExcel->getActiveSheet()->setCellValue('E3', ($row['wChassisSN']));
$objPHPExcel->getActiveSheet()->setCellValue('F3', ($row['wEngineSN']));
$objPHPExcel->getActiveSheet()->setCellValue('G3', ($row['wDateDelivery']));
$objPHPExcel->getActiveSheet()->setCellValue('H3', ($row['wDateFailure']));
$objPHPExcel->getActiveSheet()->setCellValue('I3', ($row['wDateClaim']));
$objPHPExcel->getActiveSheet()->setCellValue('J3', ($row['wOperatingHours']));
$sql = "SELECT * FROM dl_warranty_parts
WHERE wpWarrantyClaimID = '$_GET[id]'";
$res = $this->SQL($sql);
while($rowp = $this->FetchArray($res))
{
$objPHPExcel->getActivesheet()->FromArray($rowp, NULL, 'A4');
}
// Write and save file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="warrantyclaimreport.xlsx"');
$objWriter->save('php://output');
}
}
?>

Your save statement
$objWriter->save('WarrantyClaim.xlsx');
is writing a file called WarrantyClaim.xlsx to disk (in the current working directory of your script).
Yet you have headers aying that you're going to send the output to the browser
Besides sending the correct headers for the filetype that you're writing:
Filetype Writer Content type
.xls Excel5 application/vnd.ms-excel
.xlsx Excel2007 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
saving to php://output will send the file to the browser
You also have a similar issue with your Reader: using the Excel5 Reader to read a .xlsx file when you should be using the Excel2007 Reader

For your latest question (please learn how to ask questions on SO, you don't simply edit a previous question when you have a new question, but should ask a new question)
Your $this->FetchArray() method appears to be returning both enumerated and associative data... I don't know exactly what the arguments are, but there should be some setting that allows you to specify either enumerated or associative, or a method call such as FetchAssoc() that will specifically return only an associative array

Related

Generate .xlsx file using fromArray for a big amount of data

I need to write in a .xlsx file about 111.100 rows, using fromArray() but I have a strange error
I use phpspreadsheet library
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$columnLetter = 'A';
foreach ($columnNames as $columnName) {
// Allow to access AA column if needed and more
$sheet->setCellValue($columnLetter.'1', $columnName);
$columnLetter++;
}
$i = 2; // Beginning row for active sheet
$columnLetter = 'A';
foreach ($columnValues as $columnValue) {
$sheet->fromArray(array_values($columnValue), NULL, $columnLetter.$i);
$i++;
$columnLetter++;
}
// Create your Office 2007 Excel (XLSX Format)
$writer = new Xlsx($spreadsheet);
// In this case, we want to write the file in the public directory
// e.g /var/www/project/public/my_first_excel_symfony4.xlsx
$excelFilepath = $directory . '/'.$filename.'.xlsx';
// Create the file
$writer->save($excelFilepath);
And I get the exception :
message: "Invalid cell coordinate AAAA18272"
#code: 0
#file: "./vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php"
Can you help me please ?
Excel pages are limited. The limit is huge but still limited. This is a correct filter so you can't write if there is no space for it.
Anyway you shouldnt use excel pages for such a big amount of data, you can try fragmenting it into smaller pieces, but databases should be the way to manipulate such amount of information

PHPExcel - reading row comments , text strike missing

Am trying to read excel file with PHPExcel library
https://github.com/PHPOffice/PHPExcel
however when i read row then am not able to get comments on field and strikes on text also missing .
my code is
include 'PHPExcel/IOFactory.php';
$ftype = 'Excel2007';
$fname = 'data.xlsx';
$objexcel = PHPExcel_IOFactory::load($fname);
$sdata = $objexcel->getActiveSheet()->toArray(null,true,true,true);
foreach ($sdata as $k=>$d) {
print_r($d); // output
}
so it output comments and strikes which are in data.xlsx file are missing .
any idea how to display and check if row have comments and strikes through text

convert an EXCEL file to CSV file in PHP [duplicate]

This question already has answers here:
How to convert Excel XLS to CSV using PHP
(5 answers)
Closed 7 years ago.
I want to convert Excel files (.xls) into CSV file (.csv) with a script PHP ?
I tried many codes but it didn't work like this one !
No errors appear but it wont work Any idea or any other lines of codes that I can try ?
<?php
echo("it works");
require_once '../batchs/Classes/PHPExcel/IOFactory.php';
$inputFileType = 'Excel5';
$inputFileName = '../public/aixstream/stock.xls';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objWriter->setSheetIndex($sheetIndex);
$objWriter->save($loadedSheetName.'.csv');
}
?>
Thank you
As already stated in this answer, you can use the PHP-ExcelReader function to read the xls file. After that, you may easily convert it into CSV (or any other other format) using the following code, also available here.
Reading the xls file
//You will obviously need to import the function
//by downloading the file from the link above.
$reader=new Spreadsheet_Excel_Reader(); //Instantiate the function
$reader->setUTFEncoder('iconv'); // Set Encoder
$reader->setOutputEncoding('UTF-8'); // Set Output Encoding Type
$reader->read($filename); // Read the xls file
Data Output
/***
* Information about sheets is stored in boundsheets variable.
* This code displays each sheet's name.
***/
foreach ($reader->boundsheets as $k=>$sheet) //Run loop for all sheets in the file
{
echo "\n$k: $sheet";
}
//Now just save the data in the array as csv
/***
* Data of the sheets is stored in sheets variable.
* For every sheet, a two dimensional array holding table is created.
* This code saves all data to CSV file.
***/
foreach($reader->sheets as $k=>$data) // Run loop for all items.
{
echo "\n\n ".$reader->boundsheets[$k]."\n\n"; //Print Title
foreach($data['cells'] as $row) // Loop for all items
{
foreach($row as $cell) // Loop for every cell
{
echo "$cell".","; //Add a comma after each value
}
}
}
//It works! :D

is it possible to import and export excel file with size 70MB using PHPExcel library?

I have one excel file with 3 columns in which 2nd column contains email hyper-link. So I have to import this file and export it with only 2 columns first one should contains name and second one email means I have to split that hyper-link into name and email.
For 31MB file I changed memory limit to 2048MB and execution time 1200 in php.ini file. I can successfully imported and exported excel file of 31MB but while exporting 70MB file execution takes so much time and gives the following error message.
Fatal error: Allowed memory size of 2147483648 bytes exhausted (tried to allocate 15667514 bytes) in /var/www/html/PHPExcel/Reader/Excel2007.php on line 327
Is it possible to import and export excel file with size 70MB using PHPExcel library? And what I have to change like memory limit and max execution time etc in php.ini file.
require "PHPExcel.php";
require "PHPExcel/IOFactory.php";
$inputFileName = 'xxx.xlsx';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$outputObj = new PHPExcel();
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$outputObj->setActiveSheetIndex(0);
$outSheet = $outputObj->getActiveSheet();
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++){ // As row 1 seems to be header
// Read cell B2, B3, etc.
$line = $sheet->getCell('B' . $row)->getValue();
preg_match("|([^\.]+)\ <([^>]+)>|", $line, $data);
if(!empty($data))
{
// $data[1] will be name & $data[2] will be email
$outSheet->setCellValue('A' . $row, $data[1]);
$outSheet->setCellValue('B' . $row, $data[2]);
}
}
$objWriter = new PHPExcel_Writer_CSV($outputObj);
$objWriter->save("xxx.csv");
NOTE: Can I export excel file without making any changes in php.ini file
I got solution. Successfully I have done this task in python. Hopefully it will help someone. :)
# Time taken 2min 4sec for 69.9MB file.
import csv
import re
from openpyxl import Workbook, load_workbook
location = 'big.xlsx'
wb = load_workbook(filename=location, read_only=True)
users_data = []
# pattern = '^(.+?) <([^>].+)>$' # matches "your name <email#email.com>"
# pattern_new = '^(.+?)<([^>].+)>$' # matches "your name<email#email.com>"
# pattern_email = '([\w.-]+#[\w.-]+)' # extracts email from sentence
# Define patterns to check on string.
patterns = ['^(.+?) <([^>].+)>$', '^(.+?)<([^>].+)>$']
# Loop through all sheets in XLSX
for wsheet in wb.get_sheet_names():
# Load data from Sheet.
ws = wb.get_sheet_by_name(wsheet)
# Loop through each row in current Sheet.
for row in ws.rows:
# We need column B data, so get that directly.
# Check if its not empty.
if row[1].value:
val = ""
# Get column B data, remove unnecessary data and encode using utf-8 format.
data = row[1].value.replace("(at)", "#").replace("(dot)", ".").encode('utf-8')
# Loop through all patterns to match in current data.
for pattern in patterns:
# Apply regex on data.
name_data = re.search(pattern, data)
# If match found.
if name_data:
# Create list of matched data and break loop to avoid extra searches on current row.
val = [name_data.group(1), name_data.group(2)]
# val = name_data.group()
break
# If no matches found, check for only email, if not then use data as it is.
if not val:
# val = data
name_data = re.search('([\w.-]+#[\w.-]+)', data)
# If match found, then use that, else use data.
if name_data:
val = [name_data.group(1)]
else:
val = data
# Append new data to users_data array.
users_data.append(val)
# Open CSV file for writting list.
myfile = open('big.csv', 'wb')
# Open file in write mode.
wr = csv.writer(myfile, dialect='excel', delimiter = ',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
# Loop through each value in list.
for word in users_data:
# Append data in CSV.
wr.writerow([word])
# Close CSV file.
myfile.close()
#Priyanka, you can also try using Spout: https://github.com/box/spout. It works great for large files! You won't have to change your php.ini file, as it won't require more than 10MB of memory and should finish before the default time limit.
You can do something like this:
$filePath = 'xxx.xlsx';
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($filePath);
$writer = WriterFactory::create(Type::CSV);
$writer->openToFile($'xxx.csv');
$rowCount = 0;
while ($reader->hasNextSheet()) {
$reader->nextSheet();
while ($reader->hasNextRow()) {
$row = $reader->nextRow();
$rowCount++;
if ($rowCount === 1) {
continue; // that's for the header row
}
// get the values you need in the current row
// for example:
$name = $row[1];
$email = $row[2];
// write the data to the CSV file
$writer->addRow([$name, $email]);
}
}
$reader->close();
$writer->close();
Give it a try! Hopefully it will solve your problem :)
I don't see the point in loading one spreadsheet file, copying everything from that to a second, then saving the second.... that will be memory and performance intensive
why not just load the first, delete your heading row 1, then save to your CSV output
// Read the original spreadsheet
$inputFileName = 'TraiDBDump.xlsx';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
// Remove header row
$objPHPExcel->getSheet(0)->removeRow(1, 1);
// Save as a csv file
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->save("TraiDBDump.csv");
If your original has a lot of columns, and you only need A and B, then you could use a read filter to read only those two columns

PHPExcel - Existing array functions get converted into normal functions?

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.

Categories