I followed questions on stackoverflow and ended up with the following code
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$name.'.xlsx"');
$objWriter->save('php://output');
The problem is the output file is wrong, its in Chinese (encoding probably), i want to know if there is a header for encoding or if its another problem.
Edit:
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
Excel preparation code:
$iterator = 0;
foreach (get_object_vars($temp[0]) as $key => $value){
$formattedkey = str_replace('_', ' ', $key);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($iterator, 1, $formattedkey);
$iterator++;
$fieldsnum++;
}
$rowiterator = 2;
foreach ($temp as $asset){
$coliterator = 0;
foreach (get_object_vars($asset) as $key => $value){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($coliterator, $rowiterator, utf8_encode($value));
$coliterator++;
}
$rowiterator++;
}
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 try to export data from MySQL table to CSV file, It Works Will On My Virtual Hosting But When I Upload It On Real Hosting, The Exporting Has The Issue With UTF-8, I Use The Code Below
require_once 'config.php';
$questions = questions::getAssoc("SELECT id,question FROM question");
download_csv_results($questions, 'file.csv');
exit();
function download_csv_results($questions , $name)
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename=file.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-
check=0, pre-check=0');
header('Pragma: public');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
$outstream = fopen("php://output", "wb");
fputcsv($outstream, array_keys($questions[0]));
foreach($questions as $question)
{
$id = $question['id'];
fputcsv($outstream, $question);
$answers = answers::getAssoc("SELECT name,answer,mobile FROM answer WHERE qid=$id");
foreach ($answers as $answer){
fputcsv($outstream, $answer);
}
}
fclose($outstream);
}
On Virtual Host
On Real Host
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..
I am trying to generate unique CSV files from the csv data that I have using the following loop.
$k =1;
foreach ($csv_tbl as $_csv) {
$filename = "Agent_" . $k . ".csv";
$file_path = "agents/$filename";
file_put_contents($file_path, $_csv);
if (file_exists($_csv)) {
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($_csv));
readfile($_csv);
die();
}
$k++;
}
The first file generated is perfect and only has the data it should have i.e the first csv table. The second file has both the first and the second tables this goes on for all my 21 files which means the 21st file will have all the tables.
Visual example of the first two files.
How can I prevent duplicates tables from my csv file?
As your foreach is printing duplicates , it means that your array $csv_tbl contains duplicate values, you can remove duplicate values from array using array_unqiue But also by looking at the screenshots i can see that the callid is different for every record. do your csv contain duplicates?::
$k =1;
$csv_tbl = array_unique($csv_tbl);
foreach ($csv_tbl as $_csv) {
$filename = "Agent_" . $k . ".csv";
$file_path = "agents/$filename";
file_put_contents($file_path, $_csv);
if (file_exists($_csv)) {
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($_csv));
readfile($_csv);
die();
}
$k++;
}