How to give path to the file? - php

Hi I want to save the file in excel format in my local folder. For this I am creating an api which will be scheduled to call at every night and save the data in file every night.
My attempt is :
class SaveExcel
{
function SaveExcel()
{
}
function saveData()
{
$file_result = "";
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y h:i:s a', time());
$DB_TBLName = "location"; //MySQL Table Name
$filename = "LocationHistory(" . $date . ")"; //File Name
//create MySQL connection
$stmt = $dbConnection->prepare("Select * from $DB_TBLName");
$stmt->execute();
$columnHeader = '';
$columnHeader = "loc_id" . "\t" . "user_id" . "\t" . "address" . "\t" . "date_time" . "\t";
$setData = '';
while ($rec = $stmt->FETCH(PDO::FETCH_ASSOC)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// file_put_contents('history/' . $filename, $setData);
return ucwords($columnHeader)."\n".$setData."\n";
}
}
?>
By this I am getting the output as :
"Loc_id\tUser_id\tAddress\tDate_time\t\n\"118\"\t\"1\"\t\"19.166488899999997\"\t\"72.8510805\"\t\"16, Aarey Rd, Jay Prakash Nagar, Goregaon East, Mumbai, Maharashtra 400063, India\"\t\"2018-03-03 18:05:45\"\n\"119\"\t\"1\"\t\"19.165215999999997\"\t\"72.8509167\"\t\"MU Chambers, Jay Prakash Nagar, Goregaon West, Mumbai, Maharashtra 400063, India\"\t\"2018-03-03 18:22:14\"\n\"120\"\t\"1\"\t\"19.1651942\"\t\"72.85087469999999\"
now I want to save this data in excel format in local folder.
How can I do this?
Please help.. Thank you.
EDIT :
This code is working well.. Now I just want to give the path to the file. Now its getting saved under the project directory I want to get it saved in another directory. How Can I?
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, 'Employee');
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, 'Address');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, 'Date Time');
$rowCount++;
while($row = $stmt->FETCH(PDO::FETCH_ASSOC)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $user_name);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['address']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['date_time']);
$rowCount++;
}
$current_date = preg_replace('/\s+/', '', $date);
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$name = '/path/to/folder/xyz.xlsx';
$objWriter->save($user_name.$current_date.'.xlsx');
return 'File Saved';

What you are showing here is a TSV (tab-separated values) string, which is readable by Excel, but it's not a full Excel spreadsheet (e.g. you can't have colors etc.). This is good enough for many applications, and it can also be read by any app that reads TSVs (from Notepad++ to LibreOffice), which is an advantage.
However, if you want to create actual Excel files, it's much more difficult. There are libraries out there that do it, like this open-source one: https://github.com/PHPOffice/PhpSpreadsheet

you need to add header of type excel on your code.
$filename = date('m/d/Y h:i:s a', time());
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
application/xls work on < excel 2007. so if get error on excel, you can change that to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
in other way, PHPExcel is a good plugin to customize your output excel
hope this help you.

Related

Add another sheet to excel export from PHP

