Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

After exporting xls using php when i open excel file it shows the message as 'different format'

i am using php to export excel (.xls) file. After exporting the particular file,

when i open the file means it says "

**The file you are trying to open,

'file.xls',is in a different format than specified by the file extension.

Verify that the file is not corrupted and is from a trusted source

before opening the file**

".

This is my code.

  $data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
    array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
  );   


  function cleanData(&$str)
      {
        $str = preg_replace("/\t/", "\\t", $str);
        $str = preg_replace("/\r?\n/", "\\n", $str);
        if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
      } 

      // filename for download
      $filename = $formname."_".$form_id."_". date('Ymd') . ".xls";

      header("Content-Disposition: attachment; filename=\"$filename\"");
      header("Content-Type: application/vnd.ms-excel");

      $flag = false;
      foreach($data as $row) {
        if(!$flag) {
          // display field/column names as first row
          //echo implode("\t", array_keys($row)) . "\r\n";
          $flag = true;
        }
        array_walk($row, 'cleanData');
        echo implode("\t", array_values($row)) . "\r\n";
      }
      exit;

Upvotes: -1

Views: 1453

Answers (2)

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

You're not creating XLS files, you're creating a tab-delimited text file. That's why Excel complains that the file ending does not correspond with the file content.

To create real XLS files, you'd need a library that's able to write these kind of files (there are libraries out there that can write the old Excel XLS format, the Excel XML (2003) format and the new Excel XLSX format).

Upvotes: 1

Victor York
Victor York

Reputation: 1681

Are you creating Excel 2007 files?

If so try using mimetype application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and file extension .xslx

Upvotes: 0

Related Questions