I am trying to generate excel of .txt file using PHP-spreadsheets first I am creating array of .txt data than I'll be writing .txt data into excel using php-spreadsheets my excel is getting generated but while opening that excel I am getting below error message
Excel cannot open the file because file-format or extension is not valid verify the file that it has not been corrupted and the file extension matches the format of the file
$lines = array();
$fopen = fopen('read.txt', 'r');
while (!feof($fopen)) {
$line=fgets($fopen);
$line=trim($line);
$lines[]=$line;
}
fclose($fopen);
$finalOutput = array();
foreach ($lines as $string)
{
$string = preg_replace('!\s !', ' ', $string);
$row = explode(" ", $string);
array_push($finalOutput,$row);
}
echo "<pre>";
print_r($finalOutput);
echo "</pre>";
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray($finalOutput, NULL, 'A1');
// redirect output to client browser
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
CodePudding user response:
Please delete / remark all data output statements from your script before the headers for generating the xlsx file. Remember that header() should be called before any actual output is sent. You may refer to the following link (official documentation) :
https://www.php.net/manual/en/function.header.php
(1) Hence, please remark the following 3 lines
echo "<pre>";
print_r($finalOutput);
echo "</pre>";
(2) OPTIONAL - On the other hand, for your case if there is no need to use xls and csv, tyen remark these two lines as well
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
So change to
<?php
$lines = array();
$fopen = fopen('read.txt', 'r');
while (!feof($fopen)) {
$line=fgets($fopen);
$line=trim($line);
$lines[]=$line;
}
fclose($fopen);
$finalOutput = array();
foreach ($lines as $string)
{
$string = preg_replace('!\s !', ' ', $string);
$row = explode(" ", $string);
array_push($finalOutput,$row);
}
// echo "<pre>";
// print_r($finalOutput);
// echo "</pre>";
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
//use PhpOffice\PhpSpreadsheet\Writer\Xls;
//use PhpOffice\PhpSpreadsheet\Writer\Csv;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray($finalOutput, NULL, 'A1');
// redirect output to client browser
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');