Add another sheet to excel export from PHP - 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.

Related

How to give path to the file?

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.

PHP DOMDocument Not Working As Expected

So I'm trying to use the PHP DOMDocument extension to write a XML document. I have all my code written up, but the only node that appears in the new XML file is the XML header.
Here is the code:
//vars
$history_location="w1/history_files/" . md5($time) . md5(rand(0,1000)) . rand(0,1000) . '.xml';
$id=2;
$airline="Aero Test Ltd.";
$aircraft="Boeing 747-400";
$engine="Rolls-Royce RB211-524H2-T";
$f=5;
$c=25;
$yp=40;
$y=560;
//xml history file
$xml=new DOMDocument();
$xml->formatOutput=true;
//tags
$tag_history=$xml->createElement("history");
$tag_preface=$xml->createElement("preface");
$tag_l1=$xml->createElement("l1", "This is the history file for aircraft " . $id . ".");
$tag_l2=$xml->createElement("l2", "Generated: " . date("F d Y H:i:s", $time) . ".");
$tag_l3=$xml->createElement("l3", "Last Updated: " . date("F d Y H:i:s", $time) . ".");
$tag_body=$xml->createElement("body");
$tag_item=$xml->createElement("item");
$tag_airline=$xml->createElement("airline", $airline);
$tag_aircraft=$xml->createElement("aircraft", $aircraft);
$tag_engine=$xml->createElement("engine", $engine2);
$tag_config=$xml->createElement("config", $f . $c . $yp . $y);
//attr
$attr_name=$xml->createAttribute("name");
$attr_name->value="purchase";
$attr_date=$xml->createAttribute("date");
$attr_date->value=date("F d Y H:i:s", $time);
//sort
$tag_history->appendChild($tag_preface);
$tag_preface->appendChild($tag_l1);
$tag_preface->appendChild($tag_l2);
$tag_preface->appendChild($tag_l3);
$tag_history->appendChild($tag_body);
$tag_body->appendChild($tag_item);
$tag_item->appendChild($attr_name);
$tag_item->appendChild($attr_date);
$tag_item->appendChild($tag_airline);
$tag_item->appendChild($tag_aircraft);
$tag_item->appendChild($tag_engine);
$tag_item->appendChild($tag_config);
//save
$xml->save($history_location);
And all that is saved to the file is <?xml version="1.0"?>.
I've looked through all sorts of documentation, SO questions, and pages of Google searches and have found nothing that explains or solves the problem.
What exactly is going on and what did I screw up to cause the problem?
Thanks in advance,
~Hom
You're missing this before the save() call:
$xml->appendChild($tag_history);

strange symbol in RecursiveIteratorIterator

Hello I have Problem While I Listing Files in folder named upload, When There's arabic file It show ��� ����� ������
$target = "upload";
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($target));
while($it->valid()) {
if (!$it->isDot()) {
$nom=$nom+1;
echo $it->getSubPathName();
echo '<tr align="center"><td> Play </td><td>' . $it->getSubPathName() . '</td><td>' . $nom . '</td></tr>'; } }
First, convert the text to UTF-8:
iconv('CP1256', 'UTF-8', $it->getSubPathName());
Then, ensure that the web browser properly decodes the page as UTF-8. Put this as the top of your PHP file:
<?php
header("Content-Type: text/html; charset=UTF-8");
// The rest of the code

PDF to print iteration in PHP

Can anyone tell me if it's possible to iterate over an array of SimpleXML objects that contain PDF data and have each print to separate PDF files? I've been fighting with this for over a week now. My latest loop code is as follows:
foreach($xml->DocumentPDFs->DocumentPDF->PDFBytes as $PDFBytes => $value) {
$binary = base64_decode($value);
file_put_contents($xml->EnvelopeStatus->EnvelopeID . "/" . $xml->EnvelopeStatus->DocumentStatuses->DocumentStatus->Name . ".pdf", $binary,FILE_APPEND);
}
This prints out the first PDF and then exits the loop.
So it turns out it was syntax issues. Both in the base64_decode call and the file_put_contents call:
foreach($xml->DocumentPDFs->DocumentPDF as $value) {
$binary = base64_decode($value->PDFBytes);
file_put_contents($xml->EnvelopeStatus->EnvelopeID . "/" . $value->Name . ".pdf", $binary);
}
So there you go.

How do I extract from WordPress database to MS Excel?

I am trying to add data into excel file which is extracted from wordpress database, Actually I am trying to export data (tags) from database into excel file. And I write down a code, but when I click on generate button. This generates empty file.
Please guys check what I am doing wrong.
Codes are below:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
if ( $count > 0 )
{
echo 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
echo $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
echo $xls_file;
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
exit();
}
The above codes are not writing data into excel file. please check and let me know.
Just based on your existing code:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
$xls_file = '';
if ( $count > 0 )
{
$xls_file .= 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
$xls_file .= $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
echo $xls_file;
exit();
}
A more general suggestion, not a solution for your coding problem: create an HTML table file from the code and then open it in Excel for conversion. Doing it so you'll have a better understand on what's going on with your code: you can add var_dumps or simply debug it like a normal web page.
Having an html table is also useful because excel works quite well in converting it to XLS files.
After your HTML file works well, then you can apply necessary formatting/header to the code in order to create the xls file from scratch.

Categories