I have written an Export script that will export data from my database as a CSV or XLS file. The data from the database needs to be manipulated first. So far I have the CSV file working and am now trying to convert this CSV string to XLS. I want to use phpExcel but get the below error. Can anyone assist?
Fatal error: Class 'PHPExcel_Exception' not found in /var/www/leanne/api/library/PHPExcel/Exception.php on line 36
Code which is causing the error, all worked fine until I added the XLS stuff:
if($format == 'csv'){
//create and write to file for CSV
if(file_exists($file_location . $filename)){
unlink($file_location . $filename);
}
$fh = fopen($file_location . $filename , 'a');
fwrite($fh, $csv);
fclose($fh);
} else if($format == 'xls'){
//wite to file for XLS
include '../library/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('CSV');
$objReader->setDelimiter($separator);
$objReader->setEnclosure(" ");
$objReader->setLineEnding($endrow);
$objPHPExcel = $objReader->load($csv);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save($file_location . $filename);
}
NB: csv is a string containing comma separated and double quoted fields from the database. The lines end with '\n'.
Ive downloaded the files again and started from scratch and its working. Must have been something silly I had done, sorry for wasting your time and thanks for the help.
Related
I use PHPExcel library from here to create an excel file extension .xlsx
for that i use php and mysql the data of this excel file is from mysql database.
After i create the code i receive this message:
Excel can't open the file because the file format or file extension is
not valid. Verify that the file has not been corrupted and that the
file extension matches the format of the file
To solve this problem i use:
ob_start(); ob_end_clean();
After that i download the file and try to open the excel file i have this message:
We found a problem with some content in your file.Do you want to us to
try to recover as much as we can?if you trust the source of this
workbook,click yes.
When i click yes i have this message:
Excel completed file level validation and repair. Some parts of this
workbook may have been repaired or discarded.
I click close the excel file open but inside this excel file i have some empty rows with my data.
This is my code to download an excel file using PHPExcel
ob_start();
include("includes/connect.php");
require_once'PHPExcel/Classes/PHPExcel.php';
//Create PHPExcel object
$excel=new PHPExcel();
//selecting active sheet
$excel->setActiveSheetIndex(0);
$row=21;
while($data=mysqli_fetch_object($query)){
$excel->getActiveSheet()->setCellvalue('A'.$row,$data->db_maid)
->setCellvalue('B'.$row,$data->db_date)
->setCellvalue('C'.$row,$data->db_client)
->setCellvalue('D'.$row,$data->db_esid)
->setCellvalue('E'.$row,$data->db_type)
->setCellvalue('F'.$row,$data->db_phone)
->setCellvalue('G'.$row,$data->db_mobile)
->setCellvalue('H'.$row,$data->db_contactperson)
->setCellvalue('I'.$row,$data->db_competetivecompany)
->setCellvalue('J'.$row,$data->db_category)
->setCellvalue('K'.$row,$data->db_process)
->setCellvalue('L'.$row,$data->db_status)
->setCellvalue('M'.$row,$data->db_rate)
->setCellvalue('N'.$row,$data->db_doc)
->setCellvalue('O'.$row,$data->nextDate)
->setCellvalue('P'.$row,$data->db_ndstatus)
->setCellvalue('Q'.$row,$data->db_pnote)
->setCellvalue('R'.$row,$data->meetingStatus)
->setCellvalue('S'.$row,$data->db_ncam)
->setCellvalue('T'.$row,$data->medit)
->setCellvalue('U'.$row,$data->name);
//incriment the row
$row++;
}
//set column width
$excel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
$excel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('O')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('P')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('Q')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('R')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('S')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('T')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('U')->setWidth(20);
//make table headers
$excel->getActiveSheet()
->setCellValue('A1','List Of Marketing')
->setCellValue('A3','#')
->setCellValue('B3','Date')
->setCellValue('C3','Client')
->setCellValue('D3','ES')
->setCellValue('E3','Type')
->setCellValue('F3','Phone')
->setCellValue('G3','Mobile')
->setCellValue('H3','Contact Person')
->setCellValue('I3','Competetive Company')
->setCellValue('J3','Categoty')
->setCellValue('K3','Process')
->setCellValue('L3','Status')
->setCellValue('M3','Rate')
->setCellValue('N3','Date Of Calling')
->setCellValue('O3','Next Date')
->setCellValue('P3','Next Date Status')
->setCellValue('K3','Phone Note')
->setCellValue('R3','Meeting Status')
->setCellValue('S3','Next Call After Meeting')
->setCellValue('T3','Edit Date')
->setCellValue('U3','Staff');
//Margin The title
$excel->getActiveSheet()->mergeCells('A1:U1');
//aligning
$excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal('center');
//styling
$excel->getActiveSheet()->getStyle('A1')->applyFromArray(
array(
'font'=>array(
'size'=>24,
)
)
);
$excel->getActiveSheet()->getStyle('A3:U3')->applyFromArray(
array(
'font'=>array(
'bold'=>true
),
'borders'=>array(
'allborders'=>array(
'style'=>PHPExcel_Style_Border::BORDER_THIN
)
)
)
);
//give border to data
$excel->getActiveSheet()->getStyle('A4:U'.($row-1))->applyFromArray(
array(
'borders'=>array(
'outline'=>array(
'style'=>PHPExcel_Style_Border::BORDER_THIN
),
'vertical'=>array(
'style'=>PHPExcel_Style_Border::BORDER_THIN
)
)
)
);
//write the result to a file
$file=PHPExcel_IOFactory::createWriter($excel,'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="marketing.xlsx"');
header('Cache-Control:max-age=0');
ob_end_clean();
//output to php output instead of filename
$file->save('php://output');
My question is How to solve this problem i don't want this message appear also i don't want to have an empty rows in my excel also ob_end_clean() is a real solution for the first message because i saw a tutorial on the internet and his code work correctly without using the ob_end_clean() or the ob_start()?
You're doing it the other way around. The only part you need to get into the buffer is $file->save("php://output");. If for any reason simply exiting after saving to output is not enough for you, delete the first ob_start(); and last line and try this:
ob_start();
$file->save("php://output");
$content = ob_get_contents();
ob_end_clean();
die($content);
Try removing
break;
in libraries/PHPExcel/Calculation/Functions.php (line 1161)
in public static function TYPE($value = NULL){}
in elseif(is_array($value)) {}
It solved my problem.
I am using fputcsv for write data. It is working fine. what i need is i need to create another sheet like any name and i need to write data on that. How to do that? Please guide. I am not familiar with this.
This is my code.
$filename = date("Y-m-d").".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$fp = fopen('php://output', 'a');
$yetToaproveFields = array('job_no'=>'Job Number',
'revisioncycle'=> 'Revision Cycle',
'version'=>'Version',
'is_approved'=>'Approved Status'
);
fputcsv($fp, $yetToaproveFields);
$notApproveArr = array();
$notApprovedValues = self::getNotApprovedJobs($_REQUEST);
foreach ($notApprovedValues as $key=>$value) {
if ($value['is_approved'] == 1)
$value['is_approved'] = 'No';
fputcsv($fp, $value);
}
fclose($fp);
CSV doesn't support multiple sheets, it's a simple text file. To use sheets, you should use an Excel extension, such as PHPExcel.
You can't.
CSV is a very simple data file format. It doesn't support spreadsheet features like styling or multiple worksheets. If you want multiple worksheets, then you need to use a spreadsheet file format like BIFF (.xls), OfficeOpenXML (.xlsx) or OASIS (.ods)
$objPHPExcel = PHPExcel_IOFactory::load("untitled.xls");
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) //loop through the 3 worksheets of KindleEditionEISBN
{
$sheet_name = $worksheet->getTitle();
if ($worksheet->getTitle = 'Records')
{
$highestColumm = $objPHPExcel->setActiveSheetIndex(0)->getHighestColumn();
$highestRow = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($highestColumm, $highestRow, $node_10);
$objWriter2007 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter2007->save('php://output');
The above is my code, I run it and the if loop works because I am getting the output but it does not do anything in my "untitled.xls" file
This code won't write anything to untitled.xls because you're saving to php://output (the screen) so the content of the file should be displayed on screen unless you're also sending headers to tell a browser to treat the output as an Excel file; and you're using the Excel2007 Writer to generate the output as an OfficeOpenXML format xlsx file rather than as a BIFF format xls file.
So are you seeing the output on screen?
I'm using this function to read rows from csv file.
<?PHP
$file_handle = fopen("test.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
echo $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>";
}
fclose($file_handle);
?>
And I'm getting this
PK!|l˜l [Content_Types].xml ¢( Ì”]KÃ0†ïÿCÉ4Ù&ˆÈº]øq©çˆÍé–&!'›Û¿÷4û#¤nzÓÐæœ÷}’4ïp¼jL¶„€ÚÙ‚õye`K§´ìmú”ß²£´Jg¡`k#6]^§k˜Q·Å‚Õ1ú;!°¬¡‘ÈK3•ŒôfÂËr.g ½Þ(`c[ 6>#%&f+ú¼! `e÷›ÂÖ«`Ò{£K‰Túæ’o8u¦¬µÇ+Â`¢Ó¡ùÙ`Û÷B[´‚l"C|– aˆ•.Ìß›óÃ"”®ªt Ê•‹†v€£ Ö±1<¼‘Úî¸ø§bi蟤]_>‘cðO8®ÿˆ#Òÿ"=$IæÈ`\À3¯v#z̹–Ôk”gøª}ˆƒîÑ$8”(Nß…]d´Ý¹'!QÃ>4º.ßÞ‘ÒètÃo·Ú¼S :¼EÊ×Ñ'ÿÿPK!µU0#õL_rels/.rels ¢(
Œ’ÏNÃ0ÆïH¼CäûênH¡¥»LH»!TÀ$îµ£$#÷ö„‚JcÛÑöçÏ?[ÞîæiTb/Nú(A±3b{×jxŸV b"giÇŽaWÝÞl_x¤”›b×û¨²‹‹º”ü#b4Oñìr¥‘0QÊahÑ“¨eÜ”å=†¿P-<ÕÁj{ª>ú<ù²·4Mox/æ}b—NŒ#ž;ËvåCf©ÏÛ¨šBËIƒóœÓÉû"cž&Ú\Oôÿ¶8q"K‰ÐHàó<ߊs#ëë.Ÿh©ø½Î<⧄áMdøaÁÅT_ÿÿPK!Þ ý(Ôxl/_rels/workbook.xml.rels ¢(
¼“ÏjÃ0ÆƒÑ}q’ne”:½ŒA¯[÷&QâÐÄ6–ö'o?“Cº#É.¡ƒ$ü}?Чýá§ïÄjU%)´¥«ZÛ(ø8½><ƒ Ö¶Ò³¨`#‚Cq·ÃNsüD¦õ$¢Š%†Ù襤Ò`¯)qmœÔ.ôšcéuyÖ Êõ’ýãšöO /îc)ÇwÚ‡œÝbñÿÿPK!«h&¨bqxl/workbook.xmlŒRËNÃ0¼#ñ–ï4©Ó·šTB€è!QÚ³‰7UÇŽl‡´ÏÆQKQ/œv×;ÏŒ³\+E¾Á:itJ‡ƒ˜Ð¹RïSú¹yy˜Qâ<ׂ+£!¥'pt•Ýß-[c_Æh—ÒÒûzE./¡ân`jи)Œ¸ÇÑî#W[à•¾R‹ãITq©iÏ°°ÿá0E!sx2ySö=‰Å=Êw¥¬Í–…T°í^×o¼BÝGE‰âÎ?éA¤tŒ£iáÏmêÇF*ÜΓ˜Ñ(»˜|·D#Áå7hïÌŽy±c“ÙE±•Ðºßº‘wRÓ¦t4ÃhOç)Á¡ ›¾L)›N稩?{¹/=Ò'É8îØ£+ú ^*ÑÁÝGê_ª«k4€½]HlìZ;†4»BcAß7èä
ýuŽ’r®rŒª+AÄhÓ8h{w†ýK’
ÇcÌxLÚÞœHïÚÖûï]Å›*$A°>–›¸í…J%›•ŠôaËËACMÒÛʈ÷¼ÆJꟉ&Mœ;žÖ4BÎe— tˆYÛ>c~4$”‡–
I have tried many other but getting the same output.
Is there any way I can get string?
Thanks in advance.
This is not a CSV file, it is a ZIP file (note the PK at the beginning).
Probably this is an xlsx file (excel in xml inside a zip package) that you either misnamed or that has the full name test.csv.xlsx but Windows is hiding your real extension (if you are on Windows).
Try to give lineseperator of your csv file like
$csvcontent = fgetcsv($handle, 1000,"\t");
where "\t" is your line seperator.and I think it is not an CSV file...either it is an Zipped file or like .xlsx extended file,First check it once
I would like to generate a csv file with data, that I get by querying a database. The browser then should prompt the user to download the file. By problem is, that the readfile function needs a filename and not a handle, but I can't find a function to get the filename of this temporary file.
I guess there are better ways to do this, but I can't find them.
$handle = tmpfile();
fputcsv($handle, array('year', 'month', 'product', 'count'));
header('Content-Type: application/csv');
header('Content-Disposition:attachment;filename=LS_export');
echo readfile($handle);
fclose($handle);
exit();
You are looking for rewind to reset the file pointer to the start of the file, followed by fpassthru to output all the contents of the file.
rewind($handle);
fpassthru($handle);
Another solution is to use tempnam to generate a unique file which is not removed when closed. Do not forget to remove it manually when you are done with it.
$name = tempnam('/tmp', 'csv');
$handle = fopen($name, 'w');
...
fclose($handle);
readfile($name);
unlink($name);
Use
$tmpfname = tempnam("/", "");
$handle = fopen($tmpfname, "w");
...
fclose($handle);
And you have the filename too.
from mysql
SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE 1
and delete it on demand
redefine separators and other param as you need