How to remove warning when exporting excel using PHP

12,274

Solution 1

The above answer in PHPExcel will give you fine result. But if you want to impliment it with corePHP then here is the code to impliment.

<?php

function xlsBOF() {
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
}
function xlsEOF() {
    echo pack("ss", 0x0A, 0x00);
}
function xlsWriteNumber($Row, $Col, $Value) {
    echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
    echo pack("d", $Value);
}
function xlsWriteLabel($Row, $Col, $Value) {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
} 
// prepare headers information
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"export_".date("Y-m-d").".xls\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
// start exporting
xlsBOF();
// first row 
xlsWriteLabel(0, 0, "id");
xlsWriteLabel(0, 1, "name");
xlsWriteLabel(0, 2, "email");
// second row 
xlsWriteNumber(1, 0, 230);
xlsWriteLabel(1, 1, "John");
xlsWriteLabel(1, 2, "[email protected]");
// third row 
xlsWriteNumber(2, 0, 350);
xlsWriteLabel(2, 1, "Mark");
xlsWriteLabel(2, 2, "[email protected]");
// end exporting
xlsEOF();
exit;

?>

Reference from http://krasimirtsonev.com/blog/article/php-export-mysql-data-to-xls-file

Solution 2

You are probably saving CSV file with XLS extension. Change Content-type to text/csv and file extension to .csv, it opens by default in Excel and should prevent displaying this warning.

Share:
12,274
Paengski
Author by

Paengski

Updated on June 05, 2022

Comments

  • Paengski
    Paengski almost 2 years

    Could anyone help me on how to remove this warning when I export Excel using PHP.

    "The file you are trying to open 'MyFile.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. Do you want to open the file now?"

    I completely understand the warning, saying that the Excel content has a different format. I just want to know how/what to do to remove this warning

    <?php
        header("Content-type:   application/x-msexcel; charset=utf-8");
        header("Content-Disposition: attachment; filename=MyFile.xls");
    ?>
    

    Right now I only have the above codes, meaning no display yet, I'm trying to fix first this problem before populating any content. The current version installed is MS Office 2007. I want to try PHPExcel, however I'm not sure if it can fix the issue.

    Thanks in advance!