First, I have a few knowledge in PHP, and that is all I could do with my excel export (see attached code below)
It works, but I want to export that excel file with 2 more sheets, I've googled a lot but could not customize the code to insert in it, please, help me if you can
Thank you
<?php
$filename = time().".csv";
header ( 'HTTP/1.1 200 OK' );
header ( 'Date: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Last-Modified: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Content-Type: application/vnd.ms-excel') ;
header ( 'Content-Disposition: attachment;filename='.$filename);
ExportFile1($main_exce);
function ExportFile1($records) {
$do = false;
if(!empty($records)){
foreach($records as $down){
$heading = true;
foreach($down as $row) {
if($heading) {
// display field/column names as a first row
$heading = false;
if(!$do){
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
$do = true;
}
}else{
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
// $d = "\t\n\t\n\t\n";
// print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
}
exit;
?>
The reason you can't make this work is that you are not creating an Excel export here.
You're creating a plain-text, tab-delimited file. Excel can import files in that format, but it's not a true Excel file. It's a simple flat file, and as such, it doesn't support multiple worksheets, unlike a real Excel file.
If you want to solve this, you need to rewrite this code so that it outputs a file which is in the real Excel file format - it's considerably more complex than a tab-delimited text format. There are various libraries available for PHP which can help you easily create real Excel files in xlsx format. Recommendations are off-topic here but they are not hard to find using a search engine.

Error "invalid numeric value for data type numeric in...." while exporting database to excel

I've used phpspreadsheet to export data to excel.
This works fine but, sometime it gives the error as invalid numeric value for data type numeric in c:\xamp\htdocs\phpspreadsheet\vendor\phpoffice\spreadsheet\src\phpspeeadsheet\Cell\Cell.php:221
The image that I've attached is the error I get. Please help me.
session_start();
//php_spreadsheet_export.php
include 'C:/xampp/htdocs/phpspreadsheet/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
$connect = new PDO("mysql:host=localhost;dbname=IDC", "root", " ");
$school=$_SESSION['code'];
$name="name";
$query = "SELECT * FROM SCHOOL WHERE School='".$school."' AND Name!='".$name."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
if(isset($_POST["export"]))
{
$file = new Spreadsheet();
$active_sheet = $file->getActiveSheet();
$active_sheet->setCellValue('A1', 'Name');
$active_sheet->setCellValue('B1', 'Phone');
$active_sheet->setCellValue('C1', 'DOB');
$active_sheet->setCellValue('D1', 'Father');
$active_sheet->setCellValue('E1', 'Mother');
$active_sheet->setCellValue('F1', 'Address');
$active_sheet->setCellValue('G1', 'Blood');
$active_sheet->setCellValue('H1', 'Admission');
$active_sheet->setCellValue('I1', 'Photo link');
$active_sheet->setCellValue('J1', 'Class');
$active_sheet->setCellValue('K1', 'Section');
$count = 2;
foreach($result as $row)
{
$active_sheet->setCellValue('A' . $count, $row["Name"]);
$active_sheet->setCellValue('B' . $count, $row["Phone"]);
$active_sheet->setCellValue('C' . $count, $row["DOB"]);
$active_sheet->setCellValue('D' . $count, $row["Father"]);
$active_sheet->setCellValue('E' . $count, $row["Mother"]);
$active_sheet->setCellValue('F' . $count, $row["Address"]);
$active_sheet->setCellValue('G' . $count, $row["Blood"]);
$active_sheet->setCellValue('H' . $count, $row["Adm_no"]);
$active_sheet->setCellValue('I' . $count, $row["Photo_link"]);
$active_sheet->setCellValue('J' . $count, $row["Class"]);
$active_sheet->setCellValue('K' . $count, $row["Section"]);
$count = $count + 1;
}
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($file, $_POST["file_type"]);
$file_name = time() . '.' . strtolower($_POST["file_type"]);
$writer->save($file_name);
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Transfer-Encoding: Binary');
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_name);
unlink($file_name);
exit;
}
?> ```
This is the code and it works fine for all data except for this error.
I got the error solved. The error was that, the numbers had a space at the end and was not matching the data type detected by value binder. So I set the data type as string.
Here is the changed code, if it will help anyone who is facing similar trouble.
$active-sheet->setCellValueExplicit( 'B'. $count, $row["phone"],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
I got this answer from
https://phpspreadsheet.readthedocs.io/en/latest/topics/accessing-cells/

PHPExcel - Call to a member function getCacheData() on null

I am getting an error something like below when writing a file
Error: Call to a member function getCacheData() on null
File E:\websites\d3a-qa\vendor\PHPExcel\PHPExcel\Worksheet.php
Line: 2554
Line 2554:
public function garbageCollect() {
// Flush cache
$this->_cellCollection->getCacheData('A1');
I know this error is coming because $this->_cellCollection is null but I dont know why is it null. I am calling $writer->save($saving_name); where it gives this issue.
I tried doing all sort of things. From backtracing to commenting the disconnectWorksheet code. resetting the variables for PHPExcel object but nothing works.
The funny part is sometimes it works and sometimes it doesn't. There's not much documentation or answers to queries aboout PHPExcel on internet. Therefore at last I have come here so that I could get any answer or at least a hint of what needs to be done.
Thanks in Advance.
EDIT
Here's my code where I am using PHPExcel. It appears that the error is coming at $writer->save($saving_name);.
$parts is an array having several number of XLS that needs to be merged into one XLS sheet.
PS: The error comes only when heavy processing is done (or nearly 45 sheets). For smaller xls counts its working fine.
if(!empty($insertSummary)) {
$PHPExcel = new \PHPExcel();
$PHPExcel = $PHPExcel->createSheet();
$PHPExcel->setTitle(_EXPORT_DES_SUMMARY);
}
foreach ($parts as $part) {
$bigExcel = '';
if(!empty($insertSummary))
$bigExcel = $this->addSummarySheet($insertSummary, $part, $PHPExcel);
$bigExcel = $this->processPartFiles($part, $bigExcel);
$writer = \PHPExcel_IOFactory::createWriter($bigExcel, 'Excel5');
$returnFilename = $dbName . '_' . 'DES' . '_' . date('Y-m-d-h-i-s') . '_' . 'Part_' . ++$count . '.xls';
// name of file, which needs to be attached during email sending
$saving_name = _DES_PATH_WEBROOT . DS . $returnFilename;
$zipFiles[] = $saving_name;
$writer->save($saving_name);
//Log::write('debug', 'Line(' . __LINE__ .') memory_get_peak_usage - ' . memory_get_peak_usage(true));
//Log::write('debug', 'Line(' . __LINE__ .') memory_get_usage - ' . memory_get_usage());
}
EDIT-2
$this->addSummarySheet()
public function addSummarySheet($insertSummary, $part, $PHPExcel) {
$keys = array_keys($part);
$bigExcel = $this->CommonInterface->readXlsOrCsv($insertSummary, false);
//Copy & paste values of range of cells
$cellValuesTitle = $bigExcel->getActiveSheet()->rangeToArray('A1:C1');
$cellValues = $bigExcel->getActiveSheet()->rangeToArray('A' . ($keys[0] + 1) .':C' . ($keys[count($keys) - 1] + 1));
$bigExcel->removeSheetByIndex(0);
$bigExcel->addSheet($PHPExcel);
$bigExcel->getActiveSheet()->fromArray($cellValuesTitle, null, 'A1');
$bigExcel->getActiveSheet()->fromArray($cellValues, null, 'A2');
foreach($keys as $rowCount => $sheet) {
$cellCordinateRow = $rowCount + 2;
$bigExcel->getActiveSheet()->getCell('A' . $cellCordinateRow)->getHyperlink()->setUrl("sheet://'Data $sheet'!A{$cellCordinateRow}");
}
return $bigExcel;
}
$this->CommonInterface->readXlsOrCsv()
public function readXlsOrCsv($filename = null, $unlinkFile = true, $sheetnames = null) {
require_once(ROOT . DS . 'vendor' . DS . 'PHPExcel' . DS . 'PHPExcel' . DS . 'IOFactory.php');
/** Identify the type of $inputFileName **/
$inputFileType = \PHPExcel_IOFactory::identify($filename);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
if(!empty($sheetnames)) {
//$objReader->setReadDataOnly(true);
$objReader->setLoadSheetsOnly($sheetnames);
}
$objPHPExcel = $objReader->load($filename);
//$objPHPExcel = \PHPExcel_IOFactory::load($filename);
if ($unlinkFile == true)
$this->unlinkFiles($filename); // Delete The uploaded file
return $objPHPExcel;
}
I've solved the issue I was facing with PHPExcel.
I have changed removed $bigExcel = $this->CommonInterface->readXlsOrCsv($insertSummary, false); from $this->addSummarySheet() and placed it under if(!empty($insertSummary)) { as stated in EDIT 2.
Also, I have added below line of code in $this->addSummarySheet()
$PHPExcelSheet = new \PHPExcel();
$PHPExcelSheet->removeSheetByIndex(0);
$PHPExcel = new \PHPExcel();
$PHPExcel = $PHPExcel->createSheet();
$PHPExcel->setTitle(_EXPORT_DES_SUMMARY);
SO My final code in $this->addSummarySheet() becomes
public function addSummarySheet($insertSummary, $part, $PHPExcel, $summaryExcel) {
$keys = array_keys($part);
//$summaryExcel= $this->CommonInterface->readXlsOrCsv($insertSummary, false);
//Copy & paste values of range of cells
$cellValuesTitle = $summaryExcel->getActiveSheet()->rangeToArray('A1:C1');
$cellValues = $summaryExcel->getActiveSheet()->rangeToArray('A' . ($keys[0] + 1) .':C' . ($keys[count($keys) - 1] + 1));
$PHPExcelSheet = new \PHPExcel();
$PHPExcelSheet->removeSheetByIndex(0);
$PHPExcel = new \PHPExcel();
$PHPExcel = $PHPExcel->createSheet();
$PHPExcel->setTitle(_EXPORT_DES_SUMMARY);
$PHPExcelSheet->addSheet($PHPExcel);
$PHPExcelSheet->getActiveSheet()->fromArray($cellValuesTitle, null, 'A1');
$PHPExcelSheet->getActiveSheet()->fromArray($cellValues, null, 'A2');
foreach($keys as $rowCount => $sheet) {
$cellCordinateRow = $rowCount + 2;
$PHPExcelSheet->getActiveSheet()->getCell('A' . $cellCordinateRow)->getHyperlink()->setUrl("sheet://'Data $sheet'!A{$cellCordinateRow}");
}
return $PHPExcelSheet;
}
Thanks Mark for providing the $this->addSummarySheet() hint. It truly helped.

How do I export MySQL table to Excel with PHP?

I am currently developing an App for my school to record Class Cleanliness Results for each class, so I need to convert the results collated in MySQL table into Microsoft Excel using PHP, preferably also able to be opened by a Android OS Phone.
I used the following PHP code:
<?PHP
$mysqli_user = "(user)";
$mysqli_password = "(password)";
$mysqli_host = "(host)";
$mysqli_database = "(database)";
$filename = "grading_results_" . time() . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$link = mysqli_connect($mysqli_host,$mysqli_user,$mysqli_password,$mysqli_database);
$query = 'SELECT * FROM (table_name)';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)){
print implode("\t", $row) . "\n";
}
mysqli_close($link);
?>
This is how my table looks like in phpMyAdmin:
https://www.dropbox.com/s/7pr3gh06zta5d8u/Snip20150618_2.png?dl=0
This is how the Excel file looks like after I used this code to convert.
https://www.dropbox.com/s/571m9lfj64tklpc/Snip20150618_3.png?dl=0
Why is there no columns and rows? I need the Excel file to be exactly the same formatting and style as the table in phpMyAdmin. Can anyone help edit my code instead of providing me a brand new code?
Thanks in advance for your answers!
Manual
Run tour localhost and log in to phpMyAdmin
Click on your database then click on the table which you want to get
Excel.
then
then press GO button
With Code
define ("DB_HOST", "localhost");
define ("DB_USER", "root");
define ("DB_PASS","");
define ("DB_NAME","DATABASE_NAME");
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
then
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "YOUR SQL QUERY GOES HERE";
$setRec = mysql_query($setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "no matching records found";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
More About Code
SELECT id, name, email INTO OUTFILE '/tmp/ram.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE id=1
Here /tmp/ is address where u want to store the csv
<?php
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
// print your data here. note the following:
// - cells/columns are separated by tabs ("\t")
// - rows are separated by newlines ("\n")
// for example:
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>
// You can fetch the data from the database and display in the table. Then put the table in echo to get Excel file.

PhpExcel Load a dynamic template

I am trying to load an excel xlsx file template which is dynamic, I tried with the following method :
$approve_employee_id = $this->input->post('approve_employee_id');
$query = "SELECT * from employee where employee.employee_id='$approve_employee_id'";
$query = $this->db->query($query);
foreach ($query->result() as $value) {
$f_name = $value->f_name;
$s_name = $value->s_name;
$user_name = $value->user_name;
$under_score = "_";
$file_name = $user_name . $under_score . $approve_month_id . $under_score . $approve_year_name;
$folder_name = $approve_month_id . $approve_year_name;
$basedir = $_SERVER['DOCUMENT_ROOT'] . "/timesheet/files";
$this->load->library('excel');
$objPHPexcel = PHPExcel_IOFactory::load("/Applications/MAMP/htdocs/timesheet/files/un_approved/'$file_name'.xlsx");
echo 'Loading template successfull...';
$objWorksheet = $objPHPexcel->getActiveSheet();
}
How can I load the file name in a dynamic way?
The following is one of the file's name : HS103_January_2014
Look at the filename you're trying to load:
"/Applications/MAMP/htdocs/timesheet/files/un_approved/'$file_name'.xlsx"
If the value of $file_name is HS103_January_2014, then this will try to load
/Applications/MAMP/htdocs/timesheet/files/un_approved/'HS103_January_2014'.xlsx
Does it really have single quotes in the actual filename?
Use
$objPHPexcel = PHPExcel_IOFactory::load(
"/Applications/MAMP/htdocs/timesheet/files/un_approved/{$file_name}.xlsx"
);

Categories