I am using phpspreadsheet to generate excel files from my database in CodeIgniter. While I try to open the exported excel file it shows me an error:
Excel cannot open the file 'abc.xlsx' because the file format or extension is not valid. Verify that file has not been corrupted and that the file extension matches the format of the file
Here is my code:
model
public function getAllMembersSearchByFamily($term)
{
$this->db->select('*,tab_family.family_name');
$this->db->from('tab_members');
$this->db->join('tab_family', 'tab_family.family_id = tab_members.family_id');
$this->db->where('tab_members.family_id', $term);
$query = $this->db->get();
return $query->result();
}
Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require "vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Applications extends CI_Controller {
public function generatefamilyreport()
{
$output="";
$term = trim($this->input->post('searchterm'));
echo $term;
$result = $this->Family_model->getAllMembersSearchByFamily($term);
if(!empty($result))
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$i = 1;
foreach($result as $res)
{
$sheet->setCellValue('A'.$i, $res->name);
$i++;
}
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="users.xlsx"');
header('Cache-Control: max-age=0');
header('Expires: Fri, 11 Nov 2011 11:11:11 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
$writer->save('php://output');
}
}
}
view
<?php
$attributes = array('class' => 'search-form', 'id' => 'generatereport');
echo form_open('Applications/generatefamilyreport',$attributes);
?>
<input type="text" name="searchterm" id="generatereporttext" <?php if(isset($term) && !empty($term)) { ?> value="<?php echo $term;?>" <?php } ?>>
<button class="btn btn-danger" style="margin-left: 15px;">Generate Report</button>
<?php echo form_close(); ?>
I am using phpspreadsheet for the first time. Can anyone help me to fix this?? Thanks in advance!
Edit 1
This same code works when I try with inline data, that is not using the data from database. The excel file gets exported and I am able to open it.
here is the edited controller code for inline data:
public function generatefamilyreport()
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->setTitle('Simple');
$spreadsheet->setActiveSheetIndex(0)
->setCellValue('A1', 'This')
->setCellValue('B2', 'is')
->setCellValue('C1', 'a')
->setCellValue('D2', 'test.');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="simple.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
}
Related
Hello everyone in my project, I am trying to export data from database to an xlsx file but I am not getting correct data.I have attached image of data.
I am using the following code.
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$exportArray = array();
$query = mysqli_query($conn, "select * from table");
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)) {
$exportArray[$exp]['id'] = $row['id'];
$exportArray[$exp]['name'] = $row['name'];
$exportArray[$exp]['address'] = $row['address'];
$exp++;
}
}
$array = array();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'id');
$sheet->setCellValue('B1', 'name');
$sheet->setCellValue('C1', 'address');
$rowCount = 2;
foreach ($exportArray as $value) {
$sheet->setCellValue('A' . $rowCount, $value['id']);
$sheet->setCellValue('B' . $rowCount, $value['name']);
$sheet->setCellValue('C' . $rowCount, $value['address']);
$rowCount++;
}
$fileName = 'test123.xls';
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'. $fileName .'.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();
When I see the sheet data using below code
$sheetData = $sheet->toArray(null, true, true, true);
print_r($sheetData);
I am getting the right output. Everything looks fine but I don't understand, why am I getting data in wrong format in sheet?
Try This:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$conn = new mysqli("localhost","root","root","test");
$sql = "SELECT * FROM customers";
$result = $conn->query($sql);
$write_array = array();
$fileName = "excel.xlsx";
$write_array[] = array("id","name","address");
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$write_array[] = array($row["id"],$row["name"],$row["address"]);
}
}
$conn->close();
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->fromArray($write_array,NULL,'A1');
$spreadsheet->getActiveSheet()->setTitle("My Excel");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
Add this use PhpOffice\PhpSpreadsheet\IOFactory;
Now use the following code to export data in Xlsx format
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
in my case none of the above solutions worked.
I finally managed to solve it by adding this line: ob_end_clean();
just before: $writer->save('php://output');
ob_end_clean();
$writer->save('php://output');
I used phpspreadsheet to export mysql table data as XLSX format but after exporting when I import the XLSX file its not importing.the exported xlsx file data is ok.If I copy the data in another XLSX file then it works perfectly.
Thanks in advance!
<?php
require 'connect.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Program');
$sheet->setCellValue('B1', 'FormalCode');
$sheet->setCellValue('C1', 'Title');
$sql = "select * from class_routine";
$result = $conn->query($sql);
if($result->num_rows > 0){
$n = 1;
while($row = $result->fetch_assoc()){
$rowNum = $n + 1;
$sheet->setCellValue('A' .$rowNum, $row['Program']);
$sheet->setCellValue('B' .$rowNum, $row['FormalCode']);
$sheet->setCellValue('C' .$rowNum, $row['Title']);
$n++;
}
}
$filename = 'ClassRoutine-template-'.time().'.xlsx';
// Redirect output to a client's web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
Full Code Here https://pastebin.com/imP2QdLm
Giving this warnings when importing the exported xlsx file in import page:
Warning: XMLReader::open(): Empty string supplied as input in C:\xampp\htdocs\corap\vendor\SpreadsheetReader_XLSX.php on line 959
Warning: XMLReader::read(): Load Data before trying to read in C:\xampp\htdocs\corap\vendor\SpreadsheetReader_XLSX.php on line 995
Warning: XMLReader::read(): Load Data before trying to read in C:\xampp\htdocs\corap\vendor\SpreadsheetReader_XLSX.php on line 995
I am trying to fetch records from a database and then download these records as an excel sheet. It downloads but when I open the excel sheet, I see html codes and some gibberish. I don't even see the records at all. I don't know where the problem is coming from. Here is my php code:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$res = $call->fetchRecords();
$num = $res->num_rows;
if($num > 0){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('records');
$i = 1;
while($row = mysqli_fetch_assoc($res)){
$sheet->setCellValue('A'.$i, $row['date']);
$sheet->setCellValue('B'.$i, $row['Reference']);
$sheet->setCellValue('C'.$i, $row['amount']);
$i++;
}
$writer = new Xlsx($spreadsheet);
if(isset($writer)){
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="pending_transactions.xlsx"');
header('Cache-Control: max-age=0');
header('Content-Transfer-Encoding: binary');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
$writer->save('php://output');
}
}
Im using PhpSpreadsheet to generate XLS files, all the functions work perfect except that it saves local files in temporary directories and I want to save them in a specific folder.
use PhpOffice\PhpSpreadsheet\IOFactory;
require __DIR__ . '/Header.php';
$spreadsheet = require __DIR__ . '/templates/MyTemplate.php';
$filename = $helper->getFilename("MyFilename", 'xls');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$callStartTime = microtime(true);
$writer->save($filename);
$helper->logWrite($writer, $filename, $callStartTime);
But the output is located in
Write Xls format to /var/folders/pn/lyj970q90lq20mjv39bpgx_80000gn/T/phpspreadsheet/MyFilename.xls in 0.0640 seconds
Is there an other function to set the saving directory I want the files in?
Use dot in path
$writer->save("./templates/MyFilename.xls");
On this line:
$filename = $helper->getFilename("MyFilename", 'xls');
Change to:
$filename = basename($helper->getFilename("MyFilename", 'xls'));
This way, $filename will only contain the file name. Then you can insert your path and make it work as you want, as I did with mine:
$writer->save('C:/xampp/htdocs/tmp/' . $outputFileName);
Make sure these lines are commented out. Since this parameter will tell the server to export Xlsx as downloadable file. Not in specific custom location.
// Redirect output to a client’s web browser (Xlsx)
// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// header('Content-Disposition: attachment;filename="'.$FileName.'"');
// header('Cache-Control: max-age=0');
// // If you're serving to IE 9, then the following may be needed
// header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
// header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
// header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
// header('Pragma: public'); // HTTP/1.0
And finally you can save your file :
$writer->save("Location/Of/YourFolder".$YourFileName);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
source
https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#redirect-output-to-a-clients-web-browser
DevelopersI am using Yii1 and I want to generate a report using PHPExcel extension but my file is not ready to download, instead it appears in console. I also set headers but still file is not ready for download. I can't find exact answer. please resolve my problem
public function GenerateReport($dataProvider)
{
$phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.Classes');
include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
$objPHPExcel = new PHPExcel();
$fileName = 'report-'.uniqid().'.xlsx';
$objPHPExcel->getProperties()->setCreator("Palash Gupta");
$objPHPExcel->getProperties()->setTitle($fileName);
$objPHPExcel->getProperties()->setSubject("Placement Student List");
$objPHPExcel->getProperties()->setDescription("Placement Student List");
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, 'Name');
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, 'Course');
$rowCount = 2;
foreach ($dataProvider->getData() as $data)
{
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $data['sd_fname']);
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $data['fk_mc_id']);
$rowCount++;
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
Try this:
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'. $fileName .'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Ref: https://github.com/PHPOffice/PHPExcel/blob/1.8/Examples/01simple-download-xls.php