PHP_XLSXWriter and Code Igniter Corrupted Output Excel File - php

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));

Related

Excell Error when opening file generated using XLSWriter

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();
```

JasperReports Server and data collection from php to report as parameter

I want to use JasperReports with cakephp. The connection between cakephp and JasperReports Server works. It generates a header of an excel report. The problem: I want to pass data to loop on in report but I can't because I don't know how to give a data list as parameter and how to loop.
I don't want to use SQL as data source because I have a filter in the page and according to that I want to export only the data filtered by many parameters in the page.
Here's my code i use to create a report:
$c = new Jaspersoft\Client\Client(
"http://localhost:8080/jasperserver",
"jasperadmin",
"jasperadmin"
);
$info = $c->serverInfo();
$controls = array(
'Contract reference' => 'Contract Reference',
'Type' => __('Type'),
'Entity' => 'Subsidiary'
);
$report = $c->reportService()->runReport('/reports/Contrat_User', 'xlsx', null, null,$controls);
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=contratexport.xlsx');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen($report));
header('Content-Type: application/xml');
echo $report;

text file download code in php

I am a new PHP programmer. I am trying to write code to allow users to download text file from my website. I followed the answers to similar questions on this subject and put together this following test program. It did not force the download to go to a file, instead, it sent the content to the screen (in Chrome, IE, Firefox). Could someone point out what I did wrong?
Here is my test code:
<?php
$file = "test.txt";
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Send file headers
header("Content-type: $type");
header("Content-Disposition: attachment;filename=\"test.txt\"");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
readfile($file);
exit();
?>
You can simply use
$handle = fopen("file.txt", "w");
fwrite($handle, "Shadow ");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Edited , try it on single php page .
This code will display the text file content in the screen, and user can download it as a text plain file:
$file = "test.txt";
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Send file headers
header("Content-type: $type");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
echo file_get_contents($file);
But this code (by #Drop Shadow) will force browser to show download dialog without displaying anything:
$file = "test.txt";
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Send file headers
header("Content-type: $type");
header("Content-Disposition: attachment;filename=\"test.txt\"");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
readfile($file);
exit();

Downloading csv file in firefox bug

There is a download in CSV feature in my current CodeIgniter project. When a user click the link, it will download a file in CSV. The downloaded CSV file's filename is incorrect once the provided filename in the code has a question mark character. To make things clear, below is the code.
public function download($role = NULL, $id = 0, $eid = 0) {
$this->load->helper('download');
$list = $this->respondent->get_respondents($eid);
$questions = $this->respondent->get_all_questions($eid);
$fp = fopen('php://output', 'w');
$fields = array(
'Timestamp',
'First Name',
'Middle Name',
'Last Name',
);
$fields = array_merge($fields, $questions);
fputcsv($fp, $fields);
foreach ($list as $respondent) {
$respondent_data = array(
$respondent->since,
$respondent->first_name,
$respondent->middle_name,
$respondent->last_name,
);
$query = $this->respondent->get_responses($respondent->rid);
foreach($query as $response) {
array_push($respondent_data, $response->answer, $response->duration);
}
fputcsv($fp, $respondent_data);
}
$data = file_get_contents('php://output');
$name = $this->respondent->get_experiment($respondent->eid)->title.'.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
}
In the line header('Content-Disposition: attachment; filename="'.basename($name).'"');, once the $name has a question mark character, downloading the file in Firefox or Chrome browser can't interpret it correctly. Rather than a question mark character, the generated character is an underscore or hyphen, respectively. However, when Safari is used to download, the filename is just fine. Is the problem in the code or the browsers?
What I meant in my comment is this.
str_replace('?', '_', $name); //when saving file on the server
This way there is no limit for users simply every question mark is replaced with _, I guess no big deal.
The part about FF and GCH I can not answer.

PHP readfile return data

(my first question on stack, so sorry for errors and/or inaccuracies...)
So : I've developed a Wordpress Theme and I'd like my users to download the attachments of a post. So I created a Zip Archive and use a readfile(). The function is called by link and using a $_GET['zip'] test.
The Problem : readfile() returns (i mean display) binary characters like this (here I tried to download a test .png file) : �PNG IHDRp�r�*� pHYs�� OiCCPPhotoshop ICC profilexڝSgTS�=���BK���KoR
And nothing is downloaded.
Here my code (the readfile part) :
$zip = new ZipArchive();
if ($zip->open($file_path.$archive_file_name, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
foreach($file_names as $file){
$zip->addFile($file,$file);
}
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file_path.$file).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path.$file));
ob_clean();
flush();
readfile($file_path.'screenshot.png');
I don't know where to search, and it's my first time with zip archive AND readfile()...
Thanks for the tracks (? do we say that? ) !
I don't know how exactly but it works now. I added an ob_start() just at the beginning of the function. Thanks for support !
The entire function :
if (!function_exists('zipThoseFiles')) {
ob_start();
function zipThoseFiles($id){
if (!function_exists('zipFilesDownload')) {
function zipFilesDownload($file_names,$archive_file_name,$file_path){
$zip = new ZipArchive();
if ($zip->open($file_path.$archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
foreach($file_names as $file){
$zip->addFile($file,$file);
}
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file_path.$archive_file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path.$archive_file_name));
ob_end_clean();
flush();
readfile($file_path.$archive_file_name);
unlink($file_path.$archive_file_name);
exit;
}
}
$fileNames = array();
$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$fileNames[] = get_attached_file( $attachment->ID );
}
}
$zip_file_name = 'mediasArchive.zip';
$file_path = dirname(__FILE__).'/';
zipFilesDownload($fileNames,$zip_file_name,$file_path);
}
}

Categories