Im trying to generate excell file using XLS Writer on PHP, but when i tried to open it it got error "Excell Cannot Open file xxx because the format or file extension is not valid"
Below is my code i wonder what im missing
thank you for your help
$list_data = $this->product_management_model->list_of_product_report();
include_once APPPATH.'/third_party/xlsxwriter.class.php';
ini_set('display_errors', 0);
ini_set('log_errors', 0);
error_reporting(E_ALL & ~E_NOTICE);
$filename = "Merchandise Report.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$styles = array('widths'=>[3,50,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15], 'font'=>'Arial','font-size'=>10,'font-style'=>'bold', 'halign'=>'center', 'border'=>'left,right,top,bottom');
$styles2 = array( ['font'=>'Arial','font-size'=>10,'font-style'=>'bold', 'halign'=>'left', 'border'=>'left,right,top,bottom',],);
$datestring = "%d %M %Y";
$header = array(
'No'=>'integer'
);
$writer = new XLSXWriter();
$writer->setAuthor('DK System');
$writer->writeSheetHeader('Merchandise Report', $header, $styles);
$no = 1;
foreach($list_data->result() as $row)
{
$writer->writeSheetRow('Merchandise Report', [$no], $styles2);
$no++;
}
$writer->writeToStdOut();
```
Related
I'm trying to integrate [PHP_XLSXWriter] (https://github.com/mk-j/PHP_XLSXWriter) with Code Igniter
Here's my controller source code
public function ToExcel(){
include_once APPPATH.'/third_party/xlsxwriter.class.php';
$filename = "report-".date('d-m-Y-H-i-s').".xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$styles = array('widths'=>[3,20,30,40], 'font'=>'Arial','font-size'=>10,'font-style'=>'bold', 'fill'=>'#eee', 'halign'=>'center', 'border'=>'left,right,top,bottom');
$styles2 = array( ['font'=>'Arial','font-size'=>10,'font-style'=>'bold', 'fill'=>'#eee', 'halign'=>'left', 'border'=>'left,right,top,bottom','fill'=>'#ffc'],['fill'=>'#fcf'],['fill'=>'#ccf'],['fill'=>'#cff'],);
$header = array(
'No 1'=>'string',
'No 2'=>'string',
'No 3'=>'string',
'No 4'=>'string',
);
$writer = new XLSXWriter();
$writer->setAuthor('Human');
$writer->writeSheetHeader('Sheet1', $header, $styles);
for($no=1;$no<=10;$no++){
$writer->writeSheetRow('Sheet1', [$no, $no, $no, $no], $styles2);
}
$writer->writeToStdOut();
}
The Excel file are generated and downloaded successfully, but when I try to open it using Ms Excel, it says that the file was corrupted. The problem is, it turned out that there's empty single line at the source of the generated Excel file
When I delete that empty line, it can be opened without any problem
And also, if I copy that controller code to single php file (without Code Igniter involved), the script and generated Excel file worked like a charm
How do I get rid of that first empty line?
Many thanks for the help
Если вы делали AJAX запрос:
$filename = "example.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$rows = array(
array('2003','1','-50.5','2010-01-01 23:00:00','2012-12-31 23:00:00'),
array('2003','=B1', '23.5','2010-01-01 00:00:00','2012-12-31 00:00:00'),
);
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
//$writer->writeToFile('example.xlsx');
//echo $writer->writeToString();
// создаём файл
ob_start();
foreach($rows as $row)
$writer->writeSheetRow('Sheet1', $row);
$writer->writeToStdOut();
$xlsData = ob_get_contents();
ob_end_clean();
$response = array(
'status' => TRUE,
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
);
die(json_encode($response));
I have the following php script which exports a .doc file. I want to set specific page margins to the exported .doc file but nothing that I tried worked.
/*header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; Filename=".rand().".doc");
header("Expires: 0");*/
header( 'Content-Type: application/msword' );
header("Content-disposition: attachment; filename=" .date("Y-m-d").".doc");
/*
header("Content-type: application/vnd.ms-word");
header("Content-disposition: attachment; filename=" .date("Y-m-d").".rtf");
*/
$html = preg_replace('%/[^\\s]+\\.(jpg|jpeg|png|gif)%i', 'http://www.abogaciapractica.com\\0', $_POST['description']);
print "<html xmlns:v=\"urn:schemas-microsoft-com:vml\"";
print "xmlns:o=\"urn:schemas-microsoft-com:office:office\"";
print "xmlns:w=\"urn:schemas-microsoft-com:office:word\"";
print "xmlns=\"http://www.w3.org/TR/REC-html40\">";
print "<xml>
<w:WordDocument>
<w:View>Print</w:View>
<w:DoNotHyphenateCaps/>
<w:PunctuationKerning/>
<w:DrawingGridHorizontalSpacing>9.35 pt</w:DrawingGridHorizontalSpacing>
<w:DrawingGridVerticalSpacing>9.35 pt</w:DrawingGridVerticalSpacing>
</w:WordDocument>
</xml>
";
die($html);
I tried the codes that are in the following links and had no success, the page margins remained the same.
http://officeopenxml.com/WPSectionPgMar.php
https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
Thanks in advance for your time.
For future references I Update the post with the alternative solution I found using PHPword library.
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection(
array('paperSize' => 'Legal', 'marginLeft' => 2834.645669291, 'marginRight' => 1417.322834646, 'marginTop' => 2834.645669291, 'marginBottom' => 1417.322834646)
);
//$html = $_POST['description'];
$html = $_POST['description'];
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);
// Save file
// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
//$objWriter->save('test.docx');
$temp_file_uri = tempnam('', 'xyz');
$objWriter->save($temp_file_uri);
//download code
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=helloWorld.docx');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Content-Length: ' . filesize($temp_file_uri));
readfile($temp_file_uri);
unlink($temp_file_uri); // deletes the temporary file
exit;
I'm going to modify the below php script such that it downloads the database as a .pdf file rather than in a .csv format. How should I do that? Currently when this script is called, the database will be downloaded as a .csv file. The database is defined in directadmin.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'db.php';
define("tableStuff", "stuff");
define("tableUser", "user");
define("ERR", '{"status":1}');
define("INVALID", '{"status":2}');
define("rowUserId", "user_id");
define("rowRegDate", "reg_date");
define("rowStuffName", "stuff_name");
define("rowPurchaseDate", "purchase_date");
define("rowStuffCount", "stuff_count");
define("rowStuffDescription", "stuff_description");
define("rowPicUrl", "pic_url");
define("rowUserName", "user_name");
//**********************************************************************
$mysqli = mysqli_connect(DBIP, DBUN, DBPW, DBNAME);
if ($mysqli->connect_errno) {
echo ERR;
die;
}
mysqli_set_charset($mysqli, "utf8");
$result = $mysqli->query("SELECT ".rowStuffName.",".rowStuffCount.",".rowStuffDescription.",".rowPurchaseDate.",".tableStuff.".".rowRegDate.",".rowUserName." FROM " . tableStuff .",".tableUser.
" WHERE " . tableStuff.".".rowUserId . " = " . tableUser.".".rowUserId);
if ($result->num_rows > 0) {
$array = array();
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$array[] = $row;
}
header('Content-Encoding: UTF-8');
header('Content-Type: application/csv; charset=utf-8' );
header(sprintf( 'Content-Disposition: attachment; filename=stuff.csv', date( 'dmY-His' ) ) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//echo pack("CCC",0xef,0xbb,0xbf);
$title = array("نام کالا","تعداد (مقدار)","توضیحات","زمان ثبت","نام فرد ثبت کننده");
$out = fopen("php://output", 'w');
//fputs($out,"\xEF\xBB\xBF");
fputcsv($out, $title,"\t");
foreach ($array as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
} else {
echo INVALID;
}
mysqli_close($mysqli);
I am late,but i am using FPDF to generate all PDF files,It includes a built in example of making PDF with tables from CSV file,I just changed the source of CSV file.It is super easy.
I'm currently trying to make a file download in the user's browser but have so far been unable to make it happen.
I've looked at other answers on stackoverflow.com and so far haven't found anything that has solved my problem.
My process is as follows:
I create the filename and filepath, then set headers:
$date = new DateTime();
$currentDateTime = $date->format("Y-m-d H:i:s");
$filename = "{$name}_{$currentDateTime}.csv";
$filepath = $rootfull . "/{$filename}";
// Set headers
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filepath . '"');
header('Content-Length: ' . filesize($filepath));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
I then create the file and start writing to it:
// Write header
fputcsv($output, $header);
fputcsv($output, array()); // Empty line
// Write column names
$column_headers = array_keys(array_flip($columns));
foreach ($data as $row)
{
fputcsv($output, $row);
}
echo readfile($filepath);
die();
The file gets generated and written to the specified location (in this case /var/www/<project>/<filename>.csv without any indication to the user that anything has happened. No download dialog, nothing.
If anyone can spot a problem with my code or my process, please point it out and preferably suggest a better/alternative way of doing it, any help at all is welcome at this point.
If no benefit (poor mans cache) to writing to disk then maybe something like this writing to buffer:
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="dump_' . date('Ymd') . '.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$this->outputCSV($results);
exit(); //->
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);
}
?>
I am facing with strange problem while exporting my csv file on safari it is just displaying on browser instead of downloading .While same code is working with Firefox and Crome.I have searched but nothing is working for me. Please help. Here is my code-
<?php
ob_clean();
ob_start();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
function exportData() {
$fp = fopen('php://output', 'w');
fputcsv($fp, array('Market ID', 'Market Name', 'Suburb', 'State', 'Start Time', 'End Time', 'Status',"~"));
include "database.php";
$dbquery = #$_POST['query'];
$queryAllUser = $dbquery;
$resultAllUser = mysql_query($queryAllUser);
$countAllUser = mysql_num_rows($resultAllUser);
if($countAllUser > 0)
{
while($rowMarketId= mysql_fetch_assoc($resultAllUser))
{
$marketId = $rowMarketId['mrkt_id'];
$isCancel = $rowMarketId['is_cancel'];
$openning_tim = $rowMarketId['openning_time'];
$closing_tim = $rowMarketId['closing_time'];
$suburb = $rowMarketId['suburb'];
$name = $rowMarketId['name'];
$state = $rowMarketId['state'];
if($isCancel == 0)
{
$status_type = "Open";
}
else
{
$status_type = "Close";
}
$val = array();
$val[] = $marketId;
$val[] = $name;
$val[] = $suburb;
$val[] = $state;
$val[] = $openning_tim;
$val[] = $closing_tim;
$val[] = $status_type;
$val[] = "~";
fputcsv($fp, $val);
}
}
}
exportData();
?>
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' .urlencode(basename($filename)));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
Try With this Headers........ This should Work